"""Shared pytest fixtures for backend API tests.""" from __future__ import annotations import sys from pathlib import Path from typing import Iterator import pytest from fastapi import FastAPI from fastapi.testclient import TestClient from sqlalchemy import create_engine from sqlalchemy.orm import Session, sessionmaker from sqlalchemy.pool import StaticPool BACKEND_DIR = Path(__file__).resolve().parents[1] if str(BACKEND_DIR) not in sys.path: sys.path.insert(0, str(BACKEND_DIR)) from database import Base, get_db # noqa: E402 from main import websocket_progress # noqa: E402 from routers import admin, ai, auth, dashboard, export, media, projects, tasks, templates # noqa: E402 @pytest.fixture() def db_session() -> Iterator[Session]: engine = create_engine( "sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool, ) TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base.metadata.create_all(bind=engine) session = TestingSessionLocal() auth.ensure_default_admin(session) try: yield session finally: session.close() Base.metadata.drop_all(bind=engine) engine.dispose() @pytest.fixture() def app(db_session: Session) -> FastAPI: test_app = FastAPI() def override_get_db() -> Iterator[Session]: yield db_session test_app.dependency_overrides[get_db] = override_get_db test_app.include_router(auth.router) test_app.include_router(projects.router) test_app.include_router(templates.router) test_app.include_router(media.router) test_app.include_router(ai.router) test_app.include_router(export.router) test_app.include_router(dashboard.router) test_app.include_router(tasks.router) test_app.include_router(admin.router) @test_app.get("/health") def health_check() -> dict[str, str]: return {"status": "ok", "service": "SegServer"} test_app.add_api_websocket_route("/ws/progress", websocket_progress) return test_app @pytest.fixture() def client(app: FastAPI, db_session: Session) -> Iterator[TestClient]: with TestClient(app) as test_client: admin = auth.ensure_default_admin(db_session) test_client.headers.update({ "Authorization": f"Bearer {auth.create_access_token(admin)}" }) yield test_client