我正在尝试使用官方推荐的方法覆盖注入的数据库来测试我的 FastAPI 端点FastAPI文档 https://fastapi.tiangolo.com/advanced/testing-dependencies/.
我注入数据库的函数是一个闭包,它允许我通过给定数据库名称来从 MongoClient 构建任何所需的数据库,同时(我假设)仍然使用 FastAPI dependent,因为它返回闭包函数的签名。没有抛出错误,所以我认为这个方法是正确的:
# app
def build_db(name: str):
def close():
return build_singleton_whatever(MongoClient, args....)
return close
将其添加到端点:
# endpoint
@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
然而,依赖关系似乎根本没有被覆盖,测试最终会像正常执行一样使用生产数据库的 IP 创建一个 MongoClient。
So,关于覆盖在其端点中给定参数的 FastAPI 依赖项有什么想法吗?
我尝试创建一个模拟闭包函数,但没有成功:
def mock_closure(*args):
def close():
return args
return close
app.dependency_overrides[app.build_db] = mock_closure('otherDB')
我也尝试提供相同的签名,包括参数,但仍然没有成功:
app.dependency_overrides[app.build_db('someDB')] = mock_closure('otherDB')
编辑备注我也知道我可以创建一个单独的函数来创建我想要的数据库并将其用作依赖项,但我更喜欢使用这个动态版本,因为它更具可扩展性,可以在我的应用程序中使用更多数据库,并避免我基本上重复编写功能只是为了可以干净地注入它们。