PyFactory 0.4.0 Documentation


PyFactory is a library for writing and using model factories. Model factories allow you to replace test fixtures or manual model creation in tests with succint, easy to use factories.

The need for factories becomes apparent when you’re testing any application of at least average complexity, where models often have a large tree of dependencies. For example, on some website you may want to test the Comment model. A Comment requires an author, which is a User, and a Post. A Post may further require a Category, and so on. So, just to test a simple Comment, you’re typically forced to either create a brittle network of static fixtures, or manually create many models and glue together their relationships. Yuck!

With model factories, you would simply do the following:

comment = CommentFactory().create("comment")

This handles creating all the dependent models, as well. And the code for this factory is equally simple:

from pyfactory import Factory, association, schema
import models

class CommentFactory(Factory):
    _model = models.Comment
    _model_builder = models.ModelBuilder

    def comment(self):
        return {
            "body": "Some text...",
            "author_id": association(UserFactory(), "user", "id"),
            "post_id": association(PostFactory(), "post", "id")

# Imagine the UserFactory and PostFactory here, which are basically
# equivalent to the above.



A Tutorial covering most of the features is available.

Usage Documentation

The following is a list of pages dedicated to specific concepts of PyFactory. It is recommended that you read the Tutorial before diving into these pages.

API Reference

A complete API reference is the recommend documentation for in-depth details on various pieces of PyFactory.

Indices and tables