-
Notifications
You must be signed in to change notification settings - Fork 0
Test FastAPI app #7
Copy link
Copy link
Open
Description
Overriding a SQLAlchemy Session Dependency for Testing
FastAPI provides app.dependency_overrides — a simple dict — that lets you replace any dependency with a test-specific version without touching your production code. [[dependency overrides](https://fastapi.tiangolo.com/advanced/testing-dependencies/#use-the-app-dependency-overrides-attribute)]
The pattern is straightforward:
- Key: the original dependency callable (your
session_makerfunction) - Value: a replacement callable that returns a session backed by your test database engine
Here is how you can apply this to your situation:
from typing import Annotated, Generator
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session
# --- Your production app ---
PRODUCTION_DB_URL = "postgresql://user:password@localhost/prod_db"
engine = create_engine(PRODUCTION_DB_URL)
SessionLocal = sessionmaker(bind=engine)
app = FastAPI()
def get_db() -> Generator[Session, None, None]:
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/items/")
async def read_items(db: Annotated[Session, Depends(get_db)]):
# ... use db session
return {"message": "items"}
# --- Your test file ---
TEST_DB_URL = "sqlite:///./test.db" # or any test DB URL
test_engine = create_engine(TEST_DB_URL)
TestSessionLocal = sessionmaker(bind=test_engine)
def override_get_db() -> Generator[Session, None, None]:
db = TestSessionLocal()
try:
yield db
finally:
db.close()
# Apply the override
app.dependency_overrides[get_db] = override_get_db
client = TestClient(app)
def test_read_items():
response = client.get("/items/")
assert response.status_code == 200
# Reset overrides after tests if needed
app.dependency_overrides = {}Key points:
app.dependency_overrides[get_db] = override_get_dbtells FastAPI to calloverride_get_dbwhereverget_dbwas used — in path operation functions, decorators, routers included via.include_router(), etc. [[dependency overrides](https://fastapi.tiangolo.com/advanced/testing-dependencies/#use-the-app-dependency-overrides-attribute)]- If you only want the override active for specific tests, set it at the start of the test function and reset it at the end by assigning
app.dependency_overrides = {}. [[dependency overrides](https://fastapi.tiangolo.com/advanced/testing-dependencies/#use-the-app-dependency-overrides-attribute)] - The override function does not need to match the original's signature exactly — FastAPI only cares about the value it returns/yields.
Note: The knowledge sources cover the
dependency_overridesmechanism in detail, but the specific SQLAlchemy session setup (e.g., table creation,Base.metadata) is beyond what the provided sources cover. You'll need to handle database schema setup for your test engine separately using SQLAlchemy's own APIs.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels