pytest-fastapi-deps

raw JSON →
0.2.3 verified Mon Apr 27 auth: no python

A pytest fixture that allows easy replacement of FastAPI dependencies for testing. Version 0.2.3 (PyPI). It wraps FastAPI's dependency override mechanism in a clean fixture, enabling overrides at the test level with context managers. Release cadence is irregular.

pip install pytest-fastapi-deps
error AttributeError: module 'pytest_fastapi_deps' has no attribute 'fastapi_dep'
cause Incorrect import. Some users try `from pytest_fastapi_deps import fastapi_deps` (plural) or the wrong symbol.
fix
Use from pytest_fastapi_deps import fastapi_dep (singular).
error ValueError: Dependency override must be a callable or a class
cause Passing a non-callable as the replacement in versions <0.2.0.
fix
Upgrade to 0.2.0+ or wrap the value in a lambda: override={get_token: lambda: value}
error RuntimeError: No override context active
cause Calling `fastapi_dep(app).override(...)` outside of a `with` block, or after the context has exited.
fix
Use the method as a context manager: with fastapi_dep(app).override(...):
gotcha The fixture must be used as a context manager; nested overrides are allowed but order matters.
fix Use `with fastapi_dep(app).override(...)` instead of assigning the fixture to a variable without entering the context.
gotcha Plain objects can be passed as replacements since v0.2.0; prior versions required wrapping in a callable.
fix Upgrade to 0.2.0+ or wrap plain objects in a lambda: `lambda: 'value'`
gotcha The override is applied globally for the app instance during the context; ensure tests don't share the same app fixture if isolation is needed.
fix Create a new app or use separate fixtures to avoid cross-test contamination.

Basic usage: override a dependency with a lambda.

from fastapi import FastAPI, Depends
from pytest_fastapi_deps import fastapi_dep

app = FastAPI()

def get_token():
    return "original"

@app.get("/token")
def read_token(token: str = Depends(get_token)):
    return {"token": token}

# In test file
import pytest
from fastapi.testclient import TestClient

@pytest.fixture
def client():
    with fastapi_dep(app).override({get_token: lambda: "overridden"}):
        yield TestClient(app)

def test_token(client):
    response = client.get("/token")
    assert response.json() == {"token": "overridden"}