Sub topic 10
Keeping generated data deterministic
This chapter assumes you can write pytest tests and have read the earlier chapters on defaults, overrides, and sequences. You should know what make_user and make_order do.
Why determinism matters
A test is deterministic when the same code and the same inputs give the same result on every run. Factories can break this in two ways:
- They draw values from an unseeded random source, so each run sees different data.
- They depend on state that changes between runs, such as the clock or a shared counter.
A test that fails once in fifty runs is hard to fix because you can't recreate the failing data. The goal is not to remove randomness. The goal is to make every random run reproducible.
Prefer fixed defaults
Most fields don't need random values. Defaults like role="member" and total_cents=1000 are the same on every run. Use randomness only where varied input helps find bugs, such as amounts, strings, or dates. For everything else, use a constant.
Seed a random generator
Python's random.Random(seed) creates a generator that gives the same sequence for the same seed. Pass the generator to the factory instead of calling the global random functions. This keeps the randomness explicit and local to the test.
import os
import random
from dataclasses import dataclass
import pytest
@dataclass
class Order:
id: int
total_cents: int
status: str
def make_order(**overrides):
defaults = {"id": 1, "total_cents": 1000, "status": "pending"}
return Order(**{**defaults, **overrides})
def make_random_total(rng):
return rng.randint(100, 50_000)
@pytest.fixture
def rng():
seed = int(os.environ.get("TEST_SEED", random.SystemRandom().randrange(2**32)))
print(f"seed={seed}")
return random.Random(seed)
def test_total_is_never_negative(rng):
order = make_order(total_cents=make_random_total(rng))
assert order.total_cents > 0The fixture uses the TEST_SEED environment variable if it is set. Otherwise it picks a fresh seed. It prints the seed either way. Pytest shows captured output for failing tests, so a failure includes its seed.
To replay a failure, run TEST_SEED=12345 pytest. The same seed produces the same values.
Other sources of nondeterminism
Seeding the generator doesn't cover everything. Watch for these:
| Source | Problem | Fix |
|---|---|---|
| `datetime.now()` in a factory | The value changes every run, and tests near midnight can break | Use a fixed date as the default |
| Global counters | Ids depend on how many tests ran before | Assert on relationships, not literal ids |
| Test order and parallel runs | Shared sequences give different ids per worker | Don't depend on exact sequence values |
| Unordered collections | Sets and some query results have no guaranteed order | Sort before comparing |
Sequences are deterministic only if the order of calls is. If a test asserts user.id == 7, it breaks when another test is added or the run order changes. Assert on what the test controls instead.
Keep the seed visible
Reproducibility works only if you can find the seed. A few habits help:
- Print the seed in the test output, as the fixture above does.
- Accept an override through an environment variable, so CI failures can be replayed locally.
- Create one generator per test, not one for the whole session. A session-wide generator makes each test's data depend on which tests ran before it.
Common errors
- Calling
random.randintdirectly inside a factory. The factory then has hidden randomness that no test can control. - Printing the seed after the failure point, or not at all.
- Using random values for fields the test doesn't care about. Extra variation adds noise without finding more bugs.
- Letting a test override only some of the random fields and then wondering why the others change between runs.
Exercise
A test fails on CI with assert order.total_cents < 40000, and it passes on your machine. The factory call is make_order(total_cents=make_random_total(rng)). What do you need from the CI log to reproduce the failure, and how do you use it?
Show answer
You need the seed that the rng fixture printed. Run the test locally with TEST_SEED=<that seed> pytest. The seeded generator then produces the same total as on CI, so the failure repeats. Once you find the cause, add a regression test with the failing total written as a constant.