6
6
import pytest
7
7
from asgi_lifespan import LifespanManager
8
8
from httpx import ASGITransport , AsyncClient
9
- from sqlalchemy .ext .asyncio import AsyncSession
9
+ from sqlalchemy .ext .asyncio import AsyncConnection , AsyncSession
10
10
11
11
from app import ioc
12
12
from app .application import build_app
13
13
14
14
15
- @pytest .fixture
15
+ @pytest .fixture ( scope = "session" )
16
16
async def app () -> typing .AsyncIterator [fastapi .FastAPI ]:
17
17
app_ = build_app ()
18
18
async with LifespanManager (app_ ):
19
19
yield app_
20
20
21
21
22
- @pytest .fixture
22
+ @pytest .fixture ( scope = "session" )
23
23
async def client (app : fastapi .FastAPI ) -> typing .AsyncIterator [AsyncClient ]:
24
24
async with AsyncClient (
25
25
transport = ASGITransport (app = app ),
@@ -28,23 +28,32 @@ async def client(app: fastapi.FastAPI) -> typing.AsyncIterator[AsyncClient]:
28
28
yield client
29
29
30
30
31
- @pytest .fixture
31
+ @pytest .fixture ( scope = "session" )
32
32
def di_container (app : fastapi .FastAPI ) -> modern_di .Container :
33
33
return modern_di_fastapi .fetch_di_container (app )
34
34
35
35
36
- @pytest .fixture (autouse = True )
37
- async def db_session (di_container : modern_di .Container ) -> typing .AsyncIterator [AsyncSession ]:
36
+ @pytest .fixture (scope = "session" )
37
+ async def db_connection (di_container : modern_di .Container ) -> typing .AsyncIterator [AsyncConnection ]:
38
38
engine = await ioc .Dependencies .database_engine .async_resolve (di_container )
39
- connection = await engine .connect ()
40
- transaction = await connection .begin ()
41
- await connection .begin_nested ()
42
- ioc .Dependencies .database_engine .override (connection , di_container )
43
-
39
+ connection : typing .Final = await engine .connect ()
44
40
try :
45
- yield AsyncSession ( connection , expire_on_commit = False , autoflush = False )
41
+ yield connection
46
42
finally :
47
- if connection .in_transaction ():
48
- await transaction .rollback ()
49
43
await connection .close ()
50
44
await engine .dispose ()
45
+
46
+
47
+ @pytest .fixture (autouse = True )
48
+ async def db_session (
49
+ db_connection : AsyncConnection , di_container : modern_di .Container
50
+ ) -> typing .AsyncIterator [AsyncSession ]:
51
+ transaction = await db_connection .begin ()
52
+ await db_connection .begin_nested ()
53
+ ioc .Dependencies .database_engine .override (db_connection , di_container )
54
+
55
+ try :
56
+ yield AsyncSession (db_connection , expire_on_commit = False , autoflush = False )
57
+ finally :
58
+ if db_connection .in_transaction ():
59
+ await transaction .rollback ()
0 commit comments