You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何覆盖带参数的FastAPI依赖项以实现接口测试?

如何覆盖带参数的FastAPI依赖项?

我按照FastAPI官方文档的方法,尝试在测试接口时覆盖注入的数据库依赖。

我使用闭包函数build_db,通过传入数据库名来基于MongoClient构建所需的数据库实例,闭包返回的函数可被FastAPI的Depends正常使用(运行无报错,我认为该方法可行):

# app代码
def build_db(name: str):
    def get_db():
        return build_singleton_whatever(MongoClient, args....)
    return get_db

将其添加到接口定义中:

# 接口代码
@app.post("/notification/feed")
async def route_receive_notifications(db: Database = Depends(build_db("someDB"))):
    # 业务逻辑实现
    ...

最后尝试在测试中覆盖该依赖:

# pytest测试代码(test_endpoint.py)
fastapi_app.dependency_overrides[app.build_db] = lambda x: lambda: x

但依赖并未被成功覆盖,测试仍然像正常运行一样连接了生产环境的MongoClient。

因此,我想请教:如何覆盖这种在接口中传入参数的FastAPI依赖项?

我尝试过创建模拟闭包函数,但没有成功:

def mock_closure(*args):
    def get_db():
        return args
    return get_db

app.dependency_overrides[app.build_db] = mock_closure('otherDB')

我还尝试使用包含参数的相同签名进行覆盖,同样失败:

app.dependency_overrides[app.build_db("someDB")] = mock_closure('otherDB')

补充说明:我知道可以为每个数据库单独创建生成函数作为依赖,但更倾向于这种动态闭包的方式,因为它在扩展到多个数据库时更便捷,能避免编写重复代码。


内容的提问来源于stack exchange,提问作者Joe Moon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 22:25:48