Deterministic Fixtures With Factory Boy
Generate deterministic test fixtures with factory_boy for reproducible test data.
Code
import factory
from datetime import datetime
class UserFactory(factory.Factory):
class Meta:
model = dict
id = factory.Sequence(lambda n: n + 1)
email = factory.Sequence(lambda n: f'user{n}@example.com')
name = factory.Faker('name')
created_at = factory.LazyFunction(datetime.utcnow)
def make_users(count=10):
return [UserFactory() for _ in range(count)]
def make_user(**overrides):
return UserFactory(**overrides)How the snippet works
Count the classes UserFactory and Meta and the functions make_users and make_user as the entire surface area of Deterministic Fixtures With Factory Boy.
The snippet’s external surface is datetime, all of it via factory.
The return value is newly constructed — inputs are never handed back.
What to watch for
- Plan for an install step:
factoryis a real dependency, resolved by the package manager.
Applying it
The main signature reads def make_users(count=10)
make_users is what another module would consume; nothing else here is load-bearing for callers.
Statements that matter
def make_user(**overrides):
return UserFactory(**overrides)
def make_users(count=10):
return [UserFactory() for _ in range(count)]
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does `make_users` modify its input?
- No mutation happens — the function reads its input and returns a new value.
- Do I need to install anything before running this?
- Yes: `factory` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.