Sub topic 10
Keeping generated data deterministic
This chapter assumes you can write a factory function with overrides and sequences, as in the earlier chapters, and that you know basic pytest usage. A factory is deterministic when the same inputs always produce the same objects. Determinism does not mean "no randomness". It means any randomness you use can be replayed.
Why nondeterminism hurts
A test that fails one run in fifty is worse than a test that always fails. You can't fix a failure you can't reproduce, and the team learns to rerun red builds instead of reading them.
Random test data causes this when the data hits an edge case only occasionally. Here is a rule with an off-by-one bug:
import random
def qualifies_for_free_shipping(total_cents):
return total_cents > 5000 # bug: the rule says "5000 or more"
def test_free_shipping_threshold():
total = random.choice([4999, 5000, 5001])
assert qualifies_for_free_shipping(total) is (total >= 5000)This test fails about one run in three, and nothing in the failure message says which value was drawn. A fixed list of the three boundary values, each in its own test, would catch the bug every time. Random data can still find bugs you didn't think of, but only if you can replay the run that found one.
Where nondeterminism comes from
Randomness from random is only one source. Any of these can make a factory return different data on different runs.
| Source | Example | Fix |
|---|---|---|
| Global random generator | `random.randint(...)` | Pass a seeded `random.Random` instance |
| Current time | `datetime.now()` as a default | Use a fixed timestamp or accept a `now` argument |
| Random identifiers | `uuid.uuid4()` | Build UUIDs from a seeded generator |
| Set ordering | `random.choice(list(some_set))` | Choose from a list or a sorted sequence |
| Global counters | Sequence values that depend on how many tests ran first | Don't assert on generated ids |
| External state | Reading environment variables or files in a factory | Pass values in as arguments |
The set ordering case surprises people. In Python, the iteration order of a set of strings changes between processes because string hashing is randomized. A factory that picks "the first element" of a set returns different data each run, even with a seeded generator.
Sequences are deterministic, but order dependent
The count() sequence from the earlier chapters is predictable inside one process. The value a given test receives depends on how many objects earlier tests created. Run a single test alone, run the suite in a different order, or split it across workers with pytest-xdist, and the same test sees different ids and emails.
Treat sequence values as unique but not meaningful. A test may assume two users have different emails. It must not assert that a user's id is 1 or that the email is [email protected]. If a test needs a specific value, override it:
def test_welcome_message_uses_email():
user = make_user(email="[email protected]")
assert "[email protected]" in welcome_message(user)If you need ids that restart for each test, reset the counter in a fixture. That works for a single process, but it hides the order dependence instead of removing it, so prefer not asserting on ids.
Seeded random generators
Python's random.Random(seed) creates a generator object with its own state. Two generators built with the same seed produce the same sequence of values. This is the building block for replayable random data.
import random
def make_random_total(rng):
return rng.randint(100, 50_000)
first = random.Random(12345)
second = random.Random(12345)
assert [make_random_total(first) for _ in range(5)] == [
make_random_total(second) for _ in range(5)
]
print("same seed, same totals")Pass the generator into your factories explicitly. Avoid calling random.seed(...) on the module-level generator. That state is shared by every piece of code in the process, including libraries, so a different import or a different test order can change which values your test receives.
ROLES = ["member", "editor", "admin"] # a list, so the order is stable
def make_random_user(rng, **overrides):
return make_user(**{"role": rng.choice(ROLES), **overrides})Here make_user is the factory from the earlier chapters. The random choice is a default, and overrides still wins, so a test that cares about the role can still set it.
Draw order matters
A seed fixes the sequence of values, not which value goes to which field. If you add a new rng.choice(...) call in the middle of a factory, every later draw shifts. A seed that used to reproduce a failure now produces different data. Two habits reduce this problem:
- Draw values in a fixed order, and add new draws at the end of a factory.
- Save the generated data, not only the seed, when a failure is important. Print the object, or save its fields, in the failure message.
Reporting the seed
A seed helps only if you can read it after the failure. The usual design is:
- Use the seed from an environment variable if one is set, so a developer can replay a run.
- Otherwise generate a fresh seed, so each normal run explores different data.
- Always print the seed.
# conftest.py
import os
import random
import secrets
import pytest
def choose_seed():
value = os.environ.get("TEST_SEED")
if value is not None:
return int(value)
return secrets.randbelow(2**32)
def pytest_configure(config):
config.test_seed = choose_seed()
def pytest_report_header(config):
return f"test seed: {config.test_seed}"
@pytest.fixture
def rng(request):
seed = f"{request.config.test_seed}:{request.node.nodeid}"
return random.Random(seed)The rng fixture combines the run's seed with the test's id. Each test gets its own generator, so the data one test sees does not depend on which tests ran before it. Python accepts a string as a seed and turns it into the same state every time, in every process.
A test uses it like this:
def test_total_is_positive(rng):
order = make_order(total_cents=make_random_total(rng))
assert order.total_cents > 0To replay a failed CI run, copy the seed from the report header and set it:
# shell: TEST_SEED=2891736402 pytest tests/test_orders.pyThe header does not appear when you run pytest with -q. If your CI uses -q, print the seed through your own logging instead.
Time and identifiers
Defaults based on the current time are a common hidden source of flaky tests. A test that builds an object with datetime.now() and then checks "expires in 30 days" can fail near midnight, at a month boundary, or across a daylight-saving change. Use a fixed timestamp as the default, and let tests override it.
from datetime import datetime, timedelta, timezone
FIXED_NOW = datetime(2026, 1, 15, 12, 0, tzinfo=timezone.utc)
def make_expiry(now=FIXED_NOW, days=30):
return now + timedelta(days=days)
assert make_expiry() == datetime(2026, 2, 14, 12, 0, tzinfo=timezone.utc)If the code under test reads the clock itself, give that code a clock argument or use a time-freezing tool. The factory should not call the clock either way.
Random UUIDs need the same treatment. uuid.uuid4() reads the operating system's entropy and can't be seeded. To get UUIDs that are valid version 4 values but reproducible, build them from your generator:
import random
import uuid
def make_uuid(rng):
return uuid.UUID(int=rng.getrandbits(128), version=4)
rng = random.Random(7)
print(make_uuid(rng))Do not use these for anything security-sensitive. They exist only for test data.
Seeding factory libraries
The libraries from the earlier chapter have their own random sources. factory_boy keeps a shared generator that you can reseed. Faker, which factory_boy uses for fake names and addresses, has its own seed. Set both in one place, such as conftest.py:
import factory.random
from faker import Faker
def seed_factories(seed):
factory.random.reseed_random(seed)
Faker.seed(seed)Call this at the start of each test, or from an autouse fixture that uses the same per-test seed shown above. Without a per-test seed, the values a test receives depend on how much random data earlier tests drew.
When not to use random data
Determinism is easier when you use less randomness. Prefer fixed values for anything a test asserts on. Use random data when the exact value doesn't matter and you want broad coverage, such as many different totals passing through a pricing function. Tests of specific rules, such as the shipping threshold above, should name their boundary values directly.
Common mistakes
- Seeding the global
randommodule and assuming nothing else uses it. - Choosing from a set, or from a dict built in an unstable order.
- Printing the seed only on success, or not at all.
- Asserting on generated ids or on
[email protected]. - Adding a draw in the middle of a factory and then wondering why an old seed no longer reproduces the failure.
Exercise
A test fails in CI with a random total, and a teammate reruns it locally with the same TESTSEED but it passes. The factory uses a seeded random.Random, and the failing test also builds an object with a default createdat of datetime.now(). Name two likely causes and one fix for each.
Show answer
Likely cause 1: the default createdat reads the clock, so the data differs between the CI run and the local run even with the same seed. Fix: use a fixed timestamp default such as FIXEDNOW, or pass a now argument. Likely cause 2: the factory code changed between the CI commit and the local checkout, for example a new rng draw was added in the middle, which shifts every later value drawn from the same seed. Fix: check out the same commit as CI, and add new draws at the end of the factory. A related cause is a set or other unordered collection used to pick a value, fixed by choosing from a list.
Exercise
Why does the rng fixture in this chapter build its seed from both the run seed and request.node.nodeid, instead of returning random.Random(run_seed) for every test?
Show answer
With one shared seed per test, each test would start from the same generator state and receive identical random values, so tests would not explore different data. With a single generator shared across tests, the values a test receives would depend on which tests ran before it. Combining the run seed with the test's id gives each test its own stable stream: it differs between tests, it stays the same when that test is run alone or in a different order, and it still changes between runs unless TEST_SEED is fixed.