Files
p42.f-w/backend/tests/conftest.py
T
guyg1474andClaude Opus 5.5 79cbaab092 Tests: pytest-Suite für Konten, Haushalt, Kanban, Reisen und Migrationen
- backend/tests: jede Test-Funktion bekommt eine frische Datenbank;
  test_migrationen.py baut ältere Datenbank-Stände nach und prüft die
  verlustfreie Umstellung (auch zweiter Start ohne Änderung)
- requirements-dev.txt mit pytest
- Fix (von den Tests gefunden): Eine neue, leere Datenbank bekam keine
  erste Liste "Zuhause"; jetzt einmalig beim ersten Start

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 18:07:54 +02:00

51 lines
1.6 KiB
Python

"""Gemeinsame Test-Hilfen: jede Test-Funktion bekommt eine frische, leere Datenbank.
Die App liest den Datenordner beim Import; deshalb zeigt P42_DATA_DIR schon vorher auf einen
Wegwerf-Ordner. Pro Test wird db.DB_FILE auf eine neue Datei umgebogen und das Schema angelegt.
Hintergrund-Aufgaben (lifespan) laufen nicht, weil TestClient ohne "with" benutzt wird.
"""
import os
import sys
import tempfile
from pathlib import Path
os.environ["P42_DATA_DIR"] = tempfile.mkdtemp(prefix="p42-test-")
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import pytest # noqa: E402
from fastapi.testclient import TestClient # noqa: E402
from app import auth, db # noqa: E402
from app.main import app # noqa: E402
PASSWORD = "passwort123"
@pytest.fixture(autouse=True)
def fresh_db(tmp_path, monkeypatch):
monkeypatch.setattr(db, "DB_FILE", tmp_path / "p42.db")
auth._failures.clear()
db.init()
return tmp_path / "p42.db"
@pytest.fixture
def conn(fresh_db):
c = db.connect()
yield c
c.close()
@pytest.fixture
def login():
"""login("anna", admin=True) → angemeldeter TestClient mit .user (id, name)."""
def make(username: str, admin: bool = False) -> TestClient:
with db.transaction() as c:
user_id = auth._create_user(c, username, username.capitalize(), PASSWORD, admin)
client = TestClient(app)
res = client.post("/api/auth/login", json={"username": username, "password": PASSWORD})
assert res.status_code == 200, res.text
client.user = {"id": user_id, "name": username.capitalize()}
return client
return make