A test fixtures replacement for Python
Alternatives To Factory_boy
Project NameStarsDownloadsRepos Using ThisPackages Using ThisMost Recent CommitTotal ReleasesLatest ReleaseOpen IssuesLicenseLanguage
Factory_bot7,84577,8871,26512 days ago71October 24, 201751mitRuby
A library for setting up Ruby objects as test data.
Axe Core5,4112,3958783 days ago1,260November 28, 2023275mpl-2.0JavaScript
Accessibility engine for automated Web UI testing
Mimesis4,11742322 days ago49August 19, 202311mitPython
Mimesis is a powerful Python library that empowers developers to generate massive amounts of synthetic data efficiently.
Factory_boy3,2405063315 days ago43July 19, 2023194mitPython
A test fixtures replacement for Python
Pytest Asyncio1,2391,5976 hours ago43December 03, 202336apache-2.0Python
Asyncio support for pytest
Ward1,14177 days ago93January 26, 202345mitPython
Ward is a modern test framework for Python with a focus on productivity and readability.
Testfixtures975483 months ago52May 01, 202317mitGo
Ruby on Rails like test fixtures for Go. Write tests against a real database
8 days ago54mitTypeScript
Data modeling and relation library for testing JavaScript applications.
Foundry53115 days ago59October 13, 202351mitPHP
A model factory library for creating expressive, auto-completable, on-demand dev/test fixtures with Symfony and Doctrine.
10 months ago2July 24, 20206mitGo
IntegreSQL manages isolated PostgreSQL databases for your integration tests.
Alternatives To Factory_boy
Select To Compare

Alternative Project Comparisons


Latest Version Supported Python versions Wheel status License

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

As a fixtures replacement tool, it aims to replace static, hard to maintain fixtures with easy-to-use factories for complex objects.

Instead of building an exhaustive test setup with every possible combination of corner cases, factory_boy allows you to use objects customized for the current test, while only declaring the test-specific fields:

class FooTests(unittest.TestCase):

    def test_with_factory_boy(self):
        # We need a 200, paid order, shipping to australia, for a VIP customer
        order = OrderFactory(
        # Run the tests here

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

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

Its main features include:

  • Straightforward declarative syntax
  • Chaining factory calls while retaining the global context
  • Support for multiple build strategies (saved/unsaved instances, stubbed objects)
  • 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



This section provides a quick summary of factory_boy features. A more detailed listing is available in the full documentation.

Defining factories

Factories declare a set of attributes used to instantiate a Python object. The class of the object must be defined in the model field of a class Meta: attribute:

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

ORM integration

factory_boy integration with Object Relational Mapping (ORM) tools is provided through specific factory.Factory subclasses:

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

More details can be found in the ORM section.

Using factories

factory_boy supports several different instantiation strategies: build, create, and stub:

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

# Returns a saved User instance.
# UserFactory must subclass an ORM base class, such as DjangoModelFactory.
user = UserFactory.create()

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

You can use the Factory class as a shortcut for the default instantiation strategy:

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

No matter which strategy is used, it's possible to override the defined attributes by passing keyword arguments:

# Build a User instance and override first_name
>>> user = UserFactory.build(first_name='Joe')
>>> user.first_name

It is also possible to create a bunch of objects in a single call:

>>> users = UserFactory.build_batch(10, first_name="Joe")
>>> len(users)
>>> [user.first_name for user in users]
["Joe", "Joe", "Joe", "Joe", "Joe", "Joe", "Joe", "Joe", "Joe", "Joe"]

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')
>>> RandomUserFactory()
<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

Most factory attributes can be added using static values that are evaluated when the factory is defined, but some attributes (such as fields whose value is computed from other elements) will need values assigned each time an instance is generated.

These "lazy" attributes can be added as follows:

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

    first_name = 'Joe'
    last_name = 'Blow'
    email = factory.LazyAttribute(lambda a: '{}.{}@example.com'.format(a.first_name, a.last_name).lower())
    date_joined = factory.LazyFunction(datetime.now)
>>> UserFactory().email
"[email protected]"


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


Unique values in a specific format (for example, e-mail addresses) can be generated using sequences. Sequences are defined by using Sequence or the decorator sequence:

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

    email = factory.Sequence(lambda n: 'person{}@example.com'.format(n))

>>> UserFactory().email
'[email protected]'
>>> UserFactory().email
'[email protected]'


Some objects have a complex field, that should itself be defined from a dedicated factories. This is handled by the SubFactory helper:

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.id is None  # Post has been 'saved'
>>> post.author.id is None  # post.author has been saved

# Builds but does not save a User, and then builds but does not save a Post
>>> post = PostFactory.build()
>>> post.id is None
>>> post.author.id is None

Support Policy

factory_boy supports active Python versions as well as PyPy3.

Debugging factory_boy

Debugging factory_boy can be rather complex due to the long chains of calls. Detailed logging is available through the factory logger.

A helper, factory.debug(), is available to ease debugging:

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.TestModel2Factory(two=<OrderedDeclarationWrapper for <factory.declarations.SubFactory object at 0x1e15610>>)
    SubFactory: Instantiating tests.test_using.TestModelFactory(__containers=(<LazyStub for tests.test_using.TestModel2Factory>,), one=4), create=True
    BaseFactory: Preparing tests.test_using.TestModelFactory(extra={'__containers': (<LazyStub for tests.test_using.TestModel2Factory>,), 'one': 4})
      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)
  LazyStub: Computed values, got tests.test_using.TestModel2Factory(two=<tests.test_using.TestModel object at 0x1e15410>)
BaseFactory: Generating tests.test_using.TestModel2Factory(two=<tests.test_using.TestModel object at 0x1e15410>)


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.

Development dependencies can be installed in a virtualenv with:

$ pip install --editable '.[dev]'

All pull requests should pass the test suite, which can be launched simply with:

$ make testall

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 (django/mongoengine/SQLAlchemy are not installed)
$ tox -e py310

# run tests inside a specific environment (django)
$ tox -e py310-djangomain
$ tox -e py310-djangomain-postgres

# run tests inside a specific environment (alchemy)
$ tox -e py310-alchemy
$ tox -e py310-alchemy-postgres

# run tests inside a specific environment (mongoengine)
$ tox -e py310-mongo


For users interesting in packaging FactoryBoy into downstream distribution channels (e.g. .deb, .rpm, .ebuild), the following tips might be helpful:


The package's run-time dependencies are listed in setup.cfg. The dependencies useful for building and testing the library are covered by the dev and doc extras.

Moreover, all development / testing tasks are driven through make(1).


In order to run the build steps (currently only for docs), run:

python setup.py egg_info
make doc


When testing for the active Python environment, run the following:

make test


You must make sure that the factory module is importable, as it is imported from the testing code.

Popular Fixtures Projects
Popular Testing Projects
Popular Software Quality Categories
Related Searches

Get A Weekly Email With Trending Projects For These Categories
No Spam. Unsubscribe easily at any time.