非常游戏网
FastAPI 测试中正确覆盖依赖项 get_db 的方法

FastAPI 测试中正确覆盖依赖项 get_db 的方法

2026-05-26日常编程244154

在 FastAPI 集成测试中,需将 app.dependency_overrides[get_db] 替换为一个可调用函数(而非 fixture 本身),使其返回 db_session 实例,并确保事务回滚与会话清理,避免 422 错误和数据库污染。

在 fastapi 集成测试中,需将 `app.dependency_overrides[get_db]` 替换为一个可调用函数(而非 fixture 本身),使其返回 `db_session` 实例,并确保事务回滚与会话清理,避免 422 错误和数据库污染。

在 FastAPI 测试中,直接将 fixture(如 db_session)赋值给 app.dependency_overrides[get_db] 是无效的——因为 FastAPI 在运行时会调用该依赖项,而非直接使用其返回值。而 db_session 是 pytest fixture,仅在测试生命周期内由 pytest 管理,无法被 FastAPI 直接调用。若错误地写成 app.dependency_overrides[get_db] = db_session,FastAPI 尝试执行 db_session() 时会因缺少 connection 参数而抛出异常,最终导致接口返回 422 Unprocessable Entity。

✅ 正确做法是:定义一个包装函数(如 override_get_db),该函数内部 yield 出已初始化的 db_session 实例。此函数符合 FastAPI 依赖注入对生成器(Depends)的预期签名,且能复用现有 fixture 的事务隔离能力。

以下是推荐的完整实现方案:

import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from fastapi.testclient import TestClient

# 假设 get_db 是你的原始依赖函数,形如:
# def get_db() -> Generator[Session, None, None]:
#     db = SessionLocal()
#     try:
#         yield db
#     finally:
#         db.close()

@pytest.fixture(scope="session")
def connection():
    url = f"postgresql://{settings.DB_username}:{settings.DB_password}@{settings.DB_hostname}:{settings.DB_port}/{settings.DB_name}"
    engine = create_engine(url, connect_args={"options": "-c timezone=utc"})
    return engine.connect()

@pytest.fixture(scope="session")
def db_session(connection):
    transaction = connection.begin()
    session_factory = sessionmaker(autocommit=False, autoflush=False, bind=connection)
    session = scoped_session(session_factory)
    yield session
    # 关键:清理会话并回滚事务,防止状态残留
    session.remove()
    transaction.rollback()

@pytest.fixture(scope="module")
def client(db_session) -> Generator[TestClient, None, None]:
    def override_get_db():
        yield db_session  # ✅ 返回已实例化的 session,非 fixture 函数本身

    app.dependency_overrides[get_db] = override_get_db
    with TestClient(app) as c:
        yield c
    # ⚠️ 必须清除覆盖,避免影响其他测试模块
    app.dependency_overrides.clear()

? 关键要点说明:

  • override_get_db 是一个无参函数,内部 yield db_session —— 它不接收参数,但能访问 db_session fixture 已注入的 session 实例;
  • db_session fixture 中必须调用 session.remove(),否则 scoped_session 可能在后续测试中复用旧会话,引发连接泄漏或状态污染;
  • app.dependency_overrides.clear() 应在 yield 后执行(即 with TestClient 退出后),确保模块级覆盖不会“泄露”到其他测试;
  • 若需支持多个并发测试模块,建议将 scope="module" 升级为 scope="function" 并配合 autouse=True,进一步强化隔离性。

通过该模式,你的 TestClient 请求将无缝使用与单元测试相同的数据库会话,真正实现端到端事务回滚式集成测试。