diff options
Diffstat (limited to 'README')
-rw-r--r-- | README | 250 |
1 files changed, 118 insertions, 132 deletions
@@ -4,43 +4,62 @@ factory_boy .. image:: https://secure.travis-ci.org/rbarrois/factory_boy.png?branch=master :target: http://travis-ci.org/rbarrois/factory_boy/ -factory_boy is a fixtures replacement based on thoughtbot's `factory_girl <http://github.com/thoughtbot/factory_girl>`_ . Like factory_girl it has a straightforward definition syntax, support for multiple build strategies (saved instances, unsaved instances, attribute dicts, and stubbed objects), and support for multiple factories for the same class, including factory inheritance. Django support is included, and support for other ORMs can be easily added. +factory_boy is a fixtures replacement based on thoughtbot's `factory_girl <http://github.com/thoughtbot/factory_girl>`_. -The official repository is at http://github.com/rbarrois/factory_boy; the documentation at http://readthedocs.org/docs/factoryboy/. +Its features include: -Credits -------- +- 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) -This README parallels the factory_girl README as much as possible; text and examples are reproduced for comparison purposes. Ruby users of factory_girl should feel right at home with factory_boy in Python. -factory_boy was originally written by Mark Sandstrom, and improved by Raphaƫl Barrois. +Links +----- + +* Documentation: http://factoryboy.readthedocs.org/ +* Official repository: https://github.com/rbarrois/factory_boy +* Package: https://pypi.python.org/pypi/factory_boy/ + +factory_boy supports Python 2.6, 2.7, 3.2 and 3.3, as well as PyPy; it requires only the standard Python library. -Thank you Joe Ferris and thoughtbot for creating factory_girl. Download -------- -Github: http://github.com/rbarrois/factory_boy/ +PyPI: https://pypi.python.org/pypi/factory_boy/ + +.. code-block:: sh + + $ pip install factory_boy + +Source: https://github.com/rbarrois/factory_boy/ -PyPI:: +.. code-block:: sh - pip install factory_boy + $ git clone git://github.com/rbarrois/factory_boy/ + $ python setup.py install -Source:: - # Download the source and run - 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 models import User + from . import models class UserFactory(factory.Factory): - FACTORY_FOR = User + FACTORY_FOR = models.User first_name = 'John' last_name = 'Doe' @@ -48,14 +67,15 @@ Factories declare a set of attributes used to instantiate an object. The class o # Another, different, factory for the same object class AdminFactory(factory.Factory): - FACTORY_FOR = User + 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:: @@ -68,174 +88,140 @@ factory_boy supports several different build strategies: build, create, attribut # Returns a dict of attributes that can be used to build a User instance attributes = UserFactory.attributes() - # Returns an object with all defined attributes stubbed out: - stub = UserFactory.stub() You can use the Factory class as a shortcut for the default build strategy:: # Same as UserFactory.create() user = UserFactory() -The default strategy can be overridden:: - UserFactory.default_strategy = factory.BUILD_STRATEGY - user = UserFactory() - -The default strategy can also be overridden for all factories:: +No matter which strategy is used, it's possible to override the defined attributes by passing keyword arguments: - # This will set the default strategy for all factories that don't define a default build strategy - factory.Factory.default_strategy = factory.BUILD_STRATEGY - -No matter which strategy is used, it's possible to override the defined attributes by passing keyword arguments:: +.. code-block:: pycon # Build a User instance and override first_name - user = UserFactory.build(first_name='Joe') - user.first_name - # => 'Joe' + >>> 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 associations and other attributes that must be dynamically generated) will need values assigned each time an instance is generated. These "lazy" attributes can be added as follows:: +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: + +.. code-block:: python 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' +.. code-block:: pycon -The function passed to ``LazyAttribute`` is given the attributes defined for the factory up to the point of the LazyAttribute declaration. If a lambda won't cut it, the ``lazy_attribute`` decorator can be used to wrap a function:: + >>> UserFactory().email + "joe.blow@example.com" - # Stub factories don't have an associated class. - class SumFactory(factory.StubFactory): - lhs = 1 - rhs = 1 - @lazy_attribute - def sum(a): - result = a.lhs + a.rhs # Or some other fancy calculation - return result - -Associations ------------- +Sequences +""""""""" -Associated instances can also be generated using ``LazyAttribute``:: +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``: - from models import Post +.. code-block:: python - class PostFactory(factory.Factory): - author = factory.LazyAttribute(lambda a: UserFactory()) + class UserFactory(factory.Factory): + FACTORY_FOR = models.User + email = factory.Sequence(lambda n: 'person{0}@example.com'.format(n)) -The associated object's default strategy is always used:: + >>> UserFactory().email + 'person0@example.com' + >>> UserFactory().email + 'person1@example.com' - # Builds and saves a User and a Post - post = PostFactory() - post.id == None # => False - post.author.id == None # => False - # Builds and saves a User, and then builds but does not save a Post - post = PostFactory.build() - post.id == None # => True - post.author.id == None # => False +Associations +"""""""""""" -Inheritance ------------ +Some objects have a complex field, that should itself be defined from a dedicated factories. +This is handled by the ``SubFactory`` helper: -You can easily create multiple factories for the same class without repeating common attributes by using inheritance:: +.. code-block:: python class PostFactory(factory.Factory): - title = 'A title' + FACTORY_FOR = models.Post + author = factory.SubFactory(UserFactory) - class ApprovedPost(PostFactory): - approved = True - approver = factory.LazyAttribute(lambda a: UserFactory()) -Sequences ---------- +The associated object's strategy will be used: -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): - email = factory.Sequence(lambda n: 'person{0}@example.com'.format(n)) +.. code-block:: python - UserFactory().email # => 'person0@example.com' - UserFactory().email # => 'person1@example.com' + # 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 -Sequences can be combined with lazy attributes:: + # 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 - class UserFactory(factory.Factory): - name = 'Mark' - email = factory.LazyAttributeSequence(lambda a, n: '{0}+{1}@example.com'.format(a.name, n).lower()) - UserFactory().email # => mark+0@example.com +Contributing +------------ -If you wish to use a custom method to set the initial ID for a sequence, you can override the ``_setup_next_sequence`` class method:: +factory_boy is distributed under the MIT License. - class MyFactory(factory.Factory): +Issues should be opened through `GitHub Issues <http://github.com/rbarrois/factory_boy/issues/>`_; whenever possible, a pull request should be included. - @classmethod - def _setup_next_sequence(cls): - return cls._associated_class.objects.values_list('id').order_by('-id')[0] + 1 +All pull request should pass the test suite, which can be launched simply with: -Customizing creation --------------------- +.. code-block:: sh -Sometimes, the default build/create by keyword arguments doesn't allow for enough -customization of the generated objects. In such cases, you should override the -Factory._prepare method:: + $ python setup.py test - class UserFactory(factory.Factory): - @classmethod - def _prepare(cls, create, **kwargs): - password = kwargs.pop('password', None) - user = super(UserFactory, cls)._prepare(create, **kwargs) - if password: - user.set_password(password) - if create: - user.save() - return user - -Subfactories ------------- -If one of your factories has a field which is another factory, you can declare it as a ``SubFactory``. This allows to define attributes of that field when calling -the global factory, using a simple syntax : ``field__attr=42`` will set the attribute ``attr`` of the ``SubFactory`` defined in ``field`` to 42:: +.. note:: + + Running test requires the unittest2 (standard in Python 2.7+) and mock libraries. - class InnerFactory(factory.Factory): - foo = 'foo' - bar = factory.LazyAttribute(lambda o: foo * 2) - class ExternalFactory(factory.Factory): - inner = factory.SubFactory(InnerFactory, foo='bar') +In order to test coverage, please use: - >>> e = ExternalFactory() - >>> e.foo - 'bar' - >>> e.bar - 'barbar' +.. code-block:: sh - >>> e2 : ExternalFactory(inner__bar='baz') - >>> e2.foo - 'bar' - >>> e2.bar - 'baz' + $ pip install coverage + $ coverage erase; coverage run --branch setup.py test; coverage report -Abstract factories ------------------- -If a ``Factory`` simply defines generic attribute declarations without being bound to a given class, -it should be marked 'abstract' by declaring ``ABSTRACT_FACTORY = True``. -Such factories cannot be built/created/.... +Contents, indices and tables +---------------------------- +.. toctree:: + :maxdepth: 2 - class AbstractFactory(factory.Factory): - ABSTRACT_FACTORY = True - foo = 'foo' + introduction + reference + orms + recipes + fuzzy + examples + internals + changelog + ideas - >>> AbstractFactory() - Traceback (most recent call last): - ... - AttributeError: type object 'AbstractFactory' has no attribute '_associated_class' +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` |