Member preview

Testing Models with Django using Pytest and Factory Boy

Pytest and Factory Boy make a rad combo for testing Django Applications.

We can test models by arranging our models as factories and running testing logic on them.

Say we have an application that is storing customers and associated customer quote data, our data model to be tested could look like so:

from django.db import models
class Customer(models.Model):
Model for Customer Attributes
name = models.CharField(max_length=128)
class Quote(models.Model):
Model for Quote Attributes
customer = models.ForeignKey('Customer')
price = models.DecimalField(

We would like to arrange factories for these models to be tested. We can arrange our file like so:

import factory
from .models import Customer, Quote

class CustomerFactory(factory.DjangoModelFactory):
Define Customer Factory
class Meta:
model = Customer

class QuoteFactory(factory.DjangoModelFactory):
Define Quote Factory
class Meta:
model = Quote
    customer = factory.SubFactory(CustomerFactory)

Next, we are prepared to implement our tests:

import pytest
from .tests.factories import CustomerFactory, QuoteFactory

def test_customer_model():
""" Test customer model """
    # create customer model instance
customer = CustomerFactory(name="Test Customer Name")
    assert == "Test Customer Name"
def test_quote_creation():
""" Test quote model """
    # create customer and quote model instances
customer = CustomerFactory(name="Test Customer Name")
quote = QuoteFactory(customer=customer, price=100.00)

assert quote.customer == customer
asset == "Test Customer Name"
assert quote.price == 100.00

The django_db decorator must be used in order for pytest to access the testing models. We can validate that our models are working appropriately and write any tests we see fit with this configuration.

For more information on Pytest and Factory Boy, Check out the documentation: