I am facing an issue with FastAPI and Depends.
The snippet below contains two dependency_overrides statements, one in a @app.get the other in @app.on_event. While first tests runs through the other test fails:
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
values = {}
def startup_parameters():
return {
"foo": None,
"bar": None
}
def update_parameters():
return {
"foo": 1,
"bar": 2
}
def override_parameters():
return {
"foo": 5,
"bar": 10
}
@app.on_event("startup")
async def on_startup(commons: dict = Depends(startup_parameters)) -> None:
global values
values = commons
@app.get("/update/")
async def set_items(commons: dict = Depends(update_parameters)) -> None:
global values
values = commons
@app.get("/items/")
async def read_items():
return values
# Test runs
def test_update_override():
with TestClient(app) as client:
app.dependency_overrides[update_parameters] = override_parameters
client.get("/update/")
response = client.get("/items/")
assert response.json() == {
"foo": 5,
"bar": 10,
}
# Test fails
def test_startup_override():
with TestClient(app) as client:
app.dependency_overrides[startup_parameters] = override_parameters
response = client.get("/items/")
assert response.json() == {
"foo": 5,
"bar": 10,
}
Looking at FAST-API Documentation (https://fastapi.tiangolo.com/advanced/advanced-dependencies/) it seems to me that dependency injection is implemented for routes but not for events. But maybe there is a workaround for it.
Thanks a lot in advance...