factory_boy
Test fixtures library for Python that builds model instances with declarative factories and sequences.
Official Documentation ↗factory_boy 3.3+ / Python 3.8+. Check the official docs for the latest API surface.Installation
pip install factory-boyMethods
No methods match this filter.
Overview
factory_boy builds test data declaratively. A factory describes how to create a model, using sequences, fakers and sub-factories, so tests request valid objects without repeating setup code.
Core Methods
Define a factory with a Meta model and attributes, then call it to build or create instances. SubFactory and RelatedFactory compose related objects, and post_generation hooks run afterwards.
Usage Notes
Keep factories small and override attributes per test to show only the values that matter. Use sequences for uniqueness and batch generation for performance.
Common Pitfalls
Sharing mutable attributes can leak state between tests. Creating more objects than needed slows suites and hides coupling. Overusing faker values makes failures hard to reproduce.
FAQ
- What is a sequence for?
- Sequences produce unique, incrementing values so unique constraints such as usernames or emails do not collide across many generated objects.
- How do I build related objects?
- Use SubFactory to create related instances automatically, and factory.RelatedFactory for reverse relations, letting a factory assemble a valid object graph.
- Can factories call code after creation?
- Yes. @factory.post_generation hooks run after the object is built, which is useful for setting many-to-many relations or other post-create state.
Report a problem with this API docOpens a pre-filled issue on GitHub.