I have this small MCVE FastAPI application which works fine as expected:
# run.py
import uvicorn
from fastapi import FastAPI, Depends
app = FastAPI()
###########
def dep_with_arg(inp):
def sub_dep():
return inp
return sub_dep
@app.get("/a")
def a(v: str = Depends(dep_with_arg("a"))):
return v
###########
def dep_without_arg():
return "b"
@app.get("/b")
def b(v: str = Depends(dep_without_arg)):
return v
###########
def main():
uvicorn.run(
"run:app",
host="0.0.0.0",
reload=True,
port=8000,
workers=1
)
if __name__ == "__main__":
main()
notice the difference between the dependencies of the /a
and /b
endpoints. in the /a
endpoint, I have created a dependency that accepts an argument. both endpoints are working as expected when I call them.
I now try to test the endpoints while overriding the dependencies as below:
from run import app, dep_without_arg, dep_with_arg
from starlette.testclient import TestClient
def test_b():
def dep_override_for_dep_without_arg():
return "bbb"
test_client = TestClient(app=app)
test_client.app.dependency_overrides[dep_without_arg] = dep_override_for_dep_without_arg
resp = test_client.get("/b")
resp_json = resp.json()
assert resp_json == "bbb"
###########
def test_a_method_1():
def dep_override_for_dep_with_arg(inp):
def sub_dep():
return "aaa"
return sub_dep
test_client = TestClient(app=app)
test_client.app.dependency_overrides[dep_with_arg] = dep_override_for_dep_with_arg
resp = test_client.get(
"/a",
)
resp_json = resp.json()
assert resp_json == "aaa"
def test_a_method_2():
def dep_override_for_dep_with_arg(inp):
return "aaa"
test_client = TestClient(app=app)
test_client.app.dependency_overrides[dep_with_arg] = dep_override_for_dep_with_arg
resp = test_client.get(
"/a",
)
resp_json = resp.json()
assert resp_json == "aaa"
def test_a_method_3():
def dep_override_for_dep_with_arg(inp):
return "aaa"
test_client = TestClient(app=app)
test_client.app.dependency_overrides[dep_with_arg] = dep_override_for_dep_with_arg("aaa")
resp = test_client.get(
"/a",
)
resp_json = resp.json()
assert resp_json == "aaa"
def test_a_method_4():
def dep_override_for_dep_with_arg():
return "aaa"
test_client = TestClient(app=app)
test_client.app.dependency_overrides[dep_with_arg] = dep_override_for_dep_with_arg
resp = test_client.get(
"/a",
)
resp_json = resp.json()
assert resp_json == "aaa"
test_b
passes as expected but all the other tests fail:
FAILED test.py::test_a_method_1 - AssertionError: assert a == aaa
FAILED test.py::test_a_method_2 - AssertionError: assert a == aaa
FAILED test.py::test_a_method_3 - AssertionError: assert a == aaa
FAILED test.py::test_a_method_4 - AssertionError: assert a == aaa
How should I override dep_with_arg
in the example above?