In FastAPI, when a test overrides get_db, which both get_current_user and the endpoint depend on, what runs during one request?
answer
- the graph is resolved per request
- every place the original appears
- cached once, keyed by the original
- overriding a parent drops its branch
basics
~10 sThe override replaces get_db everywhere in the request's dependency graph, including inside the real get_current_user, and runs once per request so both receive the same fake session; get_db itself never runs.
solid answer
~40 sFastAPI resolves dependencies recursively and checks `app.dependency_overrides` at every node, so overriding `get_db` reaches every dependent: the real `get_current_user` still runs, but receives the test session, and so does the endpoint. The per-request dependency cache is keyed by the original `get_db`, so the override is called once and both consumers share its result, unless a declaration sets `use_cache=False`. The reverse is also worth knowing: overriding `get_current_user` instead removes that whole branch, so its token scheme and its own `get_db` never run, while the endpoint's direct `get_db` still runs for real. The override may itself be a `yield` function; its teardown runs like the original's would.
code
python · 43 linesfrom typing import Annotated
from fastapi import Depends, FastAPI, Header
from fastapi.testclient import TestClient
calls: list[str] = []
def get_db():
calls.append("get_db")
yield "live-session"
DbDep = Annotated[str, Depends(get_db)]
def get_current_user(x_user: Annotated[str, Header()], db: DbDep) -> dict:
calls.append("get_current_user")
return {"name": x_user, "loaded_with": db}
app = FastAPI()
@app.get("/orders/mine")
def my_orders(user: Annotated[dict, Depends(get_current_user)], db: DbDep):
return {"user": user, "endpoint_db": db}
def fake_db():
calls.append("fake_db")
yield "test-session"
client = TestClient(app)
app.dependency_overrides[get_db] = fake_db
print(client.get("/orders/mine", headers={"X-User": "alice"}).json(), calls)
calls.clear()
app.dependency_overrides = {get_current_user: lambda: {"name": "bob"}}
print(client.get("/orders/mine").json(), calls)
app.dependency_overrides.clear()go deeper
Remember that one override of the session dependency reaches every endpoint and dependency that uses it.
Explain the recursive resolution, the per-request cache keyed by the original callable, and why overriding a parent drops its whole subtree.
Choose which node to override so the logic under test stays real, and use call tracing to prove what an override replaced.
Set a team rule to override the lowest external boundary, such as the session or outbound client, so tests keep exercising the real application logic.
## The dependency graph FastAPI resolves A FastAPI endpoint declares dependencies with `Depends`, and those dependencies can declare their own. For each request FastAPI walks this tree from the endpoint downwards, resolves each node's sub-dependencies first, then calls the node. A typical shape: - `get_db` opens a database session (a `yield` dependency, so it can close it afterwards). - `get_current_user` reads a credential and loads the user **with a session from `get_db`**. - The endpoint takes both `get_current_user` and `get_db`. So `get_db` appears twice in one request's graph: once under `get_current_user` and once directly under the endpoint. ## Overriding a leaf of the graph At every node, FastAPI asks `app.dependency_overrides` whether the node's original callable has a replacement. Overriding `get_db` therefore has three effects: 1. **Every dependent sees the override.** The real `get_current_user` still runs, with its real logic, but its `db` parameter is now the test session. The endpoint's own `db` parameter gets the test session too. 2. **The override runs once per request.** FastAPI caches each dependency's result for the rest of the request, and the cache key is built from the *original* callable, so the second appearance of `get_db` reuses the first result. Both consumers share one object. A declaration with `Depends(get_db, use_cache=False)` opts out and gets a fresh call. 3. **The original never runs.** Nothing touches the production engine. This is the property that makes a single session override sufficient for a whole app: you do not override each repository, service or user-loader that consumes the session. ## Overriding a node with children Overriding `get_current_user` behaves differently, because the replacement takes the original's place **with its whole subtree**: - the security scheme under it (for example an `OAuth2PasswordBearer` reading the `Authorization` header) is not resolved; - the `get_db` call under it is not made either; - but the endpoint's direct `get_db` is a separate branch and still runs, for real, unless it too is overridden. | What the test overrides | Real `get_current_user` runs? | Real `get_db` runs? | Token checked? | |---|---|---|---| | nothing | yes | yes, once | yes | | `get_db` | yes, with the fake session | no | yes | | `get_current_user` | no | yes, for the endpoint only | no | | both | no | no | no | The rule of thumb: override the **lowest** node that does the expensive or external thing, so the logic above it stays under test. ## What the override brings with it The override is not a bare value; FastAPI inspects it like any dependency. - **Its own parameters are resolved.** An override can declare `Depends(...)` on other dependencies, or query parameters and headers, and FastAPI resolves those. Declaring a parameter the test does not send produces a 422. - **It can be a `yield` function.** FastAPI detects generator overrides, runs the code before `yield` as setup and the code after it as teardown, as it would for the original. - **It keeps the original declaration's settings.** The cache key, `use_cache` and a yield dependency's `scope` come from the original `Depends(...)`, not from the override. - **The schema does not change.** OpenAPI is generated from the original declarations, so parameters that only the override declares never appear in `/docs`. ## Tracing it in a test The example below records which callables run. With `get_db` overridden, the log shows the override once and the real `get_current_user` once, and both the user and the endpoint report the test session. With `get_current_user` overridden, the log shows only the real `get_db`, called once for the endpoint, and no header is needed. Instrumenting a test like this is a fast way to settle an argument about what an override actually replaced, and it costs a few lines that can be deleted once the question is answered. ## Summary FastAPI applies an override at every node of every request's graph, caches it under the original's key, and replaces the original's entire subtree. Override the bottom of the graph to keep the real logic above it in the test; override a parent only when you mean to skip everything beneath it.
- Why would a test override get_db rather than get_current_user?Overriding `get_db` keeps the real user-loading logic under test: `get_current_user` still runs and still queries, just against the test database. Overriding `get_current_user` is right when the test is about the endpoint's own behaviour and the user can be a fixed value, accepting that the credential path is skipped.
- What changes if one dependent declares Depends(get_db, use_cache=False)?That declaration bypasses the per-request cache, so FastAPI calls the override again for it and that dependent receives a separate object. The others still share the cached result. With a shared in-memory test session this rarely matters, but with an override that opens a new session per call it means two sessions in one request.
- Overriding get_db also requires overriding every dependency that consumes the session.
- The override is called once for each place get_db appears in the request.
- Overriding get_current_user still runs its sub-dependencies, including the token scheme.
- An override must return a plain value; a yield function is not allowed.
- Parameters declared on the override show up in the generated OpenAPI schema.