summaryrefslogtreecommitdiff
path: root/README.rst
blob: 9b8240698bdebea8781fee513e53db9a4168273d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
factory_boy
===========

.. image:: https://pypip.in/version/factory_boy/badge.svg
    :target: http://factoryboy.readthedocs.org/en/latest/changelog.html
    :alt: Latest Version

.. image:: https://pypip.in/py_versions/factory_boy/badge.svg
    :target: https://pypi.python.org/pypi/factory_boy/
    :alt: Supported Python versions

.. image:: https://pypip.in/wheel/factory_boy/badge.svg
    :target: https://pypi.python.org/pypi/factory_boy/
    :alt: Wheel status

.. 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>`_.

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:

.. code-block:: python

    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, Mogo, 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


Links
-----

* Documentation: http://factoryboy.readthedocs.org/
* 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.


Download
--------

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

.. code-block:: sh

    $ pip install factory_boy

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

.. code-block:: sh

    $ 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 ``model`` field of a ``class Meta:`` attribute:

.. code-block:: python

    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:

.. code-block:: python

    # 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:

.. code-block:: python

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


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"


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

.. code-block:: pycon

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

Tests look better with random yet realistic values.
For this, factory_boy relies on the excellent `fake-factory <https://pypi.python.org/pypi/fake-factory>`_ library:

.. code-block:: python

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

        first_name = factory.Faker('first_name')
        last_name = factory.Faker('last_name')

.. code-block:: pycon

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

.. code-block:: python

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

.. code-block:: pycon

    >>> 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``:

.. code-block:: python

    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:

.. code-block:: python

    class PostFactory(factory.Factory):
        class Meta:
            model = models.Post

        author = factory.SubFactory(UserFactory)


The associated object's strategy will be used:


.. code-block:: python

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

.. code-block:: python

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

.. code-block:: ini

    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``
* MongoEngine, with ``factory.mongoengine.MongoEngineFactory``
* SQLAlchemy, with ``factory.alchemy.SQLAlchemyModelFactory``

Contributing
------------

factory_boy is distributed under the MIT License.

Issues should be opened through `GitHub Issues <http://github.com/rbarrois/factory_boy/issues/>`_; whenever possible, a pull request should be included.

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

.. code-block:: sh

    $ make test



In order to test coverage, please use:

.. code-block:: sh

    $ make coverage


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

.. code-block:: sh

    $ make DJANGO=1.7 test

Valid options are:

* ``DJANGO`` for ``Django``
* ``MONGOENGINE`` for ``mongoengine``
* ``ALCHEMY`` for ``SQLAlchemy``


Contents, indices and tables
----------------------------

.. toctree::
    :maxdepth: 2

    introduction
    reference
    orms
    recipes
    fuzzy
    examples
    internals
    changelog
    ideas

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`