Skip to content

Commit 1fe0faa

Browse files
committed
refactor: enhance database schema creation and add documentation for test database URL
1 parent 242ea2a commit 1fe0faa

2 files changed

Lines changed: 17 additions & 3 deletions

File tree

app/config.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,19 @@ def asyncpg_url(self) -> PostgresDsn:
8585
@computed_field
8686
@property
8787
def test_asyncpg_url(self) -> PostgresDsn:
88+
"""
89+
This is a computed field that generates a PostgresDsn URL for the test database using asyncpg.
90+
91+
The URL is built using the MultiHostUrl.build method, which takes the following parameters:
92+
- scheme: The scheme of the URL. In this case, it is "postgresql+asyncpg".
93+
- username: The username for the Postgres database, retrieved from the POSTGRES_USER environment variable.
94+
- password: The password for the Postgres database, retrieved from the POSTGRES_PASSWORD environment variable.
95+
- host: The host of the Postgres database, retrieved from the POSTGRES_HOST environment variable.
96+
- path: The path of the Postgres test database, retrieved from the POSTGRES_TEST_DB environment variable.
97+
98+
Returns:
99+
PostgresDsn: The constructed PostgresDsn URL for the test database with asyncpg.
100+
"""
88101
return MultiHostUrl.build(
89102
scheme="postgresql+asyncpg",
90103
username=self.POSTGRES_USER,
@@ -93,6 +106,7 @@ def test_asyncpg_url(self) -> PostgresDsn:
93106
path=self.POSTGRES_TEST_DB,
94107
)
95108

109+
96110
@computed_field
97111
@property
98112
def postgres_url(self) -> PostgresDsn:

tests/conftest.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,9 @@ def _create_db(conn) -> None:
3535
def _create_db_schema(conn) -> None:
3636
"""Create a database schema if it doesn't exist."""
3737
try:
38-
conn.execute(text("CREATE SCHEMA happy_hog"))
39-
conn.execute(text("CREATE SCHEMA shakespeare"))
38+
"""Create a database schema if it doesn't exist."""
39+
conn.execute(text("CREATE SCHEMA IF NOT EXISTS happy_hog"))
40+
conn.execute(text("CREATE SCHEMA IF NOT EXISTS shakespeare"))
4041
except ProgrammingError:
4142
# This might be raised by databases that don't support `IF NOT EXISTS`
4243
# and the schema already exists. You can choose to ignore it.
@@ -54,7 +55,6 @@ async def start_db():
5455

5556
# Now, connect to the newly created `testdb` with `test_engine`
5657
async with test_engine.begin() as conn:
57-
5858
await conn.run_sync(_create_db_schema)
5959
await conn.run_sync(Base.metadata.drop_all)
6060
await conn.run_sync(Base.metadata.create_all)

0 commit comments

Comments
 (0)