Skip to content

Test FastAPI app #7

@CatarinaPBressan

Description

@CatarinaPBressan

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_maker function)
  • 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_db tells FastAPI to call override_get_db wherever get_db was 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_overrides mechanism 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.

https://fastapi.tiangolo.com/advanced/testing-dependencies/#use-the-app-dependency-overrides-attribute

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions