[英]FastAPI: app.dependency_overrides affects other test files
我正在使用 FastAPI。 我在我的测试套件 ( pytest
) 中引入了app.dependency_overrides
来测试我的应用程序依赖项。 奇怪的是,当我在测试文件中使用它时,其他文件中的测试开始失败。 看起来app.dependency_overrides
会影响其他测试中发生的事情。
例子:
tests
├── test_1.py
└── test_2.py
test_1.py
def foo():
return "foo"
client = TestClient(app)
app.dependency_overrides[get_settings] = foo
def test_1():
response = client.get("/ping")
assert response.status_code == 200
assert response.json() == {"ping": "pong"}
test_2.py
client = TestClient(app)
def test_2():
print(app.dependency_overrides)
response = client.get("/ping")
assert response.status_code == 200
assert response.json() == {"ping": "pong"}
Output
tests/test_1.py::test_1 PASSED
tests/test_2.py::test_2 {<functools._lru_cache_wrapper object at 0x10f513cc0>: <function foo at 0x10ea34a60>}
PASSED
如您所见,在test_1.py中覆盖的依赖项正在影响test_2.py 。 该文档指出:
如果您只想在某些测试期间覆盖依赖项,您可以在测试开始时(在测试函数内部)设置覆盖并在结束时(在测试函数结束时)重置它。
我想知道这样的规则适用于模块内(即,每个测试文件都以空的app.dependency_overrides
),但不适用于模块间。 看来我错了。
有没有办法隔离app.dependency_overrides
对每个文件中所有测试的影响而不影响测试套件的其他模块? (除了在每个(!)测试函数中定义自定义app.dependency_overrides
)
在您的代码中,语句app.dependency_overrides[get_settings] = foo
会影响在评估后执行的所有测试,因为没有清理。
为了解决这个问题并以更简单的方式编写更改 FastAPI 依赖项的测试,我创建了pytest-fastapi-deps库。
像这样使用它:
def test_1(fastapi_dep):
with fastapi_dep(app).override({get_settings: foo}):
response = client.get("/ping")
assert response.status_code == 200
assert response.json() == {"ping": "pong"}
这对我有用:
@pytest.fixture(scope="module")
def admin_user():
"""This mocks the oauth authentication in that it returns a value user
instead of Depending on the actual implementation of oauthRequired
"""
app.dependency_overrides[oauthRequired] = lambda: OauthUser(
token="", profile=__MOCKED_USER
)
yield app
del app.dependency_overrides[oauthRequired]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.