Testing Models with Django using Pytest and Factory Boy

Josh Dwernychuk
Nov 22, 2017 · 2 min read

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 modelsclass 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(
max_digits=10,
decimal_places=2,
blank=True,
null=True,
)

We would like to arrange factories for these models to be tested. We can arrange our factories.py 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 pytestfrom .tests.factories import CustomerFactory, QuoteFactory
@pytest.mark.django_db
def test_customer_model():
""" Test customer model """
# create customer model instance
customer = CustomerFactory(name="Test Customer Name")
assert customer.name == "Test Customer Name"@pytest.mark.django_db
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 quote.customer.name == "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:

https://docs.pytest.org/en/latest/

http://factoryboy.readthedocs.io/en/latest/

Josh Dwernychuk

Written by

Engineer, Author, Adventurer - http://joshdwernychuk.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade