0
# Factory Boy
1
2
A versatile test fixtures replacement based on thoughtbot's factory_bot for Ruby. Factory Boy provides a comprehensive library for generating test data with customizable attributes, supporting multiple build strategies and integrating seamlessly with popular ORMs including Django, SQLAlchemy, MongoEngine, and Mogo.
3
4
## Package Information
5
6
- **Package Name**: factory_boy
7
- **Language**: Python
8
- **Installation**: `pip install factory_boy`
9
10
## Core Imports
11
12
```python
13
import factory
14
```
15
16
Most commonly used components:
17
18
```python
19
from factory import Factory, Sequence, LazyAttribute, SubFactory, Faker
20
```
21
22
ORM-specific imports:
23
24
```python
25
from factory.django import DjangoModelFactory
26
from factory.alchemy import SQLAlchemyModelFactory
27
from factory.mongoengine import MongoEngineFactory
28
from factory.mogo import MogoFactory
29
30
# Also available at module level:
31
from factory import DjangoModelFactory, MogoFactory
32
```
33
34
## Basic Usage
35
36
```python
37
import factory
38
from factory import Sequence, LazyAttribute, SubFactory, Faker
39
40
# Define a simple factory
41
class UserFactory(factory.Factory):
42
class Meta:
43
model = User
44
45
# Simple static value
46
is_active = True
47
48
# Sequence for unique values
49
email = Sequence(lambda n: f'user{n}@example.com')
50
51
# Lazy attribute based on other fields
52
username = LazyAttribute(lambda obj: obj.email.split('@')[0])
53
54
# Faker integration for realistic data
55
first_name = Faker('first_name')
56
last_name = Faker('last_name')
57
58
# Using the factory
59
user = UserFactory() # Creates User instance
60
user = UserFactory.build() # Build without persistence
61
user = UserFactory.create() # Create with persistence
62
user = UserFactory.stub() # Create stub object
63
64
# Batch operations
65
users = UserFactory.build_batch(5) # Create 5 users
66
users = UserFactory.create_batch(3, is_active=False) # Override defaults
67
68
# Custom attributes
69
user = UserFactory(first_name='John', is_active=False)
70
```
71
72
## Architecture
73
74
Factory Boy follows a declarative factory pattern with three core concepts:
75
76
- **Factory Classes**: Define how to build objects with customizable attributes
77
- **Declarations**: Define how individual attributes are computed (sequences, lazy attributes, etc.)
78
- **Strategies**: Control object lifecycle (build, create, stub) and ORM integration
79
- **Post-Generation**: Perform actions after object creation (relationships, method calls)
80
81
This design enables maintainable, reusable test data generation that replaces static fixtures with flexible, programmatic object creation across different ORMs and testing frameworks.
82
83
## Capabilities
84
85
### Core Factory Classes
86
87
Essential factory classes supporting different build strategies and object types. Includes the main Factory class, dictionary and list factories, and stub-only factories.
88
89
```python { .api }
90
class Factory:
91
def build(**kwargs): ...
92
def create(**kwargs): ...
93
def stub(**kwargs): ...
94
def build_batch(size, **kwargs): ...
95
def create_batch(size, **kwargs): ...
96
97
class DictFactory(Factory): ...
98
class ListFactory(Factory): ...
99
class StubFactory(Factory): ...
100
101
def use_strategy(strategy): ...
102
```
103
104
[Core Factory Classes](./core-factories.md)
105
106
### Attribute Declarations
107
108
Comprehensive declaration types for generating dynamic attribute values including sequences, lazy evaluation, faker integration, and conditional logic.
109
110
```python { .api }
111
class Sequence:
112
def __init__(self, function): ...
113
114
class LazyAttribute:
115
def __init__(self, function): ...
116
117
class LazyFunction:
118
def __init__(self, function): ...
119
120
class Faker:
121
def __init__(self, provider, **kwargs): ...
122
123
class Iterator:
124
def __init__(self, iterator, cycle=True, getter=None): ...
125
126
class SelfAttribute:
127
def __init__(self, attribute_name, default=None): ...
128
```
129
130
[Attribute Declarations](./declarations.md)
131
132
### ORM Integration
133
134
Specialized factory classes for popular ORMs providing database persistence, get-or-create behavior, and ORM-specific features.
135
136
```python { .api }
137
class DjangoModelFactory(Factory): ...
138
class SQLAlchemyModelFactory(Factory): ...
139
class MongoEngineFactory(Factory): ...
140
class MogoFactory(Factory): ...
141
142
# Django helpers
143
class FileField: ...
144
class ImageField: ...
145
def mute_signals(*signals): ...
146
```
147
148
[ORM Integration](./orm-integration.md)
149
150
### Helper Functions and Utilities
151
152
Convenience functions for direct object creation, debugging tools, and declaration wrapper functions for functional programming styles.
153
154
```python { .api }
155
def build(klass, **kwargs): ...
156
def create(klass, **kwargs): ...
157
def stub(klass, **kwargs): ...
158
def make_factory(klass, **kwargs): ...
159
def debug(logger='factory', stream=None): ...
160
161
# Declaration wrappers
162
def lazy_attribute(func): ...
163
def sequence(func): ...
164
def post_generation(func): ...
165
```
166
167
[Helper Functions and Utilities](./helpers-and-utilities.md)
168
169
## Strategy Constants
170
171
```python { .api }
172
BUILD_STRATEGY = 'build'
173
CREATE_STRATEGY = 'create'
174
STUB_STRATEGY = 'stub'
175
SPLITTER = '__' # String for splitting attribute names into subfactory paths
176
177
# Module metadata
178
__version__ = '2.12.0' # Current version
179
__author__ = 'Raphaël Barrois <raphael.barrois+fboy@polytechnique.org>'
180
```
181
182
## Strategy and Utility Functions
183
184
```python { .api }
185
def use_strategy(new_strategy):
186
"""
187
Decorator to override default strategy for a factory class.
188
189
Args:
190
new_strategy (str): Strategy to use ('build', 'create', 'stub')
191
192
Returns:
193
Decorator function that modifies factory's default strategy
194
"""
195
```
196
197
## Exception Classes
198
199
```python { .api }
200
class FactoryError(Exception):
201
"""Base exception class for all factory_boy errors."""
202
203
class AssociatedClassError(FactoryError):
204
"""Raised when a Factory subclass lacks Meta.model."""
205
206
class UnknownStrategy(FactoryError):
207
"""Raised when a factory uses an unknown strategy."""
208
209
class UnsupportedStrategy(FactoryError):
210
"""Raised when trying to use an incompatible strategy on a Factory."""
211
212
class CyclicDefinitionError(FactoryError):
213
"""Raised when cyclical declaration dependencies are detected."""
214
215
class InvalidDeclarationError(FactoryError):
216
"""Raised when sub-declaration has no related declaration (e.g. 'foo__bar' without 'foo')."""
217
```
218
219
## Common Types
220
221
```python { .api }
222
# Strategy types
223
Strategy = Literal['build', 'create', 'stub']
224
225
# Declaration base class
226
class BaseDeclaration:
227
def evaluate(self, instance, step, extra): ...
228
```