Coder Social home page Coder Social logo

factory_boy's Introduction



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

Its features include:

  • Straightforward syntax
  • Support for multiple build strategies (saved/unsaved instances, attribute dicts, stubbed objects)
  • Powerful helpers for common cases (sequences, sub-factories, reverse dependencies, circular factories, ...)
  • Multiple factories per class support, including inheritance
  • Support for various ORMs (currently Django, Mogo, SQLAlchemy)

factory_boy supports Python 2.6, 2.7, 3.2 and 3.3, as well as PyPy; it requires only the standard Python library.



$ pip install factory_boy


$ git clone git://
$ python 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 an object. The class of the object must be defined in the FACTORY_FOR attribute:

import factory
from . import models

class UserFactory(factory.Factory):
    FACTORY_FOR = models.User

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

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

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

Using factories

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

# Returns a User instance that's not saved
user =

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

# Returns a dict of attributes that can be used to build a User instance
attributes = UserFactory.attributes()

You can use the Factory class as a shortcut for the default build 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 ='Joe')
>>> user.first_name

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):
    FACTORY_FOR = models.User
    first_name = 'Joe'
    last_name = 'Blow'
    email = factory.LazyAttribute(lambda a: '{0}.{1}'.format(a.first_name, a.last_name).lower())
>>> UserFactory().email
"[email protected]"


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):
    FACTORY_FOR = models.User
    email = factory.Sequence(lambda n: 'person{0}'.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):
    FACTORY_FOR = models.Post
    author = factory.SubFactory(UserFactory)

The associated object's strategy will be used:

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

# Builds but does not save a User, and then builds but does not save a Post
>>> post =
>>> is None
>>> is None

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:

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>)

ORM Support

factory_boy has specific support for a few ORMs, through specific ~factory.Factory subclasses:

  • Django, with ~factory.django.DjangoModelFactory
  • Mogo, with ~factory.mogo.MogoFactory
  • SQLAlchemy, with ~factory.alchemy.SQLAlchemyModelFactory


factory_boy is distributed under the MIT License.

Issues should be opened through GitHub Issues; whenever possible, a pull request should be included.

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

$ python test


Running test requires the unittest2 (standard in Python 2.7+) and mock libraries.

In order to test coverage, please use:

$ pip install coverage
$ coverage erase; coverage run --branch test; coverage report

Contents, indices and tables

introduction reference orms recipes fuzzy examples internals changelog ideas

  • genindex
  • modindex
  • search

factory_boy's People


azaghal avatar carljm avatar dnerdy avatar ediskandarov avatar eyvoro avatar ghickman avatar gotgenes avatar kmike avatar michaeljoseph avatar msabramo avatar nkryptic avatar obiwanus avatar rbarrois avatar saulshanabrook avatar tyarran avatar


 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.