python runtime_error ai_generated true

值错误:依赖项'get_db'已被覆盖

ValueError: Dependency 'get_db' has already been overridden

ID: python/fastapi-dependency-override-error

其他格式: JSON · Markdown 中文 · English
80%修复率
81%置信度
0证据数
2024-06-30首次发现

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

在测试中多次覆盖同一个FastAPI依赖项

English

在测试中多次覆盖同一个FastAPI依赖项

generic

解决方案

  1. 90% 成功率 使用context manager管理依赖项覆盖
    with TestClient(app) as client:
        app.dependency_overrides[get_db] = override_get_db
        response = client.get('/')
  2. 85% 成功率 在测试fixture中清理覆盖
    @pytest.fixture
    def client():
        app.dependency_overrides = {}
        yield TestClient(app)

无效尝试

常见但无效的做法:

  1. 尝试使用不同的依赖项名称 60% 失败

    原始依赖项仍被覆盖,新名称不匹配

  2. 在每次测试前重置依赖项 40% 失败

    app.dependency_overrides是全局状态,重置可能导致测试间污染