import pytest import os from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from fastapi.testclient import TestClient # Force settings to use sqlite test database os.environ["DATABASE_URL"] = "sqlite:///./test.db" from backend.app.main import app from backend.app.core.database import get_db from backend.app.models.base import Base # Create test engine and session SQLALCHEMY_DATABASE_URL = "sqlite:///./test_api.db" engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}) TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) @pytest.fixture(scope="session", autouse=True) def setup_db(): # Drop and recreate tables Base.metadata.drop_all(bind=engine) Base.metadata.create_all(bind=engine) yield # Clean up test database file Base.metadata.drop_all(bind=engine) if os.path.exists("./test_api.db"): try: os.remove("./test_api.db") except PermissionError: pass @pytest.fixture def db_session(): connection = engine.connect() transaction = connection.begin() session = TestingSessionLocal(bind=connection) yield session session.close() transaction.rollback() connection.close() @pytest.fixture def client(db_session): def override_get_db(): try: yield db_session finally: pass app.dependency_overrides[get_db] = override_get_db with TestClient(app) as test_client: yield test_client app.dependency_overrides.clear()