89 lines
2.5 KiB
Python
89 lines
2.5 KiB
Python
"""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 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:
|
|
with psycopg.connect(settings.dsn(), autocommit=True) as conn:
|
|
conn.execute(
|
|
"""
|
|
TRUNCATE TABLE
|
|
media_operations,
|
|
domain_events,
|
|
auth_accounts,
|
|
data_rooms
|
|
RESTART IDENTITY CASCADE
|
|
"""
|
|
)
|
|
|
|
|
|
@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):
|
|
with psycopg.connect(database.dsn(), row_factory=psycopg.rows.dict_row) as conn:
|
|
yield conn
|