PythiloLesson 7 of 14 · progress kept in this browser

Replace a dependency in a test

A dependency override replaces one callable in FastAPI's request graph. Tests can supply a fixed clock, repository or demonstration user while exercising the real route and serialization. The override key must be the original callable object, not its name as a string.

Keep overrides scoped to the application under test and clear them after use when sharing an app. Fresh app factories avoid test state leaking between cases. The replacement should provide the same kind of value as the dependency it stands in for, so the endpoint still uses its ordinary contract.

from fastapi import FastAPI, Depends
app = FastAPI()
async def label():
    return "live"
@app.get("/label")
async def read(value=Depends(label)):
    return {"label": value}
async def fixed():
    return "test"
app.dependency_overrides[label] = fixed
print(len(app.dependency_overrides))
Your task

Implement build_app(label="live"). An async get_label dependency supplies GET /label. When label differs from "live", install an async dependency override returning that label. Different app instances must remain independent.

The first run loads fastapi, httpx into this browser.