python 46 lines · 7 steps

Testing FastAPI routes with dependency overrides

A pytest fixture swaps FastAPI's database and auth dependencies for test doubles so routes run against an isolated SQLite database.

Explained by highlit
1import pytest
2from fastapi.testclient import TestClient
3from sqlalchemy import create_engine
4from sqlalchemy.orm import sessionmaker
5 
6from app.main import app
7from app.database import Base, get_db
8from app.auth import get_current_user
9from app.models import User
10 
11engine = create_engine(
12 "sqlite:///./test.db",
13 connect_args={"check_same_thread": False},
14)
15TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
16 
17 
18@pytest.fixture
19def db_session():
20 Base.metadata.create_all(bind=engine)
21 session = TestingSessionLocal()
22 try:
23 yield session
24 finally:
25 session.close()
26 Base.metadata.drop_all(bind=engine)
27 
28 
29@pytest.fixture
30def client(db_session):
31 def override_get_db():
32 try:
33 yield db_session
34 finally:
35 pass
36 
37 def override_get_current_user():
38 return User(id=1, email="tester@example.com", is_active=True)
39 
40 app.dependency_overrides[get_db] = override_get_db
41 app.dependency_overrides[get_current_user] = override_get_current_user
42 
43 with TestClient(app) as test_client:
44 yield test_client
45 
46 app.dependency_overrides.clear()
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1FastAPI's dependency_overrides lets tests inject fakes without touching route code.
  2. 2Yielding fixtures give you setup-then-teardown around each test in one function.
  3. 3Overriding authentication lets you exercise protected routes as a known user.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Testing FastAPI routes with dependency overrides — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code