""" V2 API Test Configuration and Fixtures Provides test fixtures for authentication, database, and API testing """ import pytest from fastapi.testclient import TestClient from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.pool import StaticPool from app.main import app from app.core.database import Base, get_db from app.core.security import create_access_token from app.models.user import User from app.models.task import Task @pytest.fixture(scope="function") def db(): """Create test database and return session""" # Create a fresh engine and session for each test engine = create_engine( "sqlite:///:memory:", connect_args={"check_same_thread": False}, poolclass=StaticPool, ) TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base.metadata.create_all(bind=engine) db = TestingSessionLocal() try: yield db finally: db.close() Base.metadata.drop_all(bind=engine) engine.dispose() @pytest.fixture(scope="function") def client(db): """Create FastAPI test client with test database""" def override_get_db(): try: yield db finally: pass app.dependency_overrides[get_db] = override_get_db with TestClient(app) as test_client: yield test_client app.dependency_overrides.clear() @pytest.fixture def test_user(db): """Create a test user""" user = User( email="test@example.com", display_name="Test User", is_active=True ) db.add(user) db.commit() db.refresh(user) return user @pytest.fixture def admin_user(db): """Create an admin user""" user = User( email="ymirliu@panjit.com.tw", display_name="Admin User", is_active=True ) db.add(user) db.commit() db.refresh(user) return user @pytest.fixture def auth_token(test_user): """Create authentication token for test user""" token_data = { "sub": str(test_user.id), "email": test_user.email } return create_access_token(token_data) @pytest.fixture def admin_token(admin_user): """Create authentication token for admin user""" token_data = { "sub": str(admin_user.id), "email": admin_user.email } return create_access_token(token_data) @pytest.fixture def test_task(db, test_user): """Create a test task""" task = Task( user_id=test_user.id, task_id="test-task-123", filename="test.pdf", file_type="application/pdf", status="pending" ) db.add(task) db.commit() db.refresh(task) return task