https://secure.travis-ci.org/FactoryBoy/factory_boy.svg?branch=master Latest Version Supported Python versions Wheel status License

factory_boy is a fixtures replacement based on thoughtbot’s factory_bot.



class FooTests(unittest.TestCase):

    def test_with_factory_boy(self):
        order = OrderFactory(
        # Run the tests here

    def test_without_factory_boy(self):
        address = Address(
            street="42 fubar street",
        customer = Customer(
        # etc.

factory_boy is designed to work well with various ORMs (Django, Mongo, SQLAlchemy), and can easily be extended for other libraries.

Its main features include:

  • Straightforward declarative syntax
  • Chaining factory calls while retaining the global context
  • Multiple factories per class support, including inheritance


PyPI: https://pypi.org/project/factory_boy/

$ pip install factory_boy

Source: https://github.com/FactoryBoy/factory_boy/

$ git clone git://github.com/FactoryBoy/factory_boy/
$ python setup.py install




Defining factories


import factory
from . import models

class UserFactory(factory.Factory):
    class Meta:
        model = models.User

    first_name = 'John'
    last_name = 'Doe'
    admin = False

# Another, different, factory for the same object
class AdminFactory(factory.Factory):
    class Meta:
        model = models.User

    first_name = 'Admin'
    last_name = 'User'
    admin = True

Using factories


# Returns a User instance that's not saved
user = UserFactory.build()

# Returns a saved User instance
user = UserFactory.create()

# Returns a stub object (just a bunch of attributes)
obj = UserFactory.stub()


# Same as UserFactory.create()
user = UserFactory()


# Build a User instance and override first_name
>>> user.first_name


>>> len(users)
>>> [user.first_name for user in users]

Realistic, random values

Demos look better with random yet realistic values; and those realistic values can also help discover bugs. For this, factory_boy relies on the excellent faker library:

class RandomUserFactory(factory.Factory):
    class Meta:
        model = models.User

    first_name = factory.Faker('first_name')
    last_name = factory.Faker('last_name')
>>> UserFactory()
<User: Lucy Murray>

Reproducible random values

The use of fully randomized data in tests is quickly a problem for reproducing broken builds. To that purpose, factory_boy provides helpers to handle the random seeds it uses, located in the factory.random module:

import factory.random

def setup_test_environment():
    # Other setup here

Lazy Attributes


These “lazy” attributes can be added as follows:

class UserFactory(factory.Factory):
    class Meta:
        model = models.User

    first_name = 'Joe'
    last_name = 'Blow'
    date_joined = factory.LazyFunction(datetime.now)
>>> UserFactory().email


LazyAttribute calls the function with the object being constructed as an argument, when LazyFunction does not send any argument.



class UserFactory(factory.Factory):
    class Meta:
        model = models.User


>>> UserFactory().email
>>> UserFactory().email



class PostFactory(factory.Factory):
    class Meta:
        model = models.Post

    author = factory.SubFactory(UserFactory)

The associated object’s strategy will be used:

# Builds and saves a User and a Post
>>> post = PostFactory()
>>> post.author.id is None  # post.author has been saved

>>> post = PostFactory.build()
>>> post.id is None
>>> post.author.id is None

ORM Support


  • Django, with factory.django.DjangoModelFactory
  • Mogo, with factory.mogo.MogoFactory
  • MongoEngine, with factory.mongoengine.MongoEngineFactory
  • SQLAlchemy, with factory.alchemy.SQLAlchemyModelFactory

Debugging factory_boy



with factory.debug():
    obj = TestModel2Factory()

import logging
logger = logging.getLogger('factory')

This will yield messages similar to those (artificial indentation):

BaseFactory: Preparing tests.test_using.TestModel2Factory(extra={})
      LazyStub: Computing values for tests.test_using.TestModelFactory(one=4)
      LazyStub: Computed values, got tests.test_using.TestModelFactory(one=4)
    BaseFactory: Generating tests.test_using.TestModelFactory(one=4)


factory_boy is distributed under the MIT License.

Issues should be opened through GitHub Issues; whenever possible, a pull request should be included. Questions and suggestions are welcome on the mailing-list.


$ make test

In order to test coverage, please use:

$ make coverage

To test with a specific framework version, you may use a tox target:

# list all tox environments
$ tox --listenvs

# run tests inside a specific environment
$ tox -e py36-django20-alchemy13-mongoengine017

Valid options are:

  • DJANGO for Django
  • MONGOENGINE for mongoengine
  • ALCHEMY for SQLAlchemy

To avoid running mongoengine tests (e.g no mongo server installed), run:

$ make SKIP_MONGOENGINE=1 test

Contents, indices and tables