-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathconftest.py
More file actions
70 lines (55 loc) · 1.92 KB
/
conftest.py
File metadata and controls
70 lines (55 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import typing
import modern_di_fastapi
import pytest
from asgi_lifespan import LifespanManager
from httpx import ASGITransport, AsyncClient
from polyfactory.factories.sqlalchemy_factory import SQLAlchemyFactory
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession
from app.application import build_app
from app.resources.db import create_sa_engine
if typing.TYPE_CHECKING:
import fastapi
import modern_di
@pytest.fixture
async def app() -> typing.AsyncIterator[fastapi.FastAPI]:
app_ = build_app()
async with LifespanManager(app_):
yield app_
@pytest.fixture
async def client(app: fastapi.FastAPI) -> typing.AsyncIterator[AsyncClient]:
async with AsyncClient(
transport=ASGITransport(app=app),
base_url="http://test",
) as client:
yield client
@pytest.fixture
async def di_container(app: fastapi.FastAPI) -> typing.AsyncIterator[modern_di.Container]:
container = modern_di_fastapi.fetch_di_container(app)
try:
yield container
finally:
await container.close_async()
@pytest.fixture
async def db_session(di_container: modern_di.Container) -> typing.AsyncIterator[AsyncSession]:
engine = create_sa_engine()
connection = await engine.connect()
transaction = await connection.begin()
await connection.begin_nested()
di_container.override(dependency_type=AsyncEngine, mock=connection)
try:
yield AsyncSession(connection, expire_on_commit=False, autoflush=False)
finally:
if connection.in_transaction():
await transaction.rollback()
await connection.close()
await engine.dispose()
di_container.reset_override()
@pytest.fixture
async def set_async_session_in_base_sqlalchemy_factory(
db_session: AsyncSession,
) -> typing.AsyncIterator[None]:
try:
SQLAlchemyFactory.__async_session__ = db_session
yield
finally:
SQLAlchemyFactory.__async_session__ = None