mirror of
https://github.com/grillazz/fastapi-sqlalchemy-asyncpg.git
synced 2026-01-17 11:40:39 +03:00
Add test database configuration and schema creation for testing
This commit is contained in:
@@ -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:
|
||||
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user