Sub topic 13
Anti-patterns to avoid
This chapter assumes you can write a factory function with defaults and overrides, and that you know sequences, traits, and the difference between building and persisting. Here you will learn the mistakes that make a factory-based suite slow, confusing, or flaky, and how to fix each one.
Tests that rely on hidden defaults
A factory default is a convenience, not a contract. If a test depends on a default value without saying so, a later edit to the factory breaks it with no visible link.
def test_new_user_is_member():
user = make_user()
assert user.role == "member" # relies on the factory defaultIf someone changes the default role to "trial", this test fails and the cause is not in the test. State the value the test depends on:
def test_member_cannot_delete_posts():
user = make_user(role="member")
assert can_delete_posts(user) is FalseNow the setup shows the input that matters.
Shared mutable defaults
A default object created once and reused is shared by every caller. Mutating it in one test changes the data in the next.
from dataclasses import dataclass
@dataclass
class Cart:
id: int
items: list
_DEFAULT_ITEMS = []
def make_cart_shared(**overrides):
defaults = {"id": 1, "items": _DEFAULT_ITEMS}
return Cart(**{**defaults, **overrides})
def make_cart(**overrides):
defaults = {"id": 1, "items": []}
return Cart(**{**defaults, **overrides})
first = make_cart_shared()
first.items.append("book")
print(make_cart_shared().items) # ['book'], leaked from the first cart
print(make_cart().items) # [], fresh list on every callCreate lists, dicts, and nested objects inside the function body so that every call gets its own copy.
Persisting by default
A factory that writes to the database on every call makes every test slow, even tests that only need an object in memory. It also hides the cost: a test that calls make_order() may silently insert a user, an order, and several related rows.
Make building the default. Add a separate function or an explicit option for persisting, and use it only in tests that exercise queries or constraints.
Factories that grow their own logic
A factory should assemble data, not compute it. Warning signs include:
- Branches on many flags, such as
if premium and not trial. - Calculations that duplicate production code, such as a tax total computed inside the factory.
- A dozen traits that are rarely combined and never reused.
If the factory copies production logic, the test can pass while both are wrong. Pass the expected value in explicitly, for example make_order(total_cents=1100), and keep traits for variants that several tests share.
Deep relationship chains
If make_order() also builds a user, an address, a payment method, and a warehouse, then every test pays for objects it never looks at. Build only the relationships the object needs to be valid. Let tests pass in the others when they care.
Unseeded randomness and hardcoded uniqueness
Random values with no recorded seed give you failures you cannot reproduce. Hardcoded ids and emails cause collisions as soon as two objects exist in the same test. Use a sequence for unique fields, and a seeded generator for random ones, and print the seed.
Match the symptom to the fix
A quick review checklist
| Question | Healthy answer |
|---|---|
| Does each test state the values it asserts on? | Yes, passed as overrides |
| Does each call create fresh lists and dicts? | Yes |
| Does the factory touch the database? | Only when asked |
| Does the factory compute business results? | No |
| Can a failing run be replayed? | Yes, the seed is printed |
Exercise
A test calls make_cart() and appends an item to cart.items. A later test calls make_cart() and finds the item already there. The factory contains defaults = {"id": 1, "items": DEFAULT_ITEMS} with DEFAULT_ITEMS = [] at module level. What is the cause, and how do you fix it?
Show answer
Every call reuses the same list object, so a mutation in one test leaks into the next. Create the list inside the function, as in defaults = {"id": 1, "items": []}, so each call gets a new list.