Skip to content

Custom app wiring

When your app doesn't follow the app.main:create_app + app.deps:get_session convention.


When to use this

Set app_factory=None when:

  • Your app factory is in a different location
  • Your session dependency has a different name or signature
  • You need custom middleware or startup logic in tests
  • You're not using FastAPI at all

Setup

conftest.py
import pytest_asyncio
from bluefox_test import bluefox_test_setup
from app.models import Base

# Get all fixtures EXCEPT app and client
globals().update(bluefox_test_setup(base=Base, app_factory=None))


# Define your own app fixture
@pytest_asyncio.fixture
async def app(db):
    from my_app import build_app
    application = build_app()

    # Wire the test session however your app expects it
    application.state.session = db
    yield application


# Define your own client fixture
@pytest_asyncio.fixture
async def client(app):
    from httpx import ASGITransport, AsyncClient
    transport = ASGITransport(app=app)
    async with AsyncClient(transport=transport, base_url="http://test") as c:
        yield c

What still works

Everything except app and client:

Fixture Status
infra provided by bluefox_test_setup()
safe_env provided by bluefox_test_setup()
engine provided by bluefox_test_setup()
db provided by bluefox_test_setup()
create_* provided by bluefox_test_setup()
app you define this
client you define this

Common patterns

Dependency injection via app state

@pytest_asyncio.fixture
async def app(db):
    from my_app import create_app
    app = create_app()
    app.state.db_session = db
    yield app

Dependency injection via override

@pytest_asyncio.fixture
async def app(db):
    from my_app import create_app
    from my_app.dependencies import get_db

    app = create_app()

    async def _test_db():
        yield db

    app.dependency_overrides[get_db] = _test_db
    yield app
    app.dependency_overrides.clear()

Non-FastAPI frameworks

@pytest_asyncio.fixture
async def client(db):
    from my_flask_app import create_app
    app = create_app(test_session=db)
    with app.test_client() as c:
        yield c