WORKINGCHAPTER 12

Test data and fixtures: building the world a test needs

Every test needs a world to run in. Build it fresh, name only what matters, and a shuffled run stops being a surprise

45 MINSOFTWARE TESTING AND QUALITYUPDATED 2026-11-23
PREDICT

A test file has four tests that share one module-scoped catalogue. In file order all four pass. A new plugin now runs the file in a random order. What do you expect over ten runs?

A test is a small experiment. It needs a world to run in: a catalogue with products, a product with stock, a clock set to a time, a provider that answers a certain way. That world is the fixture. The word is older than any test framework. It comes from the engineering fixture that holds a part still while you work on it. Everything in this chapter is about two questions. How do you build the world? And who else can see it while you do?

What goes wrong before what fixes it

The bug in Tallowmere’s suite is not in a test. It is in what two tests share. A shared fixture is state that lives longer than one test: a module-level variable, a database that is set up once per file, a row left behind in a table, a file at a fixed path. If any test changes it, every later test inherits the change.

Gerard Meszaros calls the result Interacting Tests and files it under Erratic Test in the reading list. The symptoms are always the same. A test passes alone and fails in the suite. A test passes in the suite and fails alone. A suite goes green on one machine and red on another because the files are collected in a different order. A new test, added in the middle, breaks a test that has nothing to do with it.

▶ SIMULATION
RUNNER
fixture: shared, module-level
ran: —
FIXTURE NOW
users: []
cache: {} · db calls: 0
WHAT THE TEAM SEES
—
last—
✓ the build is red exactly when the code is wrong (the code is right)
SCHEDULE
01[RUNNER]runner: file order, one shared fixture
02[T1]t1: register adds a user
03[T2]t2: first lookup hits the database
04[T3]t3: register is idempotent
05[T4]t4: removeAll empties the list
06[RUNNER]report
Start of file order, shared fixture scenario. 6 steps.
const fixture = { users: [], cache: new Map(), dbCalls: 0 };  // module level: every test sees it

test('register adds a user', () => {
  register(fixture, 'alice');
  expect(fixture.users).toHaveLength(1);   // true only if nothing ran before
});

Run the three scenarios in order. In file order, shared fixture all four tests pass, because each one leaves exactly the state the next one assumes. In shuffled, shared fixture the same four tests, unchanged, fail. In the third scenario each test gets a fresh fixture and the same shuffle goes green. Watch the failure messages: one says expected 1 user, found 2, which names a test that did not run first. The lesson page, Order-dependent tests, has the exercises. This chapter is the same mechanism on a real suite, with a real database and a real runner.

Two things make the problem worse over time. A shared fixture is a bet that no test will ever modify it. The bet is lost the first time somebody under deadline pressure writes shop.add_product(...) into a test, because the test passes, and the damage shows up in a different file weeks later. And the failure is far from the cause. Unathi’s red test did not touch prescriptions. The test that changed the state was in another module.

Five ways to build the world

For checkout/ the world is a database with products, stock and sometimes orders. There are five usual ways to get one. They trade speed, clarity and isolation.

Way How it looks Good at Bad at
Rows by hand db.add_product("adire-house", "Aso-oke cap", 650_000, "published", 5) in the test The test is self-contained Five arguments, one of which matters; copied into every test
Factory or builder make_product(on_hand=5) Defaults hide the irrelevant fields; a test names only what it cares about Someone must keep the defaults valid
Object Mother Products.aso_oke_cap(), a named ready-made object Reads like a domain term Becomes a catalogue of special cases; tests couple to what the mother happens to contain
Dump or snapshot load a saved .sql or .sqlite file Fast, even for big data Frozen schema; the dependency is invisible in the test
Shared fixture one module- or session-scoped database Fastest to run Interacting tests

Martin Fowler’s note on the Object Mother (2006) names the pattern and its weakness in one line: shared sample data couples many tests to it. Nat Pryce’s Test Data Builder keeps the idea of a ready-made object but builds it from defaults, with a method to change one thing at a time. In Python the common spelling is a function with keyword arguments, and pytest has a name for it: factories as fixtures, in the pytest guide linked below.

The rule of thumb that follows: build fresh with a factory by default; reach for a dump or a shared fixture only when you can say what you are buying and what you are paying.

A factory has one job: say what matters

Compare two tests of the same rule: you cannot buy more than is on hand.

def test_cannot_buy_more_than_is_on_hand(db, payments, clock):
    product = db.add_product("adire-house", "Aso-oke cap", 650_000, "published", 5)
    with pytest.raises(OutOfStock):
        place_order(db, payments, clock, [{"product_id": product["id"], "qty": 6}], "key-1")
    assert db.stock_of(product["id"]) == 5
def test_cannot_buy_more_than_is_on_hand(db, payments, clock, make_product):
    product = make_product(on_hand=5)
    with pytest.raises(OutOfStock):
        place_order(db, payments, clock, [{"product_id": product["id"], "qty": 6}], "key-1")
    assert db.stock_of(product["id"]) == 5

The seller, the name, the price and the status are the same noise in both. In the first, a reader has to work out which of the five arguments the rule depends on. In the second, on_hand=5 is the only thing written, so it is the only thing that matters. Test data should read like a specification: the defaults are the background and the overrides are the story.

That gives three rules for a factory’s defaults.

  1. The default is the boring, valid case. A product that is published, in stock and priced above zero. A test about a draft says status="draft" and nothing else, and that is the only reason the word appears.
  2. A factory never reads another test’s state. It builds a row from its own arguments and returns it. If it looks up “the first product” it has become a shared fixture again.
  3. A factory that creates a dependency builds it too. make_order makes its own product unless you pass one. The test says what it needs, not how to assemble it.

Defaults are a contract, and the lab’s last step shows what breaks when someone changes one. That is the price of a factory: one place to fix, and one place where a careless change reaches every test.

Cleaning up

Fresh fixtures need discarding. pytest’s yield fixtures run the lines after yield when the test ends, whether it passed or failed:

@pytest.fixture
def uploaded_file(tmp_path):
    path = tmp_path / "catalogue.csv"
    path.write_text("name,price_kobo\n")
    yield path
    # anything here runs at teardown

For the lab’s database, none is needed. pytest’s tmp_path gives each test its own directory and removes old ones later, so a new Database(str(tmp_path / "test.sqlite")) is isolated by construction. That is the best kind of cleanup: not having a shared thing to clean. Where a test must use something external (a real port, a shared staging database), the teardown has to undo what the test did, and you must decide what happens when the teardown itself fails.

Scope: who can see the fixture

pytest names five scopes: function (the default, one build per test), class, module, package and session. A wider scope shares the fixture among more tests and builds it fewer times. The speed is real. So is the risk, and the risk depends on one question: can any test change it?

Scope Safe when Unsafe when
function always never; the cost is build time
module, session the fixture is read-only: a parsed config, a compiled schema, a template database that tests copy any test writes to it

A fixture of wide scope can be a good idea if tests only read it. The pattern that gives you speed without sharing is a template: build the expensive thing once at session scope, then give every test a copy. The lab’s step 6 times the idea: copying a database file takes under a millisecond, building 500 rows through the repository takes most of a second.

Note also what pytest enforces. A module-scoped fixture cannot use the function-scoped tmp_path, because the wider fixture would outlive the narrower one. That is why the lab’s shared fixture asks for tmp_path_factory instead. pytest is telling you the fixture has a different lifetime from a test, so you should ask whether it should.

Making order bugs loud

You find interacting tests by changing the order. pytest-randomly (pinned in the lab) shuffles the order of modules, then classes, then functions, on every run, and prints the seed it used:

Using --randomly-seed=1719508704

It also reseeds random at the start of every test, so a test that uses random values gets the same ones when you reuse the seed. Three commands cover almost every case:

Command What it does
pytest A new random order each run; the seed is in the header
pytest -p randomly --randomly-seed=1719508704 The same order as that run. Write --randomly-seed=<your seed>
pytest -p no:randomly The order the files and functions are written in; useful to show the failure belongs to the order

The three together are the method. A red run with the seed in the log can be replayed on anyone’s machine. A run that is red under the seed and green under -p no:randomly is an order dependency, not a bug in the code. Running in parallel with pytest -n auto (pytest-xdist, also pinned) exposes the same class of bug by a different route: tests on different workers see different leftover state, and share any fixed file path or port.

Do not turn the plugin off when it finds a failure. It found a real defect in your suite, at the cheapest moment to fix it.

Data that does not come from a dump of production

Teams sometimes fill test databases from a copy of production. It looks realistic and it fails in three ways. The copy contains customers’ names and, in a pharmacy, what they were prescribed, and a test database is not guarded like production. The data is large, so every run is slow. And a test that relies on a particular row in the copy fails the day the row is deleted. Build what the test needs, give it clearly artificial values, and keep the naira figures illustrative.

A hand-built dump is a different thing: a small, checked-in file made for tests. It is a good choice for a fixture that is big and read-only, such as a thousand-product catalogue for a search test. Three costs come with it. It carries the schema as it was when you dumped it, so after a migration the dump builds a database the application no longer uses. It hides the test’s dependencies, because the test says load("catalogue.sql") and a reader cannot tell that the test needs a product with 5 in stock. And it ages: the one row somebody needs for a new test is edited into the file, and every other test now sees it. If you keep dumps, regenerate them from the factories and the migrations in a script, so the file is an output and not a hand-edited source.

What to do on Monday

  • Run your suite with a random order and with -n 4. Count the failures. That number is the size of your hidden state.
  • Search for scope="module" and scope="session". For each, ask whether any test writes to it.
  • Find the setup that three tests repeat and give it a factory with boring defaults.
  • Make a rule that a bug found by order is fixed, not rerun.

The Careers track has the same material from the quality engineer’s side: Test data, environments and flaky tests. The next chapter in this module, Flaky tests: causes, quarantine and cure, deals with the failures that stay random after the order is fixed.

LAB Shuffle a shared fixture until it breaks ~35 MIN
YOU NEEDPython 3.9+ with the lab set up (README, 'Set up')labs/testing, with .venv created

You will write factories, then build a shared catalogue on purpose, shuffle the tests until it fails, reproduce the failure from its seed, and fix it. Work from labs/testing. Every test here uses a temporary database under pytest’s temporary directories (tmp_path, and tmp_path_factory for the shared one in step 3), so nothing touches data/.

cd labs/testing
.venv/bin/pytest -q
23 passed, 1 skipped, 1 deselected: the starter suite on clean code. Everything below adds to it.

1. Write a test with rows by hand.

Create tests/integration/test_stock_by_hand.py:

import pytest

from checkout.inventory import OutOfStock
from checkout.orders import place_order

def test_cannot_buy_more_than_is_on_hand(db, payments, clock):
    product = db.add_product("adire-house", "Aso-oke cap", 650_000, "published", 5)
    with pytest.raises(OutOfStock):
        place_order(db, payments, clock, [{"product_id": product["id"], "qty": 6}], "key-1")
    assert db.stock_of(product["id"]) == 5
.venv/bin/pytest tests/integration/test_stock_by_hand.py -q
1 passed. The test works. Look at the add_product line and ask which of its five arguments the rule depends on. Only the last.

2. Add factories to tests/conftest.py.

Append to the end of tests/conftest.py:

@pytest.fixture
def make_product(db):
    """Build a product row. Every argument has a default; a test names only what it cares about."""

    def make(seller_id="test-seller", name="Test product", price_kobo=100_000, status="published", on_hand=10):
        return db.add_product(seller_id, name, price_kobo, status, on_hand)

    return make

@pytest.fixture
def make_order(db, make_product, payments, clock):
    """Place a real order through place_order. Builds its own product unless you pass product_id."""
    from checkout.orders import place_order

    counter = {"n": 0}

    def make(qty=1, product_id=None, key=None, on_hand=10):
        if product_id is None:
            product_id = make_product(on_hand=on_hand)["id"]
        counter["n"] += 1
        order, _ = place_order(
            db, payments, clock, [{"product_id": product_id, "qty": qty}], key or "order-%d" % counter["n"]
        )
        return order

    return make

Create tests/integration/test_stock_with_builder.py:

import pytest

from checkout.inventory import OutOfStock
from checkout.orders import place_order

def test_cannot_buy_more_than_is_on_hand(db, payments, clock, make_product):
    product = make_product(on_hand=5)
    with pytest.raises(OutOfStock):
        place_order(db, payments, clock, [{"product_id": product["id"], "qty": 6}], "key-1")
    assert db.stock_of(product["id"]) == 5

def test_an_order_takes_stock(db, make_order):
    order = make_order(qty=3, on_hand=10)
    assert db.stock_of(order["lines"][0]["product_id"]) == 7
.venv/bin/pytest tests/integration/test_stock_with_builder.py tests/integration/test_stock_by_hand.py -q
3 passed. The first builder test says only on_hand=5. Both fixtures are function-scoped, so each test has its own db and its own rows.

3. Share a catalogue across a module, on purpose.

Create tests/integration/test_shared_catalogue.py. Its fixture is built once per file and the tests change it:

import pytest

from checkout.db import Database

@pytest.fixture(scope="module")
def shop(tmp_path_factory):
    database = Database(str(tmp_path_factory.mktemp("shared") / "shared.sqlite"))
    database.seed()
    return database

def test_catalogue_starts_with_four_products(shop):
    assert len(shop.list_products()) == 4

def test_a_new_product_is_listed(shop):
    shop.add_product("shea-co", "Black soap", 150_000, "published", 20)
    assert len(shop.list_products(status="published")) == 4

def test_aso_oke_cap_has_five_in_stock(shop):
    assert shop.stock_of(3) == 5

def test_selling_every_cap_leaves_none(shop):
    assert shop.take_stock(3, 5) is True
    assert shop.stock_of(3) == 0

Each test is correct for the order it is written in. Run it in that order first:

.venv/bin/pytest tests/integration/test_shared_catalogue.py -p no:randomly -q
4 passed. File order leaves exactly the state each test assumes: four products, then five, then a cap that is not yet sold.

4. Shuffle, and catch a failure.

Run it with the shuffle on. Omit -q so the header shows the seed. Repeat until a run fails (it did in four runs of six here):

.venv/bin/pytest tests/integration/test_shared_catalogue.py 2>&1 | grep -E "randomly-seed|passed|failed"
A line like Using --randomly-seed=1719508704, then 1 failed, 3 passed (2 failed, 2 passed is common too). Your seed will be different, and some runs pass with 0 failed. A failing run said assert 5 == 4 for test_catalogue_starts_with_four_products: the test that adds a product ran first. Another gave assert 0 == 5 for the cap stock: the test that sells every cap ran first. Nothing in the code is wrong.

5. Reproduce it from the seed, then make it vanish.

Use the seed from your own failing run:

.venv/bin/pytest tests/integration/test_shared_catalogue.py --randomly-seed=1719508704 -v 2>&1 | grep -E "PASSED|FAILED"
.venv/bin/pytest tests/integration/test_shared_catalogue.py --randomly-seed=1719508704 -q 2>&1 | tail -1
.venv/bin/pytest tests/integration/test_shared_catalogue.py -p no:randomly -q 2>&1 | tail -1
The first command lists the four tests in the order they ran, with the failed one marked FAILED (with seed 1719508704, test_catalogue_starts_with_four_products ran after test_a_new_product_is_listed). The second fails every time you repeat it: 1 failed, 3 passed. The third, in file order, shows 4 passed. A failure that follows the seed and disappears without the plugin is an order dependency.

6. Fix it with function scope, then compare three ways to build.

In tests/integration/test_shared_catalogue.py, change the fixture to build a fresh database for each test:

@pytest.fixture
def shop(tmp_path):
    database = Database(str(tmp_path / "shop.sqlite"))
    database.seed()
    return database
for i in 1 2 3 4 5 6 7 8; do .venv/bin/pytest tests/integration/test_shared_catalogue.py -q 2>&1 | tail -1; done
Eight lines of 4 passed. Every test starts from four products and the cap at 5, so the order cannot matter. The cost is seeding four rows per test, which is invisible here and not for a big catalogue. Measure that cost next.

Create tests/integration/test_catalogue_three_ways.py. It builds a 500-product catalogue three ways and prints how long each takes:

"""The same 500-product catalogue, built three ways. Run with -s to see the timings."""

import sqlite3
import time

from checkout.db import Database

N = 500

def by_hand_rows(db):
    for i in range(N):
        db.add_product("seller-%d" % (i % 10), "Product %d" % i, 100_000 + i, "published", 20)

def test_three_ways_to_get_a_catalogue(tmp_path):
    # 1. rows by hand, through the repository
    hand = Database(str(tmp_path / "hand.sqlite"))
    t0 = time.perf_counter()
    by_hand_rows(hand)
    t_hand = time.perf_counter() - t0

    # 2. a dump taken once, loaded into a fresh file
    dump = "\n".join(sqlite3.connect(hand.path).iterdump())
    loaded = tmp_path / "loaded.sqlite"
    t0 = time.perf_counter()
    conn = sqlite3.connect(str(loaded))
    conn.executescript(dump)
    conn.close()
    t_dump = time.perf_counter() - t0

    # 3. a file copy of a database built once (what a session-scoped template gives you)
    t0 = time.perf_counter()
    (tmp_path / "copy.sqlite").write_bytes(open(hand.path, "rb").read())
    t_copy = time.perf_counter() - t0

    print("\nby hand %.1f ms, dump %.1f ms, file copy %.1f ms" % (t_hand * 1000, t_dump * 1000, t_copy * 1000))
    assert len(Database(str(loaded)).list_products()) == N
.venv/bin/pytest tests/integration/test_catalogue_three_ways.py -s -q 2>&1 | grep "by hand"
.venv/bin/pytest -q
Three runs here printed by hand 628.8 ms, dump 2.6 ms, file copy 0.3 ms, by hand 698.9 ms, dump 2.4 ms ... and by hand 1004.9 ms, dump 3.1 ms .... Your numbers differ. Building through the repository costs hundreds of times more than loading, because each add_product opens a connection and commits. The full suite then shows 31 passed, 1 skipped, 1 deselected: the 23 starter tests plus your 8. A copy of a template database gives you the speed of a dump with none of the sharing.

Break it. In tests/conftest.py, change the default in make_product from status="published" to status="draft". Run .venv/bin/pytest tests/integration/test_stock_with_builder.py -q -p no:randomly.

Both tests fail with checkout.orders.UnknownProduct: unknown or unavailable product 5, and neither mentions status: only published products can be bought, and the factory now builds drafts. One default, changed in one place, broke every test that relied on it. Put it back to "published". Then decide how you would stop this: a test of the factory itself, a test that says what a default product can do, or a rule that a default is only ever changed with a run of the whole suite.

Put the lab back. Run git checkout tests/conftest.py and delete tests/integration/test_stock_by_hand.py, test_stock_with_builder.py, test_shared_catalogue.py and test_catalogue_three_ways.py. pytest -q should print 23 passed, 1 skipped, 1 deselected again.

DECIDE

Tallowmere's suite of 300 database tests takes four minutes. Sekou proposes loading one 2,000-product catalogue at module scope from a dump, which would take it to forty seconds. Unathi points out that about forty of the tests add or delete products, and the suite already fails about once a week on a shuffled run. The nine engineers want a fast suite and few false alarms.

READING
  1. DOC
    pytest: How to use fixtures

    The reference for scope, yield teardown and the 'Factories as fixtures' section behind the lab's make_product. Read those three parts; skip dynamic scope and the autouse and parametrized-fixture sections until you need them. Read on 2026-11-23.

  2. BOOK
    Meszaros, 'Fresh Fixture' (xUnit Test Patterns) Gerard Meszaros, 2007

    The pattern's own statement of why each test builds its own world and what that costs. Read the strategy comparison; skip the language-specific examples. The site serves over plain HTTP only. Read: The pattern page; the book's chapter on fixture setup strategies covers the same ground in full.

  3. POST
    Fowler, 'ObjectMother' Martin Fowler, 2006

    A short note that names the Object Mother pattern and its coupling problem. Read it all; it takes two minutes and explains why the lab uses a factory with overrides instead of named ready-made products.

  4. POST
    Pryce, 'Test Data Builders: an alternative to the Object Mother pattern' Nat Pryce, 2007

    The builder idea in its own words: sensible defaults, change one thing at a time. The examples are Java; read for the shape, not the syntax.

  5. CODE
    pytest-randomly

    What the plugin shuffles, how it seeds, and the exact options (--randomly-seed, -p no:randomly) used in the lab. Read the README top to bottom; it is short.

  6. BOOK
    Meszaros, 'Erratic Test' (xUnit Test Patterns) Gerard Meszaros, 2007

    A catalogue of why tests pass and fail at random, with Interacting Tests and Shared Fixture as the first suspects. Skim the causes you do not recognise; read the one you do. The site serves over plain HTTP only. Read: The causes list, especially Interacting Tests and its sub-causes.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Flaky tests: causes, quarantine and cure →