From 4cb0ff93c358b671802594a2ffb7f70b1354b966 Mon Sep 17 00:00:00 2001 From: Artur Shiriev Date: Mon, 28 Sep 2026 09:23:32 +0300 Subject: [PATCH] refactor: build the test session with create_session --- app/resources/db.py | 2 +- tests/conftest.py | 11 +++-------- 2 files changed, 4 insertions(+), 9 deletions(-) diff --git a/app/resources/db.py b/app/resources/db.py index 3cf5a4d..5581697 100644 --- a/app/resources/db.py +++ b/app/resources/db.py @@ -50,7 +50,7 @@ def choose_sa_engine( return primary_engine -def create_session(engine: sa.AsyncEngine) -> sa.AsyncSession: +def create_session(engine: sa.AsyncEngine | sa.AsyncConnection) -> sa.AsyncSession: # join_transaction_mode is inert in production (the session binds to an engine); when tests bind # the session to a connection already in a transaction, it makes the session own a savepoint so # the outer transaction survives commits and the per-test rollback stays clean. diff --git a/tests/conftest.py b/tests/conftest.py index d4b10b2..325d75b 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -5,16 +5,16 @@ from asgi_lifespan import LifespanManager from httpx import ASGITransport, AsyncClient from polyfactory.factories.sqlalchemy_factory import SQLAlchemyFactory -from sqlalchemy.ext.asyncio import AsyncSession from app import ioc from app.application import build_app -from app.resources.db import create_primary_sa_engine +from app.resources.db import create_primary_sa_engine, create_session if typing.TYPE_CHECKING: import fastapi import modern_di + from sqlalchemy.ext.asyncio import AsyncSession @pytest.fixture @@ -50,12 +50,7 @@ async def db_session(di_container: modern_di.Container) -> typing.AsyncIterator[ di_container.override(ioc.Dependencies.dynamic_engine, connection) try: - yield AsyncSession( - connection, - expire_on_commit=False, - autoflush=False, - join_transaction_mode="create_savepoint", - ) + yield create_session(connection) finally: if connection.in_transaction(): await transaction.rollback()