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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1FastAPI's dependency_overrides lets tests inject fakes without touching route code.
- 2Yielding fixtures give you setup-then-teardown around each test in one function.
- 3Overriding authentication lets you exercise protected routes as a known user.
Related explainers
typescript
import { Controller, Get, Query,
Validating paginated queries in NestJS
pagination
validation
pipes
Intermediate
7 steps
python
import hashlib import os from datetime import timedelta
Serving cacheable static assets in Flask
http-caching
etag
conditional-requests
Intermediate
8 steps
typescript
import { Controller, Post, UploadedFile,
Handling avatar uploads in NestJS
file-upload
validation
interceptors
Intermediate
7 steps
python
import re from collections import Counter from pathlib import Path
Ranking the top words in a PDF
text-processing
regex
counting
Intermediate
6 steps
php
<?php namespace App\Http\Middleware;
Verifying GitHub webhook signatures in Laravel
middleware
hmac
webhooks
Intermediate
5 steps
java
@Configuration @EnableWebSecurity public class OAuth2SecurityConfig {
How OIDC login works in Spring Security
oauth2
openid-connect
authorization
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/testing-fastapi-routes-with-dependency-overrides-explained-python-8995/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.