Deterministic Fixtures With Factory Boy

Generate deterministic test fixtures with factory_boy for reproducible test data.

PythonData Integrity

Code

pythonsnippet
16 lines
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: factory is 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

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.