Sub topic 6
Generating unique values with sequences
This chapter assumes you can write and run tests with pytest or a similar runner. It also assumes you know Python dataclasses and have read the earlier chapters on factory defaults and overrides. By the end you will know why fixed defaults break when a test creates several objects, how to generate unique values, and how to avoid the common mistakes with counters.
Why fixed defaults fail
A factory with a hard-coded default works until a test needs two objects. Here is a first attempt at a user factory:
from dataclasses import dataclass
@dataclass
class User:
id: int
email: str
role: str
active: bool
def make_user(**overrides):
defaults = {
"id": 1,
"email": "[email protected]",
"role": "member",
"active": True,
}
return User(**{**defaults, **overrides})
a = make_user()
b = make_user()
print(a.id == b.id, a.email == b.email)This prints True True. Both users have the same id and the same email. In memory that is harmless. It becomes a problem in three situations:
- The code under test stores users in a dictionary keyed by id. The second user silently replaces the first.
- The database has a unique constraint on
email. Inserting the second user raises an integrity error. - A test asserts that two objects are different. It passes or fails for the wrong reason because identifying fields collide.
The fix is to make identifying fields different on every call, without forcing the test author to invent values by hand.
The counter approach
A sequence is a source of values that never repeats within a run. In Python, itertools.count is the simplest one. Each call to next() returns the next integer.
from itertools import count
_user_ids = count(1)
print(next(_user_ids))
print(next(_user_ids))
print(next(_user_ids))This prints 1, 2 and 3. The counter lives at module level, so it keeps its state between calls. Now the factory can use it:
from dataclasses import dataclass
from itertools import count
@dataclass
class User:
id: int
email: str
role: str
active: bool
_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})
first = make_user()
second = make_user()
print(first.id, first.email)
print(second.id, second.email)The output is:
1 [email protected]
2 [email protected]The factory calls next() once per object and uses the single value n for every field that must be unique. Deriving both id and email from one number has two benefits. The fields stay consistent with each other, and a failure message that shows [email protected] points straight at the object with id 7.
Overrides still win
Sequences only supply defaults. A test that cares about a specific value passes it in, and the default is discarded:
alice = make_user(email="[email protected]")
print(alice.email)One detail matters here. The factory calls next(_user_ids) before it looks at the overrides, so the counter advances even when the caller overrides id and email. That is intentional. The sequence stays predictable: the third call to make_user always consumes the third number, whatever the earlier calls overrode. Skipped numbers are harmless, because uniqueness only requires that values never repeat.
There is one risk. If a test overrides id=2 and a later default also produces 2, the two collide. This is rare when tests override with obviously distinct values, such as id=9999. If your tests override ids often, keep hand-chosen ids in a range the counter never reaches.
Which fields need to be unique?
Not every field needs a sequence. Apply one where a collision would cause a real problem:
| Field kind | Example | Needs a sequence? |
|---|---|---|
| Primary key or id | `id` | Yes, if the database does not assign it |
| Unique natural key | `email`, `username`, `sku` | Yes |
| Display name | `name` | Usually no, unless shown in a list the test inspects |
| Status or role | `role="member"` | No, a constant default is clearer |
| Amount or count | `total_cents=1000` | No, a constant default keeps tests readable |
Constants are easier to read than generated values. Use a sequence only when uniqueness is required. A test that asserts order.total_cents == 1000 is simpler than one that must discover a generated total.
Sequences in more than one factory
Each kind of object gets its own counter. Sharing one counter across factories makes ids depend on the order in which unrelated objects were created, which makes failures harder to trace:
from dataclasses import dataclass
from itertools import count
@dataclass
class Order:
id: int
customer: User
total_cents: int
status: str
_order_ids = count(1)
def make_order(customer=None, **overrides):
if customer is None:
customer = make_user()
defaults = {
"id": next(_order_ids),
"customer": customer,
"total_cents": 1000,
"status": "pending",
}
return Order(**{**defaults, **overrides})
o1 = make_order()
o2 = make_order()
print(o1.id, o1.customer.id)
print(o2.id, o2.customer.id)With separate counters, order ids and user ids can both be 1 or 2 in the same test, and that is fine because they live in different tables. When make_order creates its own customer, the nested make_user() call draws from the user counter and the order draws from the order counter.
Unique values that are not numbers
Many unique fields are strings. Build them from the sequence number rather than from random text. Random text can collide, and it produces different values on every run.
_sku_numbers = count(1)
def next_sku():
return f"SKU-{next(_sku_numbers):05d}"
print(next_sku())
print(next_sku())This prints SKU-00001 and SKU-00002. The format specifier :05d pads the number with zeros to five digits. Padding keeps the values the same length, so sorted output matches creation order up to 99,999 objects.
Check each constraint that the real system enforces. Emails are often compared case-insensitively. If your factory produced [email protected] and [email protected], a case-insensitive unique index would treat them as duplicates. Keep generated values lowercase to stay clear of this.
Counters across tests
The counter is module-level state, so it is never reset between tests. The first test to run might see user 1 and a later test might see user 40. Two consequences follow.
First, tests must not assert on generated defaults. This test is fragile:
def test_first_user_has_id_one():
user = make_user()
assert user.id == 1 # breaks when any earlier test created a userIf the test depends on a value, it should set the value itself:
def test_user_keeps_given_id():
user = make_user(id=42)
assert user.id == 42Second, the counter's state depends on test order. If you run a single test alone, it sees different numbers than when it runs in the full suite. A test that passes in one case and fails in the other has usually relied on a generated value.
Resetting the counter before each test looks like a fix, but it usually adds risk. Tests that share a database could then collide with rows left by earlier tests. A counter that only moves forward is the safer default. Reset it only when you have a real need for stable numbers, such as comparing against stored snapshot files.
Parallel test runs
Tools such as pytest-xdist run tests in several worker processes. Each process imports your module separately and gets its own count(1). Two workers can therefore both produce [email protected]. This is harmless when each worker uses its own in-memory objects. It breaks when the workers share one database with a unique email constraint.
There are two common fixes:
- Give each worker its own database or schema, which is the cleaner option.
- Offset each counter by a worker-specific number, for example
count(worker_index * 1_000_000).
The second option is a workaround. Use it only when separate databases are not possible.
import os
from itertools import count
def worker_offset():
worker = os.environ.get("PYTEST_XDIST_WORKER", "gw0")
return int(worker.removeprefix("gw")) * 1_000_000
_user_ids = count(1 + worker_offset())pytest-xdist sets PYTEST_XDIST_WORKER to names like gw0 and gw1 in each worker process. Outside xdist the variable is absent, and the default gw0 gives an offset of zero.
Thread safety
next() on an itertools.count object is safe to call from multiple threads in CPython, so two threads will not receive the same number. That guarantee comes from the implementation. If you write your own counter as a class with a plain self.value += 1, two threads can read the same value before either writes it back. Prefer itertools.count. If you need a custom counter, protect the increment with a threading.Lock.
The same idea in factory_boy
The library factory_boy provides sequences as a built-in feature. factory.Sequence takes a function that receives the next number. LazyAttribute computes one field from others, so the email follows the id:
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 = True
print(UserFactory().email)
print(UserFactory().email)The counter belongs to the factory class, so you do not declare a module-level variable. By default factory_boy starts at 0, not 1. The library also provides reset_sequence() on a factory, which you can call when you do need to restart numbering. The hand-written version and the library version do the same job, and the library version removes the module-level counter.
Common mistakes
- Using a constant for a unique field.
email="[email protected]"in the defaults works until a test creates two users. - Calling
next()twice for one object. Ifidandemaileach callnext(),idis 3 while the email saysuser4. Call it once and reusen. - Random values for uniqueness.
random.randint(1, 1000)collides after roughly 40 objects, by the birthday effect. A counter never collides. - Asserting on generated values. Tests that expect
[email protected]break when run in a different order. - One shared counter for every factory. Ids then depend on unrelated object creation and are hard to read.
- Resetting counters between tests without need. Rows left in a shared database from earlier tests can then collide.
Summary
Constants collide as soon as a test creates two objects. A module-level itertools.count gives each object a fresh number, and the factory derives every unique field from that single number. Overrides still replace defaults. Keep one counter per object type, do not assert on generated values, and plan for parallel workers that share a database.
Exercise
A teammate writes this factory and reports that u.id is 5 while u.email is [email protected]. What is the bug, and how do you fix it?
def makeuser(**overrides):
defaults = {
"id": next(userids),
"email": f"user{next(user_ids)}@example.com",
}
return User({defaults, **overrides})
Show answer
The factory calls next(_user_ids) twice per object, so the two fields draw different numbers. Call it once, store the result in a variable such as n, and use n in both fields: n = next(_user_ids), then "id": n and "email": f"user{n}@example.com".
Exercise
Your test suite passes when run alone but fails when a single test is run by itself, with the message assert user.id == 3. What is the likely cause, and what should the test do instead?
Show answer
The test asserts on a generated default. The module-level counter reached 3 only because earlier tests created users first. Run alone, the counter starts at 1. The test should pass id=3 as an override, or assert on a value it set itself, so it does not depend on test order.
Exercise
Two pytest-xdist workers write users to one shared database that has a unique index on email. Intermittent integrity errors appear. Explain why, and give two fixes.
Show answer
Each worker process has its own counter starting at 1, so both generate [email protected] and the second insert violates the unique index. Fixes: give each worker its own database or schema, or offset each worker's counter by a worker-specific number such as worker_index * 1_000_000.