Performance: Testing with database
This concept affects the speed of test execution and the responsiveness of the development feedback loop.
import pytest from fastapi.testclient import TestClient from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from myapp.main import app from myapp.database import Base, get_db # Use in-memory SQLite for tests SQLALCHEMY_DATABASE_URL = 'sqlite:///:memory:' engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={'check_same_thread': False}) TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base.metadata.create_all(bind=engine) def override_get_db(): db = TestingSessionLocal() try: yield db finally: db.close() app.dependency_overrides[get_db] = override_get_db client = TestClient(app) def test_create_item(): response = client.post('/items/', json={'name': 'test'}) assert response.status_code == 200 # This test uses a fast in-memory database
import pytest from fastapi.testclient import TestClient from myapp.main import app client = TestClient(app) def test_create_item(): response = client.post('/items/', json={'name': 'test'}) assert response.status_code == 200 # This test uses the real database connection
| Pattern | Test Runtime | I/O Operations | Resource Usage | Verdict |
|---|---|---|---|---|
| Real database connection | Slow (100-500ms per test) | High (network + disk) | High (DB server resources) | [X] Bad |
| In-memory SQLite database | Fast (10-50ms per test) | Low (memory only) | Low (no external resources) | [OK] Good |
response.json()?
def test_create_item(client):
response = client.post('/items/', json={'name': 'Book', 'price': 10})
return response.json()def override_get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
app.dependency_overrides[get_db] = override_get_db
def test_read_items(client):
response = client.get('/items/')
assert response.status_code == 200
assert response.json() == []Pass the test and this pattern moves unknown