Skip to content
This repository

A test fixtures replacement for Python

This branch is 0 commits ahead and 0 commits behind master

Fix 'gif' image tests.

The latest pillow has changed the default gif palette, so we'll use a normalized RGB palette instead.
latest commit 42d3d4b8c5
Raphaël Barrois authored April 20, 2014
Octocat-spinner-32 docs Typo January 26, 2014
Octocat-spinner-32 factory Merge branch 'maint/2.3.x' January 22, 2014
Octocat-spinner-32 tests Fix 'gif' image tests. April 20, 2014
Octocat-spinner-32 .gitignore Fix setup.py post-setuptools/distribute merge. August 14, 2013
Octocat-spinner-32 .pylintrc Pylint. April 03, 2013
Octocat-spinner-32 .travis.yml Typo in .travis.yml December 25, 2013
Octocat-spinner-32 ChangeLog Add ChangeLog. August 17, 2012
Octocat-spinner-32 LICENSE Happy New Year! January 02, 2013
Octocat-spinner-32 MANIFEST.in Rename README. November 15, 2013
Octocat-spinner-32 Makefile Add factory.django.FileField (See #52) June 15, 2013
Octocat-spinner-32 README.rst Rename README. November 15, 2013
Octocat-spinner-32 dev_requirements.txt Update requirements January 21, 2014
Octocat-spinner-32 setup.py Packaging: Use codecs.open (Closes #114, #118). December 25, 2013
Octocat-spinner-32 tox.ini Document need for mock/unittest. March 11, 2013
README.rst

factory_boy

https://secure.travis-ci.org/rbarrois/factory_boy.png?branch=master

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)

Links

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

Download

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

$ pip install factory_boy

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

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

Usage

Note

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 = UserFactory.build()

# 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 = UserFactory.build(first_name='Joe')
>>> user.first_name
"Joe"

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}@example.com'.format(a.first_name, a.last_name).lower())
>>> UserFactory().email
"joe.blow@example.com"

Sequences

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}@example.com'.format(n))

>>> UserFactory().email
'person0@example.com'
>>> UserFactory().email
'person1@example.com'

Associations

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

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

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, :meth:`factory.debug()`, is available to ease debugging:

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


import logging
logger = logging.getLogger('factory')
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.DEBUG)

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 :class:`~factory.Factory` subclasses:

Contributing

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 setup.py test

Note

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 setup.py test; coverage report

Contents, indices and tables

Something went wrong with that request. Please try again.