Testing a FastAPI endpoint with dependency_overrides
app.dependency_overrides replaces any Depends, so I do not need monkeypatch.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | # ====================================================================== # Q: How do you test a FastAPI endpoint without a real database and without real # auth? # # app.dependency_overrides replaces any Depends, so I do not need monkeypatch. # For the database I prefer real PostgreSQL (Docker or testcontainers) with a # transaction that rolls back at the end of each test, because SQLite does not # have the same constraints, JSONB and locking. In Django the equivalent is # pytest-django with @pytest.mark.django_db. # ====================================================================== from fastapi.testclient import TestClient from app.main import app from app.deps import get_session, current_user, get_erp @pytest.fixture def client(db_session): # db_session: a transaction with rollback fake_erp = FakeErpClient() app.dependency_overrides[get_session] = lambda: db_session app.dependency_overrides[current_user] = lambda: User(id=1, tenant_id=7, perms={'orders:write'}) app.dependency_overrides[get_erp] = lambda: fake_erp with TestClient(app) as c: c.fake_erp = fake_erp yield c app.dependency_overrides.clear() def test_create_order_pushes_to_erp(client): r = client.post('/v1/orders', json={'lines': [{'sku': 'A1', 'qty': 2}]}) assert r.status_code == 201 assert client.fake_erp.sent[0][0] == r.json()['id'] def test_validation_error(client): r = client.post('/v1/orders', json={'lines': [{'sku': 'A1', 'qty': 0}]}) assert r.status_code == 422 |