Skip to content

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.

18 min read0/5 questions

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 and CHECK constraints reject bad data at write time.
  • Dialect: ILIKE, JSONB operators, ON CONFLICT DO UPDATE and array columns are Postgres features. SQLite accepts some, rejects others and silently treats a few differently.
  • Types: Postgres stores timestamptz and numeric precisely. 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 missing ORDER BY passes 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:

Pythonthe_fake_lies.py
import sqlite3 class FakeUserRepo: """What a hand-written fake of the database often looks like.""" def __init__(self): self.rows = [] def add(self, email): self.rows.append({"id": len(self.rows) + 1, "email": email}) class SqlUserRepo: def __init__(self, conn): self.conn = conn def add(self, email): self.conn.execute("INSERT INTO users (email) VALUES (?)", (email,)) conn = sqlite3.connect(":memory:")conn.execute(""" CREATE TABLE users ( id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE COLLATE NOCASE )""") def signup_twice(repo): repo.add("ada@example.com") repo.add("Ada@Example.com") # same person, different case return "two users created" print("fake:", signup_twice(FakeUserRepo()))try: print("real:", signup_twice(SqlUserRepo(conn)))except sqlite3.IntegrityError as err: print("real: IntegrityError:", err)
Output
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.

Quick check
A repository method lists a user's orders without ORDER BY. Every test against an in-memory fake passes. What is the risk?
Need a nudge? A hint rules out a wrong answer.

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=off

The --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.

tests/conftest.py
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:

tests/conftest.py
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:

Pythonrollback_per_test.py
import sqlite3 conn = sqlite3.connect(":memory:", isolation_level=None) # we control transactionsconn.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, total INTEGER)") # once per session def count(): return conn.execute("SELECT count(*) FROM orders").fetchone()[0] def run_in_transaction(test): conn.execute("BEGIN") try: test() print(f"PASS {test.__name__}") except AssertionError as err: print(f"FAIL {test.__name__}: {err}") finally: conn.execute("ROLLBACK") # undo whatever the test wrote def test_create_two_orders(): conn.execute("INSERT INTO orders (total) VALUES (500), (900)") assert count() == 2, f"expected 2, got {count()}" def test_starts_empty(): assert count() == 0, f"leftover rows: {count()}" def test_insert_commits_inside_app_code(): conn.execute("SAVEPOINT app") # what the app's commit becomes conn.execute("INSERT INTO orders (total) VALUES (100)") conn.execute("RELEASE app") assert count() == 1 run_in_transaction(test_create_two_orders)run_in_transaction(test_starts_empty)run_in_transaction(test_insert_commits_inside_app_code)run_in_transaction(test_starts_empty)print("rows after the whole run:", count())
Output
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 CASCADE on the touched tables afterwards.
  • Locking and concurrency cannot be tested inside one transaction. Mark those few tests and give them committed data.
Quick check
Test A inserts a user and is rolled back. Test B then inserts a user and asserts user.id == 1. On Postgres, what happens?
Need a nudge? A hint rules out a wrong answer.

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

tests/factories.py
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"
tests/conftest.py
@pytest.fixture(autouse=True)
def bind_factories(db):
    for f in (UserFactory, OrderFactory):
        f._meta.sqlalchemy_session = db      # the rolled-back test session

Now 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:

  1. 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.
  2. Eager mode for wiring. With task_always_eager=True, .delay() runs the task immediately in the same process and returns a result object; add task_eager_propagates=True so 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.
  3. A real worker for a few end-to-end tests. Celery ships pytest fixtures (celery_app, celery_worker in celery.contrib.pytest) that run a worker in a thread during the test. Check the Celery testing docs for the current setup.
Match the pairs0/5 matched

Match each testing need to the tool that fits.

Choose an item, then its match on the other side.

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.

tests/test_contract.py
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.

Quick check
What kind of bug is Schemathesis best at finding?
Need a nudge? A hint rules out a wrong answer.

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.

One test run against real services
pytest: session startspytestsession startsPostgres: container or CI servicePostgrescontainer or CI serviceAlembic: upgrade head, onceAlembicupgrade head, onceEach test: BEGIN ... ROLLBACKEach testBEGIN ... ROLLBACKfakeredis: override get_redisfakeredisoverride get_redisstart or reusemigraterunsavepointscache calls

The session fixture uses TEST_DATABASE_URL if set, otherwise starts a Testcontainers Postgres.

1/4

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.slow or @pytest.mark.integration, registered in pyproject.toml with --strict-markers as in the pytest lesson. Locally you run uv run pytest -m "not slow"; CI runs everything.
  • Keep the database fast: tmpfs and fsync=off for the test container, as shown above.
  • Run in parallel with pytest-xdist once each worker has its own database.
Put it in order6 steps

Order what happens in a test run with these fixtures.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
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.