FastAPI 的 dependency_overrides 如何替换依赖?
查看完整题解
参考回答
直接回答
app.dependency_overrides[原依赖] = 替代函数 可让测试忽略原依赖调用,使用可控结果。键应是注册时使用的依赖对象。
讲清原理
它修改的是应用实例上的测试配置。使用独立 app,或在测试结束用 finally 移除替换。真实逻辑也应有对应的集成测试。
例子与易错点
示例先确认生产读取值,再用替身读取测试值,移除覆盖后得到原结果,验证配置不会遗留给下一次测试。
from typing import Annotated
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
def repo_label():
return "default-repository"
@app.get("/repository")
def read_label(label: Annotated[str, Depends(repo_label)]):
return {"label": label}
with TestClient(app) as client:
assert client.get("/repository").json()["label"] == "default-repository"
app.dependency_overrides[repo_label] = lambda: "test-repository"
try:
assert client.get("/repository").json()["label"] == "test-repository"
finally:
app.dependency_overrides.pop(repo_label)
assert client.get("/repository").json()["label"] == "default-repository"
print("override verified and removed")
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。