How to test with Django and pytest fixtures

Here are some notes on how I like to write tests for a Django app that tests a model down to a view.

Django Model + pytest Fixture

This part is a mouthful, but I prefer to use the Model Bakery library to automatically create instances of Django models (aka a fixture) with good test data instead of manually creating them. This approach saves time and adds some variety to my test data.

We will also use the pytest fixture function to create and return an instance of a Django model using our Model Bakery fixture. This pytest fixture can be used in multiple test cases, ensuring consistency and reducing boilerplate code.

Every app in my project contains a file. My news app has a Category and a Post model, and my fixture looks like this.

# news/tests/

import pytest
from model_bakery import baker

def category(db):
    return baker.make("news.Category", name="Category Name")

def post(db, category):
    return baker.make("news.Post", title="Post Title", category=category)

Please note that a post fixture can accept category fixture as an argument.


At the top of my project, we will have a file. This is where we tell pytest to look for our fixtures so they may be automatically loaded.

pytest_plugins = ["news.tests.fixtures"]

Testing our models

Next, we write a very basic test to ensure our fixture can create an instance of a model.

# news/tests/

def test_get_category(category):
    assert == "Category Name"

def test_get_post(post):
    assert post.title == "Post Title"

Testing our views

I prefer working with django-test-plus because it helps make writing tests cleaner and more straightforward. Then, for every view we have, we will write a test to ensure that our URL patterns match our expected routes and that we return a predicted status code.

# news/tests/
import pytest

# test that our view resolves to the right uri path
def test_post_uri(tp):
    expected_url = "/"
    reversed_url = tp.reverse("post-list")
    assert expected_url == reversed_url

# test that our view works
def test_post_get(db, tp):
	response = tp.get("post-list")

Running tests

To run our tests, we can run pytest.

Jeff Triplett @webology