Sub topic 13
Anti-patterns to avoid
This chapter assumes you have read the earlier chapters. You should be comfortable with factory functions that return valid defaults, keyword overrides, sequences, relationships, traits, and the difference between building and persisting. The examples use Python and dataclasses. The ideas apply to any language.
Factories fail slowly. A factory with a few small flaws still works on day one. After a year, the suite is slow, some tests fail at random, and nobody dares change a default. Each section below covers one flaw: what it looks like, why it hurts, and the fix.
Tests that depend on hidden defaults
A factory exists so a test can state only the values it cares about. The most common anti-pattern breaks that rule from the other side. The test asserts on a value it never set.
from dataclasses import dataclass
from itertools import count
@dataclass
class Order:
id: int
total_cents: int
status: str
_order_ids = count(1)
def make_order(**overrides):
defaults = {"id": next(_order_ids), "total_cents": 1000, "status": "pending"}
return Order(**{**defaults, **overrides})
def apply_discount(order, percent):
return order.total_cents * (100 - percent) // 100
def test_discount_hidden_default():
order = make_order()
assert apply_discount(order, 10) == 900The test passes, but the reader cannot see why the answer is 900. The 1000 lives in another file. If someone changes the default total to 2500, this test fails even though apply_discount is correct.
Set the input in the test, so the arithmetic is visible:
def test_discount_visible_input():
order = make_order(total_cents=2000)
assert apply_discount(order, 10) == 1800The rule: if a test asserts on a field, or its outcome depends on a field, the test sets that field. Defaults only supply values the test does not care about.
Defaults that are valid but surprising
Defaults should be boring. A default role of "admin", a default status of "shipped", or a default total_cents of 0 makes every test start from a special case. Tests that need an ordinary object must override the special values, and a test that forgets to override them passes for the wrong reason.
Choose the most common, least special state. A new user is an active member. A new order is pending with a positive total. Express special states as traits such as make_admin or make_cancelled_order.
Defaults must also pass the same validation as production data. If the real system rejects an email without an @, the factory must not produce one. A factory that bypasses validation hides bugs, because tests run against objects that can never exist in production.
Shared mutable defaults
This bug is easy to write in Python and hard to spot. A mutable default created once at module level is shared by every object the factory returns.
from dataclasses import dataclass
@dataclass
class Post:
title: str
tags: list
DEFAULT_TAGS = []
def make_post_shared(**overrides):
defaults = {"title": "Hello", "tags": DEFAULT_TAGS}
return Post(**{**defaults, **overrides})
first = make_post_shared()
first.tags.append("draft")
second = make_post_shared()
print(second.tags)This prints ['draft']. The second post received a tag nobody gave it, because both posts hold the same list. A test that mutates its object corrupts later tests, and the failure depends on test order.
Build the mutable value inside the function so each call gets a fresh one:
def make_post(**overrides):
defaults = {"title": "Hello", "tags": []}
return Post(**{**defaults, **overrides})Be careful in the other direction as well. If a caller passes one list into two posts through an override, those two posts share it. That is the caller's choice and visible in the test, so it is acceptable.
Collisions and order-dependent ids
Two related mistakes involve unique values.
The first is a hardcoded unique field. A factory with email = "[email protected]" works until a test creates two users and hits a uniqueness check, or a database constraint. Use a sequence, as in earlier chapters.
The second is asserting on a sequence value. A counter increases across the whole test run, so the first user in one test might get id 1 and in another test get id 47. This test is fragile:
def test_user_id_fragile():
user = make_user()
assert user.id == 1It passes when run alone and fails in the full suite. Do not assert on generated ids or generated emails. Compare against the object itself, as in assert result.user_id == user.id, or pass the value explicitly with make_user(id=7).
Resetting the counter before every test appears to fix this, but it adds global state that every test must remember to reset. It also reintroduces collisions if any persisted data survives between tests. Avoiding assertions on generated values is simpler and safer.
Unseeded randomness
Random data finds edge cases, but only if you can reproduce the failure. This factory cannot be reproduced.
import random
def make_order_flaky(**overrides):
defaults = {
"id": next(_order_ids),
"total_cents": random.randint(0, 50_000),
"status": "pending",
}
return Order(**{**defaults, **overrides})It has two problems. The range includes 0, which may be an invalid total, so roughly one run in 50,000 fails with no explanation. Also, nothing records which value caused the failure.
Keep randomness out of defaults. Use fixed, valid values. When you want random data, pass a seeded generator explicitly and print the seed:
import random
def random_total(rng):
return rng.randint(100, 50_000)
seed = 12345
rng = random.Random(seed)
order = make_order(total_cents=random_total(rng))
print(f"seed={seed} total={order.total_cents}")The lower bound is now a valid total, and a failing run can be repeated with the same seed.
Eager object graphs
A factory that builds everything a model could ever need is slow and obscures what the test is about. Suppose make_order also creates a customer, an address, a payment method, three line items, and a warehouse. Every order test pays for all of them, and a failure in warehouse creation breaks tests that never touch warehouses.
Create the related objects the model requires, and no more. Optional relationships default to empty. A test that needs line items passes them in or uses a trait.
This matters most when objects are persisted. Each object is a database write, and a deep chain multiplies them. Prefer building in memory by default, and persist only when the test reads through the database. The test then pays for the objects it uses. The earlier chapter on building versus persisting covers the mechanics.
Factories that copy production logic
Consider an order factory that computes total_cents by summing line items with the same tax and discount rules the production code uses. If production has a bug in that formula, the factory has the same bug, and every test agrees with the wrong answer.
A factory should store data. It should not compute results. Derived fields are acceptable when they are trivial and the invariant is simple, such as an email built from an id. If the derivation is business logic, set the expected values by hand in the test, so the test checks the code against an independent source.
Trait and factory sprawl
Traits are cheap, so they multiply. Soon the test code has make_admin, make_inactive_admin, make_admin_with_expired_plan, and make_admin_with_expired_plan_and_two_orders. Each name hides a bundle of fields, and readers must open the factory to learn what they mean.
Use these guidelines to keep traits useful:
- A trait names one domain concept, such as
adminorcancelled. - Combine concepts by composing overrides at the call site, for example
make_admin(active=False). - If a bundle appears in only one test, write it inline in that test.
- If a name needs "and" in it, split it.
Silent typos in overrides
A dataclass rejects unknown keywords, so make_user(actve=False) raises TypeError. That is the behavior you want. Factories built on plain dictionaries can swallow the typo, and the test then runs against the default active=True. Such a test can pass while checking nothing. Make sure the factory raises on unknown field names, either by building through the real constructor or by checking the keys.
Summary table
| Anti-pattern | Symptom | Fix |
|---|---|---|
| Hidden default dependence | Test breaks when a default changes | Set the asserted field in the test |
| Surprising defaults | Every test overrides the same fields | Use the most ordinary state, add traits for special states |
| Shared mutable defaults | Objects affect each other, order-dependent failures | Create lists and dicts inside the function |
| Hardcoded unique values | Uniqueness errors with two objects | Use a sequence |
| Asserting on generated ids | Passes alone, fails in the suite | Compare to the object, or set the id explicitly |
| Unseeded randomness | Rare failures that cannot be reproduced | Fixed defaults, seeded generator, print the seed |
| Eager object graphs | Slow tests, unrelated failures | Create only required relationships |
| Production logic in the factory | Bugs hidden in both places | Write expected values by hand |
| Trait sprawl | Long names, unclear contents | One concept per trait, compose at the call site |
| Silent typos | Test passes without testing | Reject unknown field names |
Diagnosing a bad factory
When a test fails and you suspect the data, work through these questions in order.
Keeping factories healthy
A few habits prevent most of the problems above.
- Treat factory changes like production changes. A changed default can alter hundreds of tests, so run the full suite before merging.
- Add a small test for each factory that checks
make_x()returns a valid object, using the same validation as production. - Delete traits and factories that no test uses.
- When you must change a default, look at which tests break. Each failure is a test that depended on a hidden default, and you can fix it by making that dependence explicit.
Exercise
A teammate's test reads user = make_user() followed by assert report.total_users == 3, after calling make_user() three times. It passes alone and fails in the full suite. What anti-pattern is most likely, and how would you fix it?
Show answer
The test likely depends on state outside its own setup. Candidates are persisted users left over from other tests, or a counter value used as a count. Check whether the users are persisted and not cleaned up between tests, and whether the report queries a shared table. The fix is to isolate the data, for example with a per-test transaction or a clean database, and to assert on the objects the test created. Do not rely on global counters or on the number of rows in a shared store.
Exercise
This factory has a bug. Find it and rewrite it. def makecart(**overrides): defaults = {"owner": "sam", "items": SHAREDITEMS} return Cart({defaults, **overrides})
Show answer
SHARED_ITEMS is a single module-level list, so every cart built with the default shares it. One test that appends to cart.items changes the next test's cart. Create the list inside the function: defaults = {"owner": "sam", "items": []}. Each call then returns a cart with its own empty list.
Exercise
A test asserts order.total_cents == 1000 after calling make_order() with no arguments. Why is this fragile, and what is the smallest change that makes the intent clear?
Show answer
The value 1000 comes from the factory's default, so changing the default breaks the test and a reader cannot see where 1000 comes from. Pass the value in the test: order = make_order(total_cents=1000), and then assert on it. The test now states its own input.