skip to content

Swapping Dependencies

app.dependency_overrides maps a dependency callable to a replacement for tests. Interviewers ask how to swap the database session and current user, and why a forgotten override leaks across tests.

on this pageshow

explore

questions

6

In a FastAPI test, how do you make an endpoint that depends on get_current_user run as a fixed test user?

level: juniorimportance: must knowfreq 62%

answer

  1. a dict on the app object
  2. keyed by the original function
  3. value returns the fake user
  4. remove it when the test ends

basics

~10 s

Add an entry to app.dependency_overrides keyed by the original get_current_user function, whose value is a callable returning the test user; FastAPI calls it instead on every request, and the test removes the entry afterwards.

solid answer

~40 s

`app.dependency_overrides` is a plain `dict` on the `FastAPI` instance. I set `app.dependency_overrides[get_current_user] = fake_current_user`, where `fake_current_user` returns a fixed `User`, and call the endpoint through `TestClient`. FastAPI consults that dict every time it resolves a dependency, so every path operation, router or decorator dependency that uses `get_current_user` gets the fake user. Because the original is never called, neither are its own sub-dependencies: the `OAuth2PasswordBearer` scheme never reads the `Authorization` header, so the request succeeds without a token. Finally I remove the entry when the test ends, in a `finally` block or a fixture's teardown, or the next test inherits the fake user.

code

python · 36 lines
python
from typing import Annotated

from fastapi import Depends, FastAPI
from fastapi.security import OAuth2PasswordBearer
from fastapi.testclient import TestClient
from pydantic import BaseModel

app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")


class User(BaseModel):
    username: str


def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]) -> User:
    raise NotImplementedError("decode and verify the token here")


@app.get("/orders/mine")
def my_orders(user: Annotated[User, Depends(get_current_user)]):
    return {"owner": user.username}


def fake_current_user() -> User:
    return User(username="alice")


def test_my_orders_as_alice():
    app.dependency_overrides[get_current_user] = fake_current_user
    try:
        response = TestClient(app).get("/orders/mine")  # no Authorization header
        assert response.status_code == 200
        assert response.json() == {"owner": "alice"}
    finally:
        app.dependency_overrides.clear()

go deeper

for a junior

Recall the exact line: app.dependency_overrides with the original function as key and a fake-user function as value. Mention removing it after the test.

for a middle

Explain that FastAPI consults the dict on every request and that the original's sub-dependencies, such as the bearer scheme, no longer run.

for a senior

Point out what the override stops proving: authentication is bypassed, so the token path needs its own test without overrides, and cleanup belongs in teardown.

for a principal

Frame overrides as a team convention: fixtures own every override, fixed-user fakes are shared helpers, and a suite rule keeps at least one real-token test per protected router.

## What `app.dependency_overrides` is Every `FastAPI` application object carries an attribute called `dependency_overrides`. It is an ordinary Python `dict`, empty by default, and FastAPI's source documents it as existing "for testing, to replace expensive dependencies with testing versions". - The **key** is the original dependency callable: the exact object you passed to `Depends(...)`, here the function `get_current_user`. - The **value** is the replacement callable FastAPI should call instead. When FastAPI resolves the dependencies of a request, it looks each one up in this dict. If it finds the original as a key, it builds the dependency from the replacement and calls that; otherwise it calls the original. The lookup happens on every request, not when the app starts. ## Writing the override, step by step 1. Write a function that returns the user the test wants, for example `def fake_current_user() -> User: return User(username="alice")`. It usually takes no parameters. 2. Register it: `app.dependency_overrides[get_current_user] = fake_current_user`. Pass the function object itself, not a string and not a call (`fake_current_user`, not `fake_current_user()`). 3. Send the request with `TestClient(app)` and assert on the response. 4. Remove the entry when the test ends, with `app.dependency_overrides.clear()` or `app.dependency_overrides.pop(get_current_user, None)`, in a `finally` block or a pytest fixture's teardown so it runs even when an assertion fails. ## What the override skips The override replaces the original **and everything beneath it**. FastAPI resolves dependencies as a graph: `get_current_user` usually depends on `oauth2_scheme`, an `OAuth2PasswordBearer` instance that reads the `Authorization` header, and perhaps on a database session to load the user. With the override in place: - `get_current_user` is not called at all. - Its sub-dependencies are not resolved either, so the bearer scheme never runs and a request **without any token** reaches the endpoint. - Other dependencies the endpoint declares directly still run normally; only the overridden branch is replaced. - The generated OpenAPI schema does not change: `/docs` still shows the endpoint as protected, because the schema is built from the original declarations. This is exactly why the technique is useful: tests of business logic no longer need to mint and sign a real token, call an identity provider, or seed a user row just to get past authentication. It also means that a test using the override proves nothing about authentication itself; the token path needs its own test that sets no override. ## Where the override applies The FastAPI documentation notes that an override works wherever the original dependency is used: - as a parameter of a path operation function, typically through an `Annotated[User, Depends(get_current_user)]` alias; - in a path operation decorator's `dependencies=[...]` list; - in an `APIRouter(dependencies=[...])` or an `include_router(..., dependencies=[...])` call; - as a sub-dependency of another dependency. One override therefore covers every endpoint of the app at once. It does not cover a separate `FastAPI` sub-application attached with `app.mount`, which has its own `dependency_overrides` dict. ## Beginner mistakes | Mistake | What happens | |---|---| | Key is the string `"get_current_user"` | Never matched; the real dependency runs | | Key and value swapped | Never matched; the real dependency runs | | Monkeypatching the module attribute | The route already holds the original function object, so nothing changes | | No cleanup | The next test silently runs as the fake user | | Expecting a missing token to fail | The scheme was skipped, so the request succeeds | A related surprise: the override is inspected like any other dependency. If it declares a parameter, for example `role: str`, FastAPI treats it as a required query parameter and answers 422 when the test omits it, even though `/docs` never shows that parameter. Keep fixed-user overrides parameterless, or give the fake a closure over the values the test needs, for example a small factory that returns `lambda: User(username=name)` so each test can pick its user. ## Summary `app.dependency_overrides[get_current_user] = fake_current_user` is the whole mechanism: a dict keyed by the original callable, consulted on each request, applied everywhere the dependency appears, and replacing its whole sub-graph. The discipline around it, removing the entry after each test, matters as much as the line that adds it.

  • Does the override function have to match get_current_user's signature?
    No. FastAPI inspects the override like any dependency, so its own parameters become request inputs or sub-dependencies. A zero-argument function is usual for a fixed user. If it declares `role: str`, that becomes a required query parameter, and a request without it gets a 422 even though `/docs` never lists it.
  • Can the override be added after the TestClient was created?
    Yes. FastAPI reads `app.dependency_overrides` each time it resolves a request's dependencies, so an entry added or removed between two calls on the same `TestClient` takes effect on the next request. Nothing has to be rebuilt.

  • The override key is the string name of the dependency function.
  • Monkeypatching get_current_user in its module also changes what FastAPI calls.
  • Overrides must be registered before TestClient(app) is created.
  • The fake user still needs a valid bearer token in the request.
  • FastAPI drops overrides automatically when the test function returns.
open as a page

In FastAPI, what exactly must the key of app.dependency_overrides be, and why can a registered override silently never apply?

level: middleimportance: must knowfreq 52%

basics

~20 s

The key must be the exact callable given to Depends: the function, class, callable instance or lru_cache wrapper. FastAPI does a plain dict lookup, so an alias, a name or a look-alike never matches and raises no error.

open as a page

In FastAPI, when a test overrides get_db, which both get_current_user and the endpoint depend on, what runs during one request?

level: middleimportance: should knowfreq 40%

basics

~10 s

The 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.

open as a page

How do you override a FastAPI session dependency so tests use an in-memory SQLite database, and why does that need StaticPool?

level: middleimportance: should knowfreq 48%

basics

~10 s

A fixture builds a sqlite:// engine with StaticPool and check_same_thread=False, creates the tables and yields a Session; a second fixture maps get_session to a function returning it in app.dependency_overrides and removes the entry afterwards.

open as a page

In a FastAPI suite, why does an entry left in app.dependency_overrides reach later tests, and how should fixtures restore it?

level: seniorimportance: should knowfreq 45%

basics

~20 s

app.dependency_overrides is a dict on the module-level FastAPI object, shared by every test and every TestClient, and nothing resets it. Set overrides in yield fixtures, remove them in teardown, and add an autouse guard that fails a test leaving entries behind.

open as a page

A FastAPI test overrides the lru_cache-wrapped get_settings, yet part of the app still uses production values; what does the override not reach?

level: seniorimportance: should knowfreq 33%

basics

~20 s

An override of get_settings only reaches values FastAPI resolves through Depends during a request. Direct get_settings() calls at import, in the lifespan or in helpers still run the real lru_cache function and keep the production Settings.

open as a page