Tips and Tricks

FastAPI

FastAPI - Overriding dependencies while running tests


FastAPI tip:

You can override a dependency of your app while running tests with dependency_overrides.

https://fastapi.tiangolo.com/advanced/testing-dependencies/#use-the-appdependency_overrides-attribute

For example, to connect to a test database:

from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel
from sqlalchemy.orm import Session, sessionmaker, declarative_base
from sqlalchemy import create_engine, Column, Integer, String


SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"

engine = create_engine(
    SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()


class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    email = Column(String, unique=True, index=True)


Base.metadata.create_all(bind=engine)


class UserSchema(BaseModel):
    email: str

    class Config:
        orm_mode = True


app = FastAPI()


# Dependency
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


@app.post("/users/", response_model=UserSchema)
def create_user(user_data: UserSchema, database_session: Session = Depends(get_db)):
    db_user = User(email=user_data.email)
    database_session.add(db_user)
    database_session.commit()

    return db_user


SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"

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()


# THIS
app.dependency_overrides[get_db] = override_get_db
# THIS

client = TestClient(app)


def test_create_user():
    response = client.post(
        "/users/",
        json={"email": "[email protected]"},
    )
    assert response.status_code == 200