from collections.abc import Iterator from pathlib import Path import pytest from alembic import command from alembic.config import Config from fastapi.testclient import TestClient from sqlalchemy.orm import Session from app.config import get_settings from app.db import _session_factory, get_engine BACKEND_DIR = Path(__file__).resolve().parent.parent def _clear_caches() -> None: get_settings.cache_clear() get_engine.cache_clear() _session_factory.cache_clear() @pytest.fixture def static_dir(tmp_path): """Directory for the built frontend; empty by default (no SPA routes).""" path = tmp_path / "static" path.mkdir() return path @pytest.fixture def app_env(tmp_path, static_dir, monkeypatch) -> Iterator[None]: """Isolated settings and a migrated database for one test.""" monkeypatch.setenv("DATA_DIR", str(tmp_path / "data")) monkeypatch.setenv("STATIC_DIR", str(static_dir)) monkeypatch.setenv("ALLOWED_ORIGINS", "https://testserver") monkeypatch.delenv("INITIAL_ADMIN_USERNAME", raising=False) monkeypatch.delenv("INITIAL_ADMIN_PASSWORD", raising=False) _clear_caches() command.upgrade(Config(str(BACKEND_DIR / "alembic.ini")), "head") yield get_engine().dispose() _clear_caches() @pytest.fixture def db(app_env) -> Iterator[Session]: with _session_factory()() as session: yield session @pytest.fixture def client(app_env) -> Iterator[TestClient]: from app.main import create_app # https so that Secure cookies are sent back by the test client with TestClient(create_app(), base_url="https://testserver") as test_client: yield test_client