55ba9b62d6
- Use in-memory SQLite for tests to prevent conflicts - Add try/finally for robust test cleanup - Make database URL configurable via env var - Make CORS origins configurable via env var - Make SQL echo configurable via env var
34 lines
1.1 KiB
Python
34 lines
1.1 KiB
Python
import pytest
|
|
import pytest_asyncio
|
|
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
|
|
from app.database import Base, get_db
|
|
from app.main import app
|
|
from httpx import AsyncClient
|
|
|
|
TEST_DATABASE_URL = "sqlite+aiosqlite:///:memory:"
|
|
|
|
@pytest_asyncio.fixture
|
|
async def db():
|
|
engine = create_async_engine(TEST_DATABASE_URL, echo=False)
|
|
try:
|
|
async with engine.begin() as conn:
|
|
await conn.run_sync(Base.metadata.create_all)
|
|
|
|
async_session = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
|
async with async_session() as session:
|
|
yield session
|
|
finally:
|
|
async with engine.begin() as conn:
|
|
await conn.run_sync(Base.metadata.drop_all)
|
|
await engine.dispose()
|
|
|
|
@pytest_asyncio.fixture
|
|
async def client(db):
|
|
async def override_get_db():
|
|
yield db
|
|
|
|
app.dependency_overrides[get_db] = override_get_db
|
|
async with AsyncClient(app=app, base_url="http://test") as ac:
|
|
yield ac
|
|
app.dependency_overrides.clear()
|