|
| 1 | +import sys |
| 2 | +import asyncio |
| 3 | +import httpx |
| 4 | +import pytest_asyncio |
| 5 | +import pytest |
| 6 | + |
| 7 | +from typing import Any, AsyncGenerator |
| 8 | +from contextlib import asynccontextmanager |
| 9 | +from asgi_lifespan import LifespanManager |
| 10 | +from fastapi import FastAPI |
| 11 | +from sqlalchemy.pool import NullPool |
| 12 | + |
| 13 | +from config import test_connection, settings, BaseModel |
| 14 | +from config import db_connection |
| 15 | +from api_v1.routers import register_routers |
| 16 | + |
| 17 | + |
| 18 | +db_setup = test_connection( |
| 19 | + settings.test_db.url, |
| 20 | + poolclass=NullPool, |
| 21 | +) |
| 22 | + |
| 23 | + |
| 24 | +@pytest.fixture(scope='session', autouse=True) |
| 25 | +def event_loop(request): |
| 26 | + loop = asyncio.get_event_loop_policy().new_event_loop() |
| 27 | + yield loop |
| 28 | + loop.close() |
| 29 | + |
| 30 | + |
| 31 | +async def override_get_async_session(): |
| 32 | + async with db_setup.session() as session: |
| 33 | + yield session |
| 34 | + |
| 35 | + |
| 36 | +@pytest_asyncio.fixture(scope='session', autouse=True) |
| 37 | +async def app(): |
| 38 | + @asynccontextmanager |
| 39 | + async def lifespan(app: FastAPI): |
| 40 | + async with db_setup.engine.begin() as conn: |
| 41 | + await conn.run_sync(BaseModel.metadata.create_all) |
| 42 | + sys.stdout.write('alembic upgrade head') |
| 43 | + yield |
| 44 | + await conn.run_sync(BaseModel.metadata.drop_all) |
| 45 | + |
| 46 | + app = FastAPI(docs_url=None, redoc_url=None) |
| 47 | + register_routers(app=app) |
| 48 | + app.dependency_overrides[db_connection.session_geter] = override_get_async_session |
| 49 | + |
| 50 | + async with LifespanManager(app) as manager: |
| 51 | + yield manager.app |
| 52 | + |
| 53 | + |
| 54 | +@pytest_asyncio.fixture(scope='session') |
| 55 | +async def client(app: FastAPI) -> AsyncGenerator[httpx.AsyncClient, Any]: |
| 56 | + current_home = settings.CURRENT_ORIGIN |
| 57 | + current_api = settings.API_PREFIX |
| 58 | + async with httpx.AsyncClient( |
| 59 | + app=app, |
| 60 | + base_url=current_home + current_api, |
| 61 | + ) as client: |
| 62 | + yield client |
0 commit comments