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 { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
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.