import os import pytest from fastapi.testclient import TestClient @pytest.fixture def client(tmp_data_dir): from imptune.main import app with TestClient(app) as c: yield c @pytest.fixture def owner(client): """The Owner the `client` fixture's cookie jar is scoped to. Triggers the session middleware (any non-/health request creates the cookie), then resolves the Owner record so tests can create Printer/Client rows directly via the ORM that the same `client` can then see over HTTP. """ from imptune.db.models import Owner from imptune.services.session import COOKIE_NAME client.get("/") return Owner.get(Owner.key == client.cookies[COOKIE_NAME]) @pytest.fixture def tmp_data_dir(tmp_path, monkeypatch): """Set DATA_DIR to a temp directory so tests don't write to /data.""" data_dir = tmp_path / "data" data_dir.mkdir() monkeypatch.setenv("DATA_DIR", str(data_dir)) # Patch config module so the app uses the temp dir import imptune.config as cfg cfg.DATA_DIR = str(data_dir) cfg.DB_PATH = str(data_dir / "imptune.db") cfg.DRIVERS_DIR = str(data_dir / "drivers") cfg.ICONS_DIR = str(data_dir / "icons") # TestClient talks plain HTTP to http://testserver, so a Secure cookie is # dropped and every request lands on a fresh Owner (~41 spurious 404s). # Tests that care about the Secure branch monkeypatch this back to True. cfg.COOKIE_SECURE = False yield data_dir # Close the test-thread's DB connection so the next test gets a fresh one # pointing to its own tmp DB (Peewee connections are thread-local). from imptune.db.database import db if not db.is_closed(): db.close()