Add test database configuration and schema creation for testing

This commit is contained in:
grillazz
2025-12-25 15:56:23 +01:00
parent f90513aab4
commit 5d34b04ca1
9 changed files with 96 additions and 17 deletions

View File

@@ -33,6 +33,8 @@ class Settings(BaseSettings):
POSTGRES_PASSWORD: str
POSTGRES_HOST: str
POSTGRES_DB: str
POSTGRES_TEST_USER: str
POSTGRES_TEST_DB: str
@computed_field
@property
@@ -80,6 +82,17 @@ class Settings(BaseSettings):
path=self.POSTGRES_DB,
)
@computed_field
@property
def test_asyncpg_url(self) -> PostgresDsn:
return MultiHostUrl.build(
scheme="postgresql+asyncpg",
username=self.POSTGRES_USER,
password=self.POSTGRES_PASSWORD,
host=self.POSTGRES_HOST,
path=self.POSTGRES_TEST_DB,
)
@computed_field
@property
def postgres_url(self) -> PostgresDsn:

View File

@@ -15,6 +15,12 @@ engine = create_async_engine(
echo=True,
)
test_engine = create_async_engine(
global_settings.test_asyncpg_url.unicode_string(),
future=True,
echo=True,
)
# expire_on_commit=False will prevent attributes from being expired
# after commit.
AsyncSessionFactory = async_sessionmaker(
@@ -23,6 +29,12 @@ AsyncSessionFactory = async_sessionmaker(
expire_on_commit=False,
)
TestAsyncSessionFactory = async_sessionmaker(
test_engine,
autoflush=False,
expire_on_commit=False,
)
# Dependency
async def get_db() -> AsyncGenerator:
@@ -38,3 +50,18 @@ async def get_db() -> AsyncGenerator:
if not isinstance(ex, ResponseValidationError):
await logger.aerror(f"Database-related error: {repr(ex)}")
raise # Re-raise to be handled by appropriate handlers
async def get_test_db() -> AsyncGenerator:
async with TestAsyncSessionFactory() as session:
try:
yield session
await session.commit()
except SQLAlchemyError:
# Re-raise SQLAlchemy errors to be handled by the global handler
raise
except Exception as ex:
# Only log actual database-related issues, not response validation
if not isinstance(ex, ResponseValidationError):
await logger.aerror(f"Database-related error: {repr(ex)}")
raise # Re-raise to be handled by appropriate handlers