Files
language-llm/backend/tests/conftest.py
2026-02-12 18:45:10 +01:00

87 lines
2.6 KiB
Python

"""FluentGerman.ai — Test configuration & fixtures."""
import asyncio
from collections.abc import AsyncGenerator
import pytest
import pytest_asyncio
from httpx import ASGITransport, AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from app.config import Settings, get_settings
from app.database import Base, get_db
from app.main import app
# Use SQLite for tests (in-memory)
TEST_DATABASE_URL = "sqlite+aiosqlite:///./test.db"
def get_test_settings() -> Settings:
return Settings(
database_url=TEST_DATABASE_URL,
secret_key="test-secret-key",
llm_api_key="test-key",
admin_password="testadmin123",
)
test_engine = create_async_engine(TEST_DATABASE_URL, echo=False)
test_session = async_sessionmaker(test_engine, class_=AsyncSession, expire_on_commit=False)
async def override_get_db() -> AsyncGenerator[AsyncSession, None]:
async with test_session() as session:
yield session
app.dependency_overrides[get_db] = override_get_db
app.dependency_overrides[get_settings] = get_test_settings
@pytest_asyncio.fixture(autouse=True)
async def setup_database():
async with test_engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
yield
async with test_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
@pytest_asyncio.fixture
async def client() -> AsyncGenerator[AsyncClient, None]:
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as c:
yield c
@pytest_asyncio.fixture
async def admin_token(client: AsyncClient) -> str:
"""Create admin and return token."""
from app.auth import hash_password
from app.models import User
async with test_session() as db:
admin = User(
username="admin",
email="admin@test.com",
hashed_password=hash_password("admin123"),
is_admin=True,
)
db.add(admin)
await db.commit()
resp = await client.post("/api/auth/login", json={"username": "admin", "password": "admin123"})
return resp.json()["access_token"]
@pytest_asyncio.fixture
async def user_token(client: AsyncClient, admin_token: str) -> str:
"""Create a regular user via admin API and return their token."""
await client.post(
"/api/users/",
json={"username": "testuser", "email": "user@test.com", "password": "user123"},
headers={"Authorization": f"Bearer {admin_token}"},
)
resp = await client.post("/api/auth/login", json={"username": "testuser", "password": "user123"})
return resp.json()["access_token"]