Skip to main content
This is a pre-production deployment of Warehouse. Changes made here affect the production instance of PyPI (
Help us improve Python packaging - Donate today!

Generic model factory framework

Project Description

PyFactory is a library for writing generic model factories useful for unit testing.


Basic Example

The example below shows a very simple example. Say somewhere in our tests we need various instances of User objects. In our tests we would simply write the following to create a user:

user = UserFactory().create("basic")

The PyFactory code necessary to make this happen is shown below. Note that the ModelBuilder created would only have to be done once.

from pyfactory import Factory, schema

import models

class ModelBuilder(object):
    The model builder is responsible for knowing how to build
    and create models based on their attributes. This is what
    allows PyFactory to be completely model-agnostic.

    def build(cls, model_cls, attrs):
        return model_cls(attributes)

    def create(cls, model_cls, attrs):
        result =, attrs)
        return result

class UserFactory(Factory):
    This shows a simple factory which creates a type of User.

    _model = models.user.User
    _model_builder = ModelBuilder

    def basic(self):
        return {
            "first_name": "Test",
            "last_name": "User",


In any application, models typically have associations. Let’s look at the case where we have a Post model which is written by a User. If we want a valid Post object in our tests, once again we only need to do the following:

post = PostFactory().create("basic")

And the PyFactory factories to make this possible are equally simple:

class PostFactory(Factory):
    def basic(self):
        return {
            "title": "Fake Title",
            "body": "Lorem ipsum...",
            "author_id": association(UserFactory(), "basic", "id")

Attribute Overrides

Given the above examples, what if you already had a User that you wanted as a post author? Well, its simple to override attributes by just passing the override attributes as additional keyword arguments to the factory method:

author = # Pretend we got an author somewhere
post = PostFactory().create("basic",

Release History

This version
History Node


History Node


History Node


History Node


Download Files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Filename, Size & Hash SHA256 Hash Help File Type Python Version Upload Date
(6.1 kB) Copy SHA256 Hash SHA256
Source None Aug 31, 2011

Supported By

Elastic Elastic Search Pingdom Pingdom Monitoring Dyn Dyn DNS Sentry Sentry Error Logging CloudAMQP CloudAMQP RabbitMQ Heroku Heroku PaaS Kabu Creative Kabu Creative UX & Design Fastly Fastly CDN DigiCert DigiCert EV Certificate Google Google Cloud Servers DreamHost DreamHost Log Hosting