A Python backend wrote its SQL by hand, with no ORM, and almost every test mocked the database connection. All of them passed. But the two guarantees that mattered most were “a retried worker never creates a duplicate row” and “two workers never claim the same job”, and both live in SQL. The mocked tests never executed any of it.

A mock never runs the SQL

This function enqueues a job. Calling it twice with the same dedupe_key must leave one row.

def enqueue(conn: psycopg.Connection, dedupe_key: str) -> int | None:
    row = conn.execute(
        """
        INSERT INTO jobs (dedupe_key) VALUES (%s)
        ON CONFLICT (dedupe_key) DO NOTHING
        RETURNING id
        """,
        (dedupe_key,),
    ).fetchone()
    return row[0] if row else None

Tested with a mock, it looks like this:

from unittest.mock import MagicMock

from jobs import enqueue


def test_enqueue_with_a_mock():
    conn = MagicMock()
    conn.execute.return_value.fetchone.return_value = (1,)
    assert enqueue(conn, "job-42") == 1
    # Passes whether or not the SQL has ON CONFLICT, or is valid SQL at all.

The test still passes if you delete ON CONFLICT, or if the SQL doesn’t parse. All it checks is that execute was called and returned the value you planted.

List where each guarantee is implemented, and almost all of them sit in the database:

GuaranteeWhere it is implemented
A retry adds no rowUNIQUE constraint and ON CONFLICT DO NOTHING
A claimed job is not handed out againWHERE status = 'pending'
Two workers polling at once don’t take the same jobFOR UPDATE SKIP LOCKED
Another tenant’s rows are never returnedThe query’s WHERE clause
The app role can read and write its tablesGRANT
Existing data moves correctly to a new schemaThe data migration’s SQL

Swapping in SQLite doesn’t close the gap. SQLite accepts ON CONFLICT, but it has no FOR UPDATE or SKIP LOCKED, no roles or GRANT, and no PL/pgSQL. These tests have to run on the same PostgreSQL as production.

Build the schema the way production does

The test database matches production on three points:

  1. The PostgreSQL major version. testcontainers starts one postgres:18 container per test session.
  2. The schema. The same migration files run in the same order.
  3. The role. Tests connect as the role the app uses in production, not as a superuser.

The third one is easy to miss. Connected as a superuser, you can’t see a missing GRANT. A migration that creates a table and forgets the grant passes every test, and only production fails with permission denied.

A migration that creates a table also grants the app role access to it, in the same file.

-- V1__jobs.sql
CREATE TABLE jobs (
    id         bigserial PRIMARY KEY,
    dedupe_key text NOT NULL UNIQUE,
    status     text NOT NULL DEFAULT 'pending'
               CHECK (status IN ('pending', 'claimed', 'done')),
    worker     text
);
GRANT SELECT, INSERT, UPDATE, DELETE ON jobs TO app;
GRANT USAGE ON SEQUENCE jobs_id_seq TO app;

The app role itself is not created by a migration. In production the role and its password come from infrastructure; in tests the fixture creates it.

The function that applies migrations is reused later by the data migration test, so it lives in its own module, tests/integration/migrate.py:

from pathlib import Path

import psycopg

MIGRATIONS = Path(__file__).resolve().parents[2] / "migrations"


def version(path: Path) -> int:
    return int(path.name[1:].split("__")[0])


def migrate(url: str, *, start: int = 1, stop: int | None = None) -> None:
    """Apply migrations start..stop (inclusive) in version order."""
    with psycopg.connect(url, autocommit=True) as conn:
        for path in sorted(MIGRATIONS.glob("V*.sql"), key=version):
            v = version(path)
            if v < start or (stop is not None and v > stop):
                continue
            with conn.transaction():
                conn.execute(path.read_text())

tests/integration/conftest.py:

from pathlib import Path

import psycopg
import pytest
from testcontainers.community.postgres import PostgresContainer

from tests.integration.migrate import migrate


def pytest_collection_modifyitems(items):
    here = Path(__file__).parent
    for item in items:
        if here in item.path.parents:
            item.add_marker(pytest.mark.integration)


@pytest.fixture(scope="session")
def pg():
    with PostgresContainer("postgres:18", driver=None) as container:
        admin_url = container.get_connection_url()
        with psycopg.connect(admin_url, autocommit=True) as conn:
            # In production the role and its password come from infrastructure.
            conn.execute("CREATE ROLE app LOGIN PASSWORD 'app'")
        migrate(admin_url)
        host = container.get_container_host_ip()
        port = container.get_exposed_port(5432)
        app_url = f"postgresql://app:app@{host}:{port}/{container.dbname}"
        yield admin_url, app_url


@pytest.fixture
def connect(pg):
    """Open connections as the runtime role; empty every table afterwards."""
    admin_url, app_url = pg
    opened = []

    def _connect():
        conn = psycopg.connect(app_url)
        opened.append(conn)
        return conn

    yield _connect

    for conn in opened:
        conn.close()
    with psycopg.connect(admin_url, autocommit=True) as conn:
        tables = conn.execute(
            "SELECT format('%I.%I', schemaname, tablename) FROM pg_tables"
            " WHERE schemaname = 'public'"
        ).fetchall()
        if tables:
            names = ", ".join(t for (t,) in tables)
            conn.execute(f"TRUNCATE {names} RESTART IDENTITY CASCADE")


@pytest.fixture
def empty_db(pg):
    """A separate, unmigrated database on the same server."""
    admin_url, _ = pg
    with psycopg.connect(admin_url, autocommit=True) as conn:
        conn.execute("CREATE DATABASE migration_test")
    yield admin_url.rsplit("/", 1)[0] + "/migration_test"
    with psycopg.connect(admin_url, autocommit=True) as conn:
        conn.execute("DROP DATABASE migration_test WITH (FORCE)")

With psycopg 3, an execute() that takes no parameters can send a file containing several statements, or a function body quoted with $$, as is. Each migration file runs in its own transaction, so a file that fails halfway leaves nothing behind.

Isolate tests with TRUNCATE, not rollback

A common way to isolate database tests is to wrap each test in one transaction and roll it back at the end. It’s fast, but it didn’t work for this backend:

  • The code under test calls commit() itself, and a rollback can’t undo a commit.
  • The code under test takes its own connections from a pool, so it runs outside the transaction the test opened.
  • A concurrency test needs two connections, each with its own transaction. One wrapping transaction can’t hold both.

So the container starts once per session, and after each test every table is emptied with TRUNCATE ... RESTART IDENTITY CASCADE. Tests don’t rely on rows seeded by migrations. Each test creates the rows it needs with small row-building functions (factories).

TRUNCATE has three trade-offs:

  • TRUNCATE takes an ACCESS EXCLUSIVE lock on each table. If a transaction that touched the table is still open, TRUNCATE waits on it. That’s why the fixture closes the test’s connections first.
  • All tests share one database. To run them in parallel with pytest-xdist, each worker needs its own database, for example a copy of the migrated database made with CREATE DATABASE ... TEMPLATE.
  • TRUNCATE gets slower as the number of tables grows.

A retry leaves one row

Here is the enqueue from the start, tested on the real database:

from jobs import enqueue


def test_retry_does_not_enqueue_twice(connect):
    conn = connect()
    first = enqueue(conn, "job-42")
    conn.commit()
    second = enqueue(conn, "job-42")  # the worker retried
    conn.commit()

    assert first is not None
    assert second is None
    assert conn.execute("SELECT count(*) FROM jobs").fetchone() == (1,)

Delete ON CONFLICT and the second INSERT fails with UniqueViolation.

Reproducing a double claim with two connections

A worker claims one job with this SQL. The subquery locks one pending row, and the outer UPDATE marks it claimed.

def claim(conn: psycopg.Connection, worker: str) -> int | None:
    row = conn.execute(
        """
        UPDATE jobs SET status = 'claimed', worker = %s
        WHERE id = (
            SELECT id FROM jobs
            WHERE status = 'pending'
            ORDER BY id
            LIMIT 1
            FOR UPDATE SKIP LOCKED
        )
        RETURNING id
        """,
        (worker,),
    ).fetchone()
    return row[0] if row else None

Each of the three parts protects something different:

PartWhat happens without it
status = 'pending'A claimed job comes back again
FOR UPDATEBoth workers pick the same row. The later UPDATE waits for the first commit, re-checks only id, and overwrites the same row: a double claim
SKIP LOCKEDNo double claim, but the second worker waits until the first transaction ends

There are two tests:

from jobs import claim, enqueue


def test_claimed_job_is_not_handed_out_again(connect):
    conn = connect()
    enqueue(conn, "a")
    conn.commit()

    assert claim(conn, "w1") is not None
    conn.commit()
    assert claim(conn, "w1") is None


def test_concurrent_claims_skip_the_locked_row(connect):
    setup = connect()
    enqueue(setup, "a")
    enqueue(setup, "b")
    setup.commit()

    w1, w2 = connect(), connect()
    w2.execute("SET lock_timeout = '2s'")  # fail instead of hanging on a lock
    first = claim(w1, "w1")    # w1's transaction is still open
    second = claim(w2, "w2")   # must not wait for w1 or take the same row
    w1.commit()
    w2.commit()

    assert {first, second} == {1, 2}
    rows = setup.execute("SELECT id, worker FROM jobs ORDER BY id").fetchall()
    assert rows == [(1, "w1"), (2, "w2")]

You could write the second test by firing two claims at once with asyncio.gather, but whether the two queries actually overlap depends on timing. Keeping w1’s transaction open while w2 claims creates the same situation on every run. lock_timeout makes the test fail instead of hang if the implementation ever starts waiting on the lock.

Here is how each change makes them fail:

  • Remove status = 'pending' and the first test fails.
  • Remove SKIP LOCKED and the second test fails with LockNotAvailable.
  • Remove FOR UPDATE SKIP LOCKED entirely and the second test still fails, because w2’s UPDATE waits on w1’s row lock.

Re-running a data migration

A migration that transforms existing data also runs once when the schema is built. But the tables are empty at that point, so the transformation itself is never exercised. And once every migration has run, the old column is gone, so you can’t insert rows in the pre-migration shape either.

As an example, take a migration that moves an array of assignees out of a JSON column into its own table:

-- V2__tasks.sql
CREATE TABLE tasks (
    id        bigserial PRIMARY KEY,
    assignees jsonb NOT NULL DEFAULT '[]'
);
GRANT SELECT, INSERT, UPDATE, DELETE ON tasks TO app;
GRANT USAGE ON SEQUENCE tasks_id_seq TO app;

-- V3__task_assignees.sql
CREATE TABLE task_assignees (
    task_id  bigint NOT NULL REFERENCES tasks (id),
    position int    NOT NULL,
    user_id  text   NOT NULL,
    PRIMARY KEY (task_id, position)
);
GRANT SELECT, INSERT, UPDATE, DELETE ON task_assignees TO app;

INSERT INTO task_assignees (task_id, position, user_id)
SELECT t.id, a.ord - 1, a.user_id
FROM tasks t,
     jsonb_array_elements_text(t.assignees) WITH ORDINALITY AS a (user_id, ord);

ALTER TABLE tasks DROP COLUMN assignees;

The test creates a separate, unmigrated database, migrates it up to the migration just before the target, inserts rows in the old shape, runs the target migration, and checks the result.

import psycopg

from tests.integration.migrate import migrate


def test_assignees_move_to_their_own_table(empty_db):
    migrate(empty_db, stop=2)  # up to the migration just before the target
    with psycopg.connect(empty_db) as conn:
        conn.execute("""INSERT INTO tasks (assignees) VALUES ('["ann", "bob"]'), ('[]')""")

    migrate(empty_db, start=3, stop=3)  # the target migration

    with psycopg.connect(empty_db) as conn:
        rows = conn.execute(
            "SELECT task_id, position, user_id FROM task_assignees ORDER BY task_id, position"
        ).fetchall()
        assert rows == [(1, 0, "ann"), (1, 1, "bob")]
        column = conn.execute(
            "SELECT 1 FROM information_schema.columns"
            " WHERE table_name = 'tasks' AND column_name = 'assignees'"
        ).fetchone()
        assert column is None

empty_db only creates a database inside the same container, which is faster than starting a new container.

Split unit and integration lanes

Real-database tests are slower because they start a container, and they need Docker. So a plain pytest runs only the fast unit lane, and the real-database tests run only when asked for.

[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
addopts = "-m 'not integration' --timeout=120"
markers = [
    "integration: runs against a real PostgreSQL",
]
  • pytest is the unit lane. -m 'not integration' in addopts leaves out the real-database tests.
  • pytest -m integration tests/integration is the integration lane. A -m given on the command line overrides the one in addopts.
  • The directory decides the lane. The conftest in tests/integration/ adds the integration marker to every test under it, so nobody has to remember the marker. Unit tests go under tests/ in the same layout as src/. Even for integration code, a test that never touches the database, like webhook HMAC signature verification, stays in the unit lane.
  • --timeout comes from pytest-timeout. Once, code that a unit test forgot to mock reached for a real database connection and the test hung. With a timeout, a hang shows up as a test failure.

Running the whole suite at once also turned up problems nobody had seen. Under pytest’s default import mode (prepend), two test files with the same name in directories without __init__.py fail to collect with import file mismatch. The suite had only ever been run one directory at a time, so nobody noticed. Adding __init__.py to each test directory fixed it.

The integration lane in CI

The unit lane runs on every pull request. The integration lane is a separate workflow that runs on pull requests touching the backend or migrations, on pushes to main, and on demand.

name: integration

on:
  pull_request:
    paths:
      - "src/**"
      - "migrations/**"
      - "tests/**"
      - "pyproject.toml"
      - "uv.lock"
      - ".github/workflows/integration.yml"
  push:
    branches: [main]
  workflow_dispatch:

jobs:
  integration:
    runs-on: ubuntu-latest
    timeout-minutes: 15
    steps:
      - uses: actions/checkout@v7
      - uses: astral-sh/setup-uv@v10
        with:
          python-version: "3.12"
      - run: uv sync --locked
      # testcontainers starts postgres:18 on the runner's Docker
      - run: uv run pytest -m integration tests/integration

GitHub-hosted Ubuntu runners come with Docker, so testcontainers starts the container on the runner’s Docker directly. There’s no need for a separate PostgreSQL under services:, and the same fixture runs locally and in CI. With dummy settings for the app set in tests/conftest.py, no secrets are needed either.

Be careful if you make a paths-filtered workflow a required status check. When the paths don’t match and the workflow is skipped, the check stays Pending and the pull request can’t be merged.

Nobody reads a skipped failure

To make the unit lane a pull request gate from day one, existing tests that only passed on a developer machine went on a skip list. They called a real LLM API, a development database, or cloud storage. Each entry carried a reason such as “real DB”.

The list did reach zero, but not the way it was planned:

  • Only one kind of test moved to the real-database lane: tests that read and wrote specific rows in the shared development database. They were rewritten to build their own rows with factories.
  • Most of them disappeared along with the code they tested, which was deleted.
  • The last two said “real DB” but never touched a database. They failed because they asserted an old message text the handler no longer used. Fixing the assertions brought them back. They had been skipped for eight weeks.

A reason written on a skip list goes stale as the code changes, and nobody reads what a skipped test actually fails on. Keep the skip list empty: fix the test or delete it.

Summary

A mocked test checks how a function was called. A guarantee placed in SQL can only be checked when PostgreSQL actually runs that SQL. If your guarantees live in ON CONFLICT, FOR UPDATE SKIP LOCKED, GRANT, or a data migration, run those tests on the same PostgreSQL as production, and run them in CI as a lane separate from the fast unit tests.