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(
We would like to arrange factories for these models to be tested. We can arrange our factories.py file like so:
from .models import Customer, Quote
Define Customer Factory
model = Customer
Define Quote Factory
model = Quote customer = factory.SubFactory(CustomerFactory)
Next, we are prepared to implement our tests:
import pytestfrom .tests.factories import CustomerFactory, QuoteFactory
""" Test customer model """ # create customer model instance
customer = CustomerFactory(name="Test Customer Name") assert customer.name == "Test Customer Name"@pytest.mark.django_db
""" 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: