Lesson 51 of 59Testing
Testing with Real Databases
Run integration tests against a real Postgres, Redis and Celery setup, with per-test rollback, migrations, factories, contract tests and a suite that stays fast.
Your unit tests pass, your mocked repository returns exactly what you told it to, and the first request in staging fails with duplicate key value violates unique constraint. The mock never knew about that constraint, because the constraint lives in the database, not in your Python. Integration tests that talk to a real Postgres catch this whole class of bug: constraints, SQL that only one database accepts, migrations that do not match the models, queries that are correct but return rows in a surprising order. This lesson shows how to run them without making the suite slow or flaky, and how to treat Redis, Celery and your API schema with the same honesty.
Why mocks of the database lie
A mock or a hand-written fake of your database only knows the behaviour you gave it. Real databases enforce rules your fake has never heard of:
- Constraints:
UNIQUE,NOT NULL, foreign keys andCHECKconstraints reject bad data at write time. - Dialect:
ILIKE,JSONBoperators,ON CONFLICT DO UPDATEand array columns are Postgres features. SQLite accepts some, rejects others and silently treats a few differently. - Types: Postgres stores
timestamptzandnumericprecisely. A fake that keeps Python objects in a list never rounds, truncates or converts time zones. - Ordering: without
ORDER BY, row order is not guaranteed. A fake list always returns insertion order, so a missingORDER BYpasses every test and breaks pagination in production. - Transactions and locks: two requests updating the same row, a rollback after an error,
SELECT ... FOR UPDATE. None of this exists in a list.
Here is the classic case, with SQLite standing in for the real database:
Press Run (⌘ Enter) to see what happens.The fake says everything is fine. The real table, with a case-insensitive unique email (in Postgres you would use a unique index on lower(email) or the citext type), refuses the second row. Your signup route needs to turn that error into a 409, and only a test against the real schema will tell you whether it does.
Keep mocks for things you do not own, like payment providers and email. For your own database, test against the real engine.
ORDER BY. Every test against an in-memory fake passes. What is the risk?A real Postgres for tests
You have two common ways to get a disposable Postgres.
Docker, started by you. Run a container on a spare port before the tests, often from a docker compose service called db-test:
docker run -d --name pg-test -p 5433:5432 \ -e POSTGRES_USER=test -e POSTGRES_PASSWORD=test -e POSTGRES_DB=test \ --tmpfs /var/lib/postgresql/data \ postgres:16 -c fsync=off -c synchronous_commit=off -c full_page_writes=offThe --tmpfs flag keeps the data in memory, and the three -c settings turn off crash safety. Both are terrible ideas in production and harmless for a database you throw away after the run; together they make writes much faster.
Testcontainers, started by the tests. The testcontainers library starts a container from inside a pytest fixture and removes it at the end, so uv run pytest is the only command anyone needs. It still needs Docker (or a compatible runtime) on the machine.
import os
import pytest
from sqlalchemy import create_engine
from testcontainers.postgres import PostgresContainer
@pytest.fixture(scope="session")
def database_url():
if url := os.environ.get("TEST_DATABASE_URL"): # CI provides its own Postgres
yield url
return
with PostgresContainer("postgres:16", driver="psycopg") as pg:
yield pg.get_connection_url() # postgresql+psycopg://test:test@localhost:<port>/test
@pytest.fixture(scope="session")
def engine(database_url):
engine = create_engine(database_url)
yield engine
engine.dispose()The container maps Postgres to a random free port, and get_connection_url() builds the SQLAlchemy URL for it. The driver argument picks the URL prefix; the default is psycopg2, so set it to match the driver you installed. Testcontainers is reorganising its modules, and the newest releases warn that testcontainers.postgres is moving under testcontainers.community, so check the docs for the current import path.
The environment variable escape hatch matters: in CI you usually already have a Postgres service, and starting a second one inside it is wasted time.
Run your migrations, not create_all
Base.metadata.create_all() builds tables from your models. Production gets its tables from Alembic migrations. If the two disagree (a missing index, a column that is nullable in one and not the other) your tests check a schema that does not exist anywhere real. Build the test schema with the migrations you ship:
from alembic import command
from alembic.config import Config
@pytest.fixture(scope="session")
def engine(database_url):
cfg = Config("alembic.ini")
cfg.set_main_option("sqlalchemy.url", database_url)
command.upgrade(cfg, "head") # the same chain production runs
engine = create_engine(database_url)
yield engine
engine.dispose()If your env.py reads the URL from your settings instead of alembic.ini, set the environment variable your settings read before calling upgrade. Pair this with alembic check in CI, which fails when the models have changes no migration covers.
One transaction per test
The pytest lesson built the key fixture: a session-scoped engine, then a function-scoped session inside a transaction that is rolled back after each test, with join_transaction_mode="create_savepoint" so commit() in app code only releases a savepoint. Wire it into FastAPI with the same dependency override as before, and every API test sees an empty database without recreating a single table.
The mechanics, with SQLite again:
Press Run (⌘ Enter) to see what happens.Rollback isolation has limits you should know before they surprise you:
- Sequences are not transactional. A rolled-back insert still used up its id, so the next test's first row might be
id=7. Never assert on literal ids; use the id the response returned. - Code that opens its own connection (a background task with its own session, a Celery worker, a second engine) cannot see the test's uncommitted rows and its writes escape the rollback. Tests for those paths need real commits and cleanup, usually
TRUNCATE ... RESTART IDENTITY CASCADEon the touched tables afterwards. - Locking and concurrency cannot be tested inside one transaction. Mark those few tests and give them committed data.
user.id == 1. On Postgres, what happens?Parallel runs. With pytest-xdist, several workers share one Postgres. Rollback keeps their data apart for most tests, but the committed-data tests above can collide. A common fix is one database per worker: the built-in worker_id fixture (gw0, gw1, or master without xdist) names it, and a session fixture creates test_gw0, test_gw1 and so on.
Factories that write to the database
With a real database you need real rows, often with related rows behind them. factory_boy has a SQLAlchemy integration (polyfactory, from the testing lesson, offers a similar one; pick one per project):
import factory
from app.models import Order, User
class UserFactory(factory.alchemy.SQLAlchemyModelFactory):
class Meta:
model = User
sqlalchemy_session_persistence = "flush" # get an id, do not commit
email = factory.Sequence(lambda n: f"user{n}@example.com")
name = factory.Faker("name")
class OrderFactory(factory.alchemy.SQLAlchemyModelFactory):
class Meta:
model = Order
sqlalchemy_session_persistence = "flush"
user = factory.SubFactory(UserFactory)
total = 1000
status = "paid"@pytest.fixture(autouse=True)
def bind_factories(db):
for f in (UserFactory, OrderFactory):
f._meta.sqlalchemy_session = db # the rolled-back test sessionNow OrderFactory(status="pending") creates a user and an order inside the test's transaction, and UserFactory.create_batch(20) sets up a pagination test in one line. flush gives every row its id while leaving the outer rollback in charge.
Redis and Celery
Redis. For code that uses plain commands (get, set with a TTL, counters, sorted sets), fakeredis is an in-process imitation of the Redis server that speaks the same client API. fakeredis.FakeRedis() replaces redis.Redis, and fakeredis.FakeAsyncRedis() replaces redis.asyncio.Redis. Swap it in with a dependency override on your get_redis dependency. Its coverage of the command set is wide but not perfect; for Lua scripts, Redis modules or anything timing-sensitive, start a real Redis with Docker or Testcontainers, exactly like Postgres.
Celery. Test in layers:
- Test the task's logic as a function. A Celery task is still a function: call
send_receipt(order_id=42)directly, without.delay(), and assert on the result. Most of your task tests should look like this. Better still, keep the logic in a service function and make the task a thin wrapper. - Eager mode for wiring. With
task_always_eager=True,.delay()runs the task immediately in the same process and returns a result object; addtask_eager_propagates=Trueso exceptions surface in the test instead of being stored on the result. It is handy for checking that the route enqueues the right task with the right arguments. It skips the broker, serialization and the worker, so it cannot catch an argument that is not JSON-serialisable, and the Celery docs advise against relying on it for real testing. - A real worker for a few end-to-end tests. Celery ships pytest fixtures (
celery_app,celery_workerincelery.contrib.pytest) that run a worker in a thread during the test. Check the Celery testing docs for the current setup.
Match each testing need to the tool that fits.
Contract tests for the API schema
FastAPI publishes an OpenAPI schema at /openapi.json. Frontends and other services generate clients from it, so it is a contract. Schemathesis reads the schema, generates many requests from it (valid ones, edge cases and deliberately invalid ones), sends them to your app, and checks the responses: no 500s, status codes and bodies that match the schema, invalid input actually rejected.
import schemathesis
from app.main import app
schema = schemathesis.openapi.from_asgi("/openapi.json", app)
@schema.parametrize()
def test_api_matches_its_schema(case):
case.call_and_validate()from_asgi calls the app in-process like TestClient, so use your test database and auth overrides here too. Without pytest, the CLI tests a running server: schemathesis run http://localhost:8000/openapi.json. These are the current version's names; older releases used schemathesis.from_asgi, so match the docs to the version you install.
Expect findings on the first run. Pointed at a tiny app with one POST /items route taking {"name": str, "qty": int}, Schemathesis reported that the API accepted "qty": false, because Pydantic's default lax mode turns false into 0 while the schema promises an integer. After switching the model to strict mode, it reported that malformed JSON got a 400 that the schema never documented. Each failure comes with a curl command that reproduces it.
In CI
The CI lesson built the workflow with a services: postgres container and a health check. Two connections to this lesson: export TEST_DATABASE_URL pointing at that service so the session fixture uses it instead of starting Testcontainers, and let the fixture run alembic upgrade head so CI proves the migration chain on an empty database every time.
The session fixture uses TEST_DATABASE_URL if set, otherwise starts a Testcontainers Postgres.
Keeping the suite fast
Real-database tests cost milliseconds each when set up well, and seconds each when not. The rules:
- Expensive things once per session: the container, the migrations, the engine.
- Cheap things per test: the transaction and the data from factories.
- Mark the slow outliers: committed-data tests, real-worker Celery tests and Schemathesis runs get
@pytest.mark.slowor@pytest.mark.integration, registered inpyproject.tomlwith--strict-markersas in the pytest lesson. Locally you runuv run pytest -m "not slow"; CI runs everything. - Keep the database fast: tmpfs and
fsync=offfor the test container, as shown above. - Run in parallel with
pytest-xdistonce each worker has its own database.
Order what happens in a test run with these fixtures.
- Tap the steps below in the right order.
- integration test
- A test that runs your code together with real infrastructure, such as a real Postgres, instead of mocks.
- Testcontainers
- A library that starts disposable Docker containers, like Postgres or Redis, from inside your tests.
- per-test rollback
- Running each test inside a transaction that is rolled back, so every test starts from the migrated, empty schema.
- fakeredis
- An in-process imitation of a Redis server that works with the redis-py client API.
- eager mode
- A Celery setting that runs tasks inline when
.delay()is called, skipping the broker and worker. - contract test
- A test that checks an API's real behaviour against its published schema, such as OpenAPI.
- Schemathesis
- A tool that generates requests from an OpenAPI schema and checks the responses against it.