"""Suite on the existing Dev Postgres, database tsumugu_test. Dev and prod databases are refused. The workflow drops and recreates tsumugu_test beside tsumugu_dev. This is not a third server. """ from __future__ import annotations import os import tempfile import time import psycopg import pytest FORBIDDEN = frozenset({"tsumugu", "tsumugu_dev", "postgres", "template0", "template1"}) _name = os.environ.get("DB_NAME", "").strip().lower() if not _name.endswith("_test") or _name in FORBIDDEN: raise RuntimeError( "DB_NAME fehlt oder ist gesperrt. Die Suite nutzt auf der Dev-Postgres " "die Datenbank tsumugu_test, nicht tsumugu oder tsumugu_dev." ) os.environ["TSUMUGU_ENV"] = "development" os.environ["ALLOWED_ORIGINS"] = "http://testserver" os.environ["SEED_DEMO"] = "false" os.environ["MEDIA_ROOT"] = tempfile.mkdtemp(prefix="tsumugu-pytest-") def _reset(settings) -> None: # The suite truncates between tests while the app pool may still release # the previous request's transaction. A deadlock abort would roll back that # transaction and the next login would fail. Waiting and retrying keeps the # reset outside the product path. last_error: Exception | None = None for attempt in range(8): try: with psycopg.connect(settings.dsn(), autocommit=True) as conn: conn.execute("SET lock_timeout = '1500ms'") conn.execute( """ TRUNCATE TABLE media_operations, domain_events, auth_accounts, data_rooms RESTART IDENTITY CASCADE """ ) return except (psycopg.errors.DeadlockDetected, psycopg.errors.LockNotAvailable) as exc: last_error = exc time.sleep(0.15 * (attempt + 1)) if last_error is not None: raise last_error @pytest.fixture(scope="session") def database(): name = os.environ.get("DB_NAME", "").strip().lower() if name in FORBIDDEN or not name.endswith("_test"): pytest.fail( "DB_NAME muss auf der Dev-Postgres eine Datenbank *_test sein, " "nicht tsumugu oder tsumugu_dev." ) from app.core.settings import get_settings from app.db.migrate import migrate get_settings.cache_clear() settings = get_settings() if settings.db_name.lower() in FORBIDDEN or not settings.db_name.lower().endswith("_test"): pytest.fail("Die Test-Suite darf nicht gegen Dev- oder Prod-Datenbanken laufen.") migrate(settings) yield settings @pytest.fixture(scope="session") def client(database): from fastapi.testclient import TestClient from app.main import app with TestClient(app) as test_client: yield test_client @pytest.fixture(autouse=True) def clean(database, client): from app.api import routes routes._login_attempts.clear() client.cookies.clear() _reset(database) yield routes._login_attempts.clear() client.cookies.clear() _reset(database) @pytest.fixture def db(database, clean): with psycopg.connect(database.dsn(), row_factory=psycopg.rows.dict_row) as conn: try: yield conn finally: conn.rollback()