Skip to content

Commit 0ffb4dc

Browse files
authored
refactor: build the test session with create_session (#75)
1 parent 6f351b6 commit 0ffb4dc

2 files changed

Lines changed: 4 additions & 9 deletions

File tree

‎app/resources/db.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def choose_sa_engine(
5050
return primary_engine
5151

5252

53-
def create_session(engine: sa.AsyncEngine) -> sa.AsyncSession:
53+
def create_session(engine: sa.AsyncEngine | sa.AsyncConnection) -> sa.AsyncSession:
5454
# join_transaction_mode is inert in production (the session binds to an engine); when tests bind
5555
# the session to a connection already in a transaction, it makes the session own a savepoint so
5656
# the outer transaction survives commits and the per-test rollback stays clean.

‎tests/conftest.py‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,16 @@
55
from asgi_lifespan import LifespanManager
66
from httpx import ASGITransport, AsyncClient
77
from polyfactory.factories.sqlalchemy_factory import SQLAlchemyFactory
8-
from sqlalchemy.ext.asyncio import AsyncSession
98

109
from app import ioc
1110
from app.application import build_app
12-
from app.resources.db import create_primary_sa_engine
11+
from app.resources.db import create_primary_sa_engine, create_session
1312

1413

1514
if typing.TYPE_CHECKING:
1615
import fastapi
1716
import modern_di
17+
from sqlalchemy.ext.asyncio import AsyncSession
1818

1919

2020
@pytest.fixture
@@ -50,12 +50,7 @@ async def db_session(di_container: modern_di.Container) -> typing.AsyncIterator[
5050
di_container.override(ioc.Dependencies.dynamic_engine, connection)
5151

5252
try:
53-
yield AsyncSession(
54-
connection,
55-
expire_on_commit=False,
56-
autoflush=False,
57-
join_transaction_mode="create_savepoint",
58-
)
53+
yield create_session(connection)
5954
finally:
6055
if connection.in_transaction():
6156
await transaction.rollback()

0 commit comments

Comments
 (0)