import os import tempfile from pathlib import Path # Point the app at a throwaway database before any app module is imported: # a temp SQLite file, or TEST_DATABASE_URL to run the suite against Postgres. # Never point TEST_DATABASE_URL at real data: every test empties the tables. _TMP = Path(tempfile.mkdtemp(prefix="mamadachi-test-")) os.environ["DATABASE_URL"] = os.environ.get("TEST_DATABASE_URL") or f"sqlite:///{(_TMP / 'test.db').as_posix()}" os.environ["DASHBOARD_PASSWORD"] = "" os.environ["DEFAULT_TIMEZONE"] = "America/New_York" os.environ["APP_ENV"] = "development" import pytest # noqa: E402 from fastapi.testclient import TestClient # noqa: E402 from sqlalchemy import delete # noqa: E402 from app.config import get_settings # noqa: E402 from app.db import SessionLocal # noqa: E402 from app.main import app # noqa: E402 from app.models import ButtonMap, Device, DeviceReport, Event, Kind, Press, Profile # noqa: E402 from app.services.catalog import ensure_defaults # noqa: E402 from app.services.ingest import create_device # noqa: E402 @pytest.fixture(scope="session") def _app_started(): with TestClient(app) as c: # runs startup: migrations + defaults yield c @pytest.fixture def db(): s = SessionLocal() yield s s.close() @pytest.fixture(autouse=True) def clean_db(_app_started): """Every test starts from an empty log and default settings.""" with SessionLocal() as s: for model in (Press, Event, DeviceReport, Device, ButtonMap, Kind, Profile): s.execute(delete(model)) s.commit() ensure_defaults(s) settings = get_settings() saved = settings.dashboard_password yield settings.dashboard_password = saved @pytest.fixture def client(_app_started): # Fresh cookies for each test; the app itself stays started. with TestClient(app, base_url="http://testserver") as c: yield c @pytest.fixture def device(db): dev, token = create_device(db, "Test Mamadachi") return dev, token def auth(token: str) -> dict: return {"Authorization": f"Bearer {token}"}