Skip to main content

A versatile test fixtures replacement based on thoughtbot's factory_bot for Ruby.

Project description

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.

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

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(
            amount=200,
            status='PAID',
            customer__is_vip=True,
            address__country='AU',
        )
        # Run the tests here

    def test_without_factory_boy(self):
        address = Address(
            street="42 fubar street",
            zipcode="42Z42",
            city="Sydney",
            country="AU",
        )
        customer = Customer(
            first_name="John",
            last_name="Doe",
            phone="+1234",
            email="john.doe@example.org",
            active=True,
            is_vip=True,
            address=address,
        )
        # 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

  • Support for multiple build strategies (saved/unsaved instances, stubbed objects)

  • Multiple factories per class support, including inheritance

Download

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

Usage

Defining factories

Factories declare a set of attributes used to instantiate an 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

Using factories

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

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

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"

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

>>> users = UserFactory.build_batch(10, first_name="Joe")
>>> len(users)
10
>>> [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')
>>> UserFactory()
<User: Lucy Murray>

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: '{0}.{1}@example.com'.format(a.first_name, a.last_name).lower())
    date_joined = factory.LazyFunction(datetime.now)
>>> 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):
    class Meta:
        model = 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):
    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'
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

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

  • MongoEngine, with factory.mongoengine.MongoEngineFactory

  • SQLAlchemy, with factory.alchemy.SQLAlchemyModelFactory

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

Contributing

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.

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

$ make test

In order to test coverage, please use:

$ make coverage

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

$ tox --listenvs
py27-django111-alchemy12-mongoengine015
py27-django20-alchemy12-mongoengine015
# ...
pypy3-django20-alchemy12-mongoengine015
examples
lint

$ tox -e py36-django20-alchemy12-mongoengine015

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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

factory_boy-2.11.1.tar.gz (43.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

factory_boy-2.11.1-py2.py3-none-any.whl (36.8 kB view details)

Uploaded Python 2Python 3

File details

Details for the file factory_boy-2.11.1.tar.gz.

File metadata

  • Download URL: factory_boy-2.11.1.tar.gz
  • Upload date:
  • Size: 43.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for factory_boy-2.11.1.tar.gz
Algorithm Hash digest
SHA256 6f25cc4761ac109efd503f096e2ad99421b1159f01a29dbb917359dcd68e08ca
MD5 34f7141c95dddac5e1384935a75e9d82
BLAKE2b-256 d5b4649fc4bfd0daf308b5cd10bfa51c50bfa4c4c79e091ed301aca69ef6780e

See more details on using hashes here.

File details

Details for the file factory_boy-2.11.1-py2.py3-none-any.whl.

File metadata

File hashes

Hashes for factory_boy-2.11.1-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 d552cb872b310ae78bd7429bf318e42e1e903b1a109e899a523293dfa762ea4f
MD5 20113693a55178f6ef1a901b38b3d559
BLAKE2b-256 196cb2ac85b3f0b48ac968af3741c4f020bf272ab9dabbd1643e9c719441099a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page