Sub topic 6
Generating unique values with sequences
This chapter assumes you can write Python dataclasses and tests with a runner such as pytest. It also assumes you have a factory function with defaults and keyword overrides, like make_user.
Why fixed defaults break
A factory with a fixed default works until a test creates two objects. Suppose every user gets the email [email protected]. Most real systems require emails to be unique, so the second object fails or silently overwrites the first.
from dataclasses import dataclass
@dataclass
class User:
id: int
email: str
role: str
active: bool
def make_user_fixed(**overrides):
defaults = {"id": 1, "email": "[email protected]", "role": "member", "active": True}
return User(**{**defaults, **overrides})
class UserStore:
def __init__(self):
self.by_email = {}
def add(self, user):
if user.email in self.by_email:
raise ValueError(f"duplicate email: {user.email}")
self.by_email[user.email] = user
store = UserStore()
store.add(make_user_fixed())
store.add(make_user_fixed()) # raises ValueErrorThe test author would have to override email on every second call. That is the repeated setup noise factories are meant to remove.
A counter as a sequence
A sequence is a value that changes on every call. The simplest version is a counter that the factory advances each time it builds an object. Python's itertools.count does this.
from itertools import count
_user_ids = count(1)
def make_user(**overrides):
n = next(_user_ids)
defaults = {
"id": n,
"email": f"user{n}@example.com",
"role": "member",
"active": True,
}
return User(**{**defaults, **overrides})
a = make_user()
b = make_user()
print(a.id, a.email) # 1 [email protected]
print(b.id, b.email) # 2 [email protected]The factory calls next once and derives every unique field from that single number. Using one n keeps related fields consistent: user 7 has the email [email protected].
Overrides still win
The counter runs on every call, even when the caller overrides the field. That is intended. The id sequence stays predictable, and an explicit value always takes priority.
alice = make_user(email="[email protected]")
print(alice.email) # [email protected]
print(make_user().email) # [email protected], because the counter still advancedNotice the gap: alice consumed n = 1, so the next default user is number 2.
Common errors
- Resetting the counter between tests. If you recreate
count(1)for each test, ids repeat across objects that live in shared state, such as a database that persists between tests. A module-level counter that is never reset is safer. Tests should not depend on a specific number. - Asserting on generated values. A test that expects
[email protected]breaks when another test runs first. If a test cares about a value, override it and assert on that value. - Uniqueness from time or randomness alone.
datetime.now()can produce equal values on fast machines, and random values can collide. A counter cannot collide within a process. - Sharing a counter across processes. If tests run in parallel worker processes against one database, each process starts its own counter at 1. Add a per-worker prefix, for example
f"user{worker}-{n}@example.com", or use a database-generated id.
Sequences in a factory library
Libraries package the same idea. In factory_boy, factory.Sequence supplies the counter, and LazyAttribute derives a field from other fields.
import factory
class UserFactory(factory.Factory):
class Meta:
model = User
id = factory.Sequence(lambda n: n)
email = factory.LazyAttribute(lambda obj: f"user{obj.id}@example.com")
role = "member"
active = TrueThis matches the hand-written version. The library also resets or shares counters per factory class, so each factory has its own numbering.
Exercise
Your tests pass alone but fail when the whole suite runs, with "duplicate email: [email protected]" errors from the database. The factory uses a fixed email default. What is the smallest change that fixes it without editing any test, and why?
Show answer
Change the factory so the email default is built from a counter, for example f"user{n}@example.com" with n = next(_user_ids). Each call then produces a different email, so objects that remain in the database from earlier tests no longer collide. The tests need no edits because they either override the email explicitly or never cared about its value.