import os import sys import pytest from fastapi.testclient import TestClient from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker # 添加项目根目录到Python路径 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) from app.main import app from app.database import Base, get_db # 使用SQLite内存数据库进行测试 SQLALCHEMY_DATABASE_URL = "sqlite:///./test.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") def db(): """获取测试数据库会话""" # 创建数据库表 Base.metadata.create_all(bind=engine) # 创建会话 db = TestingSessionLocal() try: yield db finally: db.close() # 清理:删除所有表 Base.metadata.drop_all(bind=engine) # 删除测试数据库文件 if os.path.exists("./test.db"): os.remove("./test.db") @pytest.fixture def client(db): """创建FastAPI测试客户端""" def override_get_db(): try: yield db finally: pass # 替换依赖项 app.dependency_overrides[get_db] = override_get_db # 创建测试客户端 with TestClient(app) as client: yield client # 清理:恢复原始依赖项 app.dependency_overrides = {}