blob: 2e0f4a3774fb622bcc8d87deffa44dccaf46cbf1 (
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
|
Welcome to Factory Boy's documentation!
=======================================
factory_boy provides easy replacement for fixtures, based on thouthbot's `factory_girl <http://github.com/thouthbot/factory_girl>`_.
It allows for an easy definition of factories, various build factories, factory inheritance, ...
Example
-------
Defining a factory
""""""""""""""""""
Simply subclass the :py:class:`~factory.Factory` class, adding various class attributes which will be used as defaults::
import factory
class MyUserFactory(factory.Factory):
FACTORY_FOR = MyUser # Define the related object
# A simple attribute
first_name = 'Foo'
# A 'sequential' attribute: each instance of the factory will have a different 'n'
last_name = factory.Sequence(lambda n: 'Bar' + n)
# A 'lazy' attribute: computed from the values of other attributes
email = factory.LazyAttribute(lambda o: '%s.%s@example.org' % (o.first_name.lower(), o.last_name.lower()))
Using a factory
"""""""""""""""
Once defined, a factory can be instantiated through different methods::
# Calls MyUser(first_name='Foo', last_name='Bar0', email='foo.bar0@example.org')
>>> user = MyUserFactory.build()
# Calls MyUser.objects.create(first_name='Foo', last_name='Bar1', email='foo.bar1@example.org')
>>> user = MyUserFactory.create()
# Values can be overridden
>>> user = MyUserFactory.build(first_name='Baz')
>>> user.email
'baz.bar2@example.org'
# Additional values can be specified
>>> user = MyUserFactory.build(some_other_var=42)
>>> user.some_other_var
42
Contents:
.. toctree::
:maxdepth: 2
examples
subfactory
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
|