41 lines
1.4 KiB
Python
41 lines
1.4 KiB
Python
"""Unit-test fixtures for repository tests against the running dev database.
|
|
|
|
Repository tests roll back every test via a nested transaction so the shared
|
|
dev database stays clean. If the compose stack is not up, the tests are skipped.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from collections.abc import AsyncIterator
|
|
|
|
import pytest
|
|
import pytest_asyncio
|
|
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
|
from sqlalchemy.pool import NullPool
|
|
|
|
_DB_URL = "postgresql+asyncpg://contract_check:contract_check@localhost:15432/contract_check"
|
|
|
|
|
|
@pytest_asyncio.fixture
|
|
async def db_session() -> AsyncIterator[AsyncSession]:
|
|
"""Open a rolled-back transaction against the dev database."""
|
|
engine = create_async_engine(_DB_URL, poolclass=NullPool)
|
|
try:
|
|
async with engine.begin() as conn:
|
|
trans = await conn.begin_nested()
|
|
factory = async_sessionmaker(
|
|
bind=conn,
|
|
expire_on_commit=False,
|
|
autoflush=False,
|
|
autocommit=False,
|
|
)
|
|
session = factory()
|
|
try:
|
|
yield session
|
|
finally:
|
|
await session.close()
|
|
await trans.rollback()
|
|
except OSError as exc:
|
|
pytest.skip(f"Postgres not reachable for repository tests: {exc}")
|
|
finally:
|
|
await engine.dispose()
|