"""Shared pytest fixtures for the newzy backend test suite. The application is pointed at a throwaway SQLite file *before* it is imported, so the module-level engine created in ``db.session`` never touches the real database. """ import os import tempfile from collections.abc import Iterator from pathlib import Path import pytest from fastapi.testclient import TestClient from sqlalchemy import Engine, create_engine, event from sqlalchemy.orm import Session, sessionmaker # --- Point the application at a temporary database before import --------- _TMP_DB_FD, _TMP_DB_PATH = tempfile.mkstemp(suffix=".db") os.close(_TMP_DB_FD) os.environ["DATABASE_URL"] = f"sqlite:///{_TMP_DB_PATH}" from db.session import get_db # noqa: E402 from main import app # noqa: E402 from models import Base # noqa: E402 def _enable_foreign_keys(dbapi_connection, _connection_record) -> None: """Mirror the FK pragma applied to the production engine (see db.session).""" cursor = dbapi_connection.cursor() cursor.execute("PRAGMA foreign_keys=ON") cursor.close() @pytest.fixture() def engine() -> Iterator[Engine]: """A fresh SQLite database per test (created and destroyed around it).""" fd, path = tempfile.mkstemp(suffix=".db") os.close(fd) test_engine = create_engine( f"sqlite:///{path}", connect_args={"check_same_thread": False} ) event.listen(test_engine, "connect", _enable_foreign_keys) Base.metadata.create_all(test_engine) try: yield test_engine finally: test_engine.dispose() Path(path).unlink(missing_ok=True) @pytest.fixture() def session(engine: Engine) -> Iterator[Session]: """A SQLAlchemy session bound to the per-test database.""" TestingSession = sessionmaker(bind=engine, autoflush=False, autocommit=False) db = TestingSession() try: yield db finally: db.close() @pytest.fixture() def client(engine: Engine) -> Iterator[TestClient]: """A FastAPI TestClient whose ``get_db`` dependency is overridden per test.""" TestingSession = sessionmaker(bind=engine, autoflush=False, autocommit=False) def override_get_db() -> Iterator[Session]: db = TestingSession() try: yield db finally: db.close() app.dependency_overrides[get_db] = override_get_db with TestClient(app) as test_client: yield test_client app.dependency_overrides.clear()