ZetCode

Django testing

last modified November 21, 2026 Python 3.15

Django comes with a test framework built on Python's unittest. The command manage.py test finds the tests, creates a separate test database, sets up a test environment where email is kept in memory instead of being sent, runs the tests, and removes the database again. Django adds test case classes that wrap every test in a transaction, a test client that sends requests to the views without a server, and assertions for responses, templates, redirects, and forms. In this article we test a small task list application step by step, from a test of one model method to a suite of thirty tests and its coverage. The examples use Django 6.1 and Python 3.15.

The example project

The project is created with uv; the steps are explained in Django introduction. The commands below create a project directory, install Django, generate the project with the configuration package config, start the app tasks.

$ mkdir tasklist
$ cd tasklist
$ uv init --bare
$ uv add django
$ uv run django-admin startproject config .
$ uv run python manage.py startapp tasks

The trailing dot in startproject config . creates manage.py and the config package in the current directory instead of one level deeper. The new app is added to INSTALLED_APPS in config/settings.py; the other entries are generated by startproject. At the end of the file we add the setting TASKS_NOTIFY, a list of addresses that get an email when someone adds an urgent task.

config/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'tasks',
]

...

TASKS_NOTIFY = ['boss@example.com']

A task has a title, a priority from 1 to 5, an optional due date, and a flag that says whether it is done. The custom QuerySet adds the method pending() (see Django managers and custom QuerySets). The method is_overdue() takes the current date as an optional argument; code that reads the clock itself is hard to test, so the tests can pass a fixed date instead. The method contains a bug, which our tests will find.

tasks/models.py
from datetime import date

from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models


class TaskQuerySet(models.QuerySet):
    def pending(self):
        return self.filter(done=False)


class Task(models.Model):
    title = models.CharField(max_length=100)
    priority = models.PositiveSmallIntegerField(
        default=3, validators=[MinValueValidator(1), MaxValueValidator(5)])
    due = models.DateField(null=True, blank=True)
    done = models.BooleanField(default=False)

    objects = TaskQuerySet.as_manager()

    class Meta:
        ordering = ['-priority', 'title']

    def __str__(self):
        return self.title

    def is_overdue(self, today=None):
        if self.done or self.due is None:
            return False
        today = today or date.today()
        return self.due <= today

We create the migration. The tests do not need the development database db.sqlite3: the test runner builds its own database from the migrations.

$ uv run python manage.py makemigrations tasks
Migrations for 'tasks':
  tasks/migrations/0001_initial.py
    + Create model Task

A first test

startapp generated the module tasks/tests.py. A test is a method whose name starts with test in a subclass of a test case class. SimpleTestCase is the Django test case for tests that do not touch the database; it is the right choice here, because Task(...) creates a model instance in memory without saving it. The assertion methods, such as assertTrue and assertFalse, come from unittest.

tasks/tests.py
from datetime import date

from django.test import SimpleTestCase

from tasks.models import Task


class TaskOverdueTests(SimpleTestCase):

    def test_past_due_date_is_overdue(self):
        task = Task(title='Pay rent', due=date(2026, 11, 1))
        self.assertTrue(task.is_overdue(today=date(2026, 11, 21)))

    def test_done_task_is_never_overdue(self):
        task = Task(title='Pay rent', due=date(2026, 11, 1), done=True)
        self.assertFalse(task.is_overdue(today=date(2026, 11, 21)))

    def test_task_without_due_date(self):
        task = Task(title='Read a book')
        self.assertFalse(task.is_overdue())

The test runner searches every installed app for modules named test*.py. Each passed test prints a dot. Since no test needs the database, no test database is created.

$ uv run python manage.py test
Found 3 test(s).
System check identified no issues (0 silenced).
...
----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK

A failing test

A task due today is still on time, so it should not be overdue. We add a test for this case to tasks/tests.py.

tasks/tests.py
from datetime import date

from django.test import SimpleTestCase

from tasks.models import Task


class TaskOverdueTests(SimpleTestCase):

    def test_past_due_date_is_overdue(self):
        task = Task(title='Pay rent', due=date(2026, 11, 1))
        self.assertTrue(task.is_overdue(today=date(2026, 11, 21)))

    def test_done_task_is_never_overdue(self):
        task = Task(title='Pay rent', due=date(2026, 11, 1), done=True)
        self.assertFalse(task.is_overdue(today=date(2026, 11, 21)))

    def test_task_without_due_date(self):
        task = Task(title='Read a book')
        self.assertFalse(task.is_overdue())

    def test_due_today_is_not_overdue(self):
        task = Task(title='Pay rent', due=date(2026, 11, 21))
        self.assertFalse(task.is_overdue(today=date(2026, 11, 21)))

The second test fails. A failure prints F instead of the dot, then the name of the test, the line, and the assertion message, and the command exits with a non-zero status. A test that raises any other exception would be reported as an error, E.

$ uv run python manage.py test
Found 4 test(s).
System check identified no issues (0 silenced).
.F..
======================================================================
FAIL: test_due_today_is_not_overdue (tasks.tests.TaskOverdueTests.test_due_today_is_not_overdue)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "./tasks/tests.py", line 24, in test_due_today_is_not_overdue
    self.assertFalse(task.is_overdue(today=date(2026, 11, 21)))
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: True is not false

----------------------------------------------------------------------
Ran 4 tests in 0.001s

FAILED (failures=1)

Fixing the bug

The comparison in is_overdue() must be strict. This is the final version of the model.

tasks/models.py
from datetime import date

from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models


class TaskQuerySet(models.QuerySet):
    def pending(self):
        return self.filter(done=False)


class Task(models.Model):
    title = models.CharField(max_length=100)
    priority = models.PositiveSmallIntegerField(
        default=3, validators=[MinValueValidator(1), MaxValueValidator(5)])
    due = models.DateField(null=True, blank=True)
    done = models.BooleanField(default=False)

    objects = TaskQuerySet.as_manager()

    class Meta:
        ordering = ['-priority', 'title']

    def __str__(self):
        return self.title

    def is_overdue(self, today=None):
        if self.done or self.due is None:
            return False
        today = today or date.today()
        return self.due < today

All four tests pass.

$ uv run python manage.py test
Found 4 test(s).
System check identified no issues (0 silenced).
....
----------------------------------------------------------------------
Ran 4 tests in 0.000s

OK

A tests package

One module becomes too long as the tests grow. We replace it with a package tests and put the tests of each part of the app into its own module. Every module name must start with test, and the package needs an __init__.py. The tests import the model with an absolute import, from tasks.models import Task, so the moved module works without changes.

$ mkdir tasks/tests
$ mv tasks/tests.py tasks/tests/test_models.py
$ touch tasks/tests/__init__.py
$ tree tasks/tests
tasks/tests
├── __init__.py
└── test_models.py

0 directories, 2 files

Running selected tests

The command accepts labels: a dotted path to a package, a module, a class, or a single method. The option -v 2 prints the name of every test, and the message Skipping setup of unused database(s) confirms that no database was created. The option -k runs only the tests whose name contains a pattern.

$ uv run python manage.py test tasks.tests.test_models -v 2
Found 4 test(s).
Skipping setup of unused database(s): default.
System check identified no issues (0 silenced).
test_done_task_is_never_overdue (tasks.tests.test_models.TaskOverdueTests.test_done_task_is_never_overdue) ... ok
test_due_today_is_not_overdue (tasks.tests.test_models.TaskOverdueTests.test_due_today_is_not_overdue) ... ok
test_past_due_date_is_overdue (tasks.tests.test_models.TaskOverdueTests.test_past_due_date_is_overdue) ... ok
test_task_without_due_date (tasks.tests.test_models.TaskOverdueTests.test_task_without_due_date) ... ok

----------------------------------------------------------------------
Ran 4 tests in 0.000s

OK
$ uv run python manage.py test -k due_date
Found 2 test(s).
System check identified no issues (0 silenced).
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

Tests with the database

Tests that read or write models use TestCase. It runs every test in a transaction and rolls it back afterwards, so each test starts with the same data, whatever the previous test did. The class method setUpTestData() creates the data once for the whole class; the method setUp(), which runs before every test, is slower for data that every test needs. The objects stored in class attributes, such as cls.rent, are copied for each test, so a test may change them.

tasks/tests/test_queries.py
from datetime import date

from django.test import TestCase

from tasks.models import Task


class TaskQueryTests(TestCase):

    @classmethod
    def setUpTestData(cls):
        cls.rent = Task.objects.create(title='Pay rent', priority=5, due=date(2026, 11, 1))
        Task.objects.create(title='Buy milk', priority=2)
        Task.objects.create(title='Call mom', priority=4, done=True)

    def test_pending_excludes_done_tasks(self):
        titles = [task.title for task in Task.objects.pending()]
        self.assertEqual(titles, ['Pay rent', 'Buy milk'])

    def test_changes_are_rolled_back(self):
        Task.objects.all().delete()
        self.assertEqual(Task.objects.count(), 0)

    def test_complete_task(self):
        self.rent.done = True
        self.rent.save()
        self.assertQuerySetEqual(Task.objects.pending(), ['Buy milk'], transform=str)

    def test_data_is_restored_for_each_test(self):
        self.assertEqual(Task.objects.count(), 3)
        self.assertFalse(self.rent.done)

The runner executes the methods of a class in alphabetical order. The test test_data_is_restored_for_each_test runs after the test that deleted all tasks and after the one that completed the rent task, and still sees three tasks and a pending self.rent. assertQuerySetEqual() compares a QuerySet with a list; transform=str turns each task into its title first. The verbose output shows how the runner creates the test database: in memory for SQLite, with the tables created by the migrations. We filter out the long list of applied migrations with grep.

$ uv run python manage.py test tasks.tests.test_queries -v 2 2>&1 | grep -v "^  Apply"
Found 4 test(s).
Creating test database for alias 'default' ('file:memorydb_default?mode=memory&cache=shared')...
Operations to perform:
  Synchronize unmigrated apps: messages, staticfiles
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
Running migrations:
System check identified no issues (0 silenced).
test_changes_are_rolled_back (tasks.tests.test_queries.TaskQueryTests.test_changes_are_rolled_back) ... ok
test_complete_task (tasks.tests.test_queries.TaskQueryTests.test_complete_task) ... ok
test_data_is_restored_for_each_test (tasks.tests.test_queries.TaskQueryTests.test_data_is_restored_for_each_test) ... ok
test_pending_excludes_done_tasks (tasks.tests.test_queries.TaskQueryTests.test_pending_excludes_done_tasks) ... ok

----------------------------------------------------------------------
Ran 4 tests in 0.003s

OK
Destroying test database for alias 'default' ('file:memorydb_default?mode=memory&cache=shared')...

The test client

The test client sends requests through the whole Django stack: URL resolution, middleware, the view, and the template. No server runs; the request is processed in the same process. We write two views: the list of pending tasks and the detail of a task.

tasks/views.py
from django.shortcuts import get_object_or_404, render

from .models import Task


def task_list(request):
    tasks = Task.objects.pending()
    return render(request, 'tasks/task_list.html', {'tasks': tasks})


def task_detail(request, pk):
    task = get_object_or_404(Task, pk=pk)
    return render(request, 'tasks/task_detail.html', {'task': task})

The app's URLconf names the URLs, so the tests can build them with reverse().

tasks/urls.py
from django.urls import path

from . import views

app_name = 'tasks'
urlpatterns = [
    path('', views.task_list, name='list'),
    path('<int:pk>/', views.task_detail, name='detail'),
]

The project includes the URLs of the app under /tasks/.

config/urls.py
from django.urls import include, path

urlpatterns = [
    path('tasks/', include('tasks.urls')),
]

The list template marks overdue tasks and shows a message when there is nothing to do.

tasks/templates/tasks/task_list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Tasks</title>
</head>
<body>
<h1>Tasks</h1>
<ul>
{% for task in tasks %}
  <li><a href="{% url 'tasks:detail' task.pk %}">{{ task.title }}</a>{% if task.is_overdue %} (overdue){% endif %}</li>
{% empty %}
  <li>Nothing to do.</li>
{% endfor %}
</ul>
</body>
</html>

The detail template shows the priority and the due date.

tasks/templates/tasks/task_detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{ task.title }}</title>
</head>
<body>
<h1>{{ task.title }}</h1>
<p>Priority: {{ task.priority }}</p>
<p>Due: {{ task.due|default:"no date" }}</p>
</body>
</html>

Every TestCase has a client in self.client. The response it returns has, besides the status code and the content, two test-only attributes: context, the context the template was rendered with, and templates, which assertTemplateUsed() checks. assertContains() checks the status code (200 by default) and searches the content for a text; with html=True it compares HTML elements, so whitespace and attribute order do not matter.

tasks/tests/test_views.py
from datetime import date

from django.test import TestCase
from django.urls import reverse

from tasks.models import Task


class TaskViewTests(TestCase):

    @classmethod
    def setUpTestData(cls):
        cls.rent = Task.objects.create(title='Pay rent', priority=5, due=date(2026, 11, 1))
        Task.objects.create(title='Call mom', done=True)

    def test_list_shows_pending_tasks(self):
        response = self.client.get(reverse('tasks:list'))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'tasks/task_list.html')
        self.assertContains(response, 'Pay rent')
        self.assertNotContains(response, 'Call mom')

    def test_list_marks_overdue_tasks(self):
        response = self.client.get(reverse('tasks:list'))
        url = reverse('tasks:detail', args=[self.rent.pk])
        self.assertContains(response, f'<li><a href="{url}">Pay rent</a> (overdue)</li>',
                            html=True)

    def test_empty_list(self):
        Task.objects.all().delete()
        response = self.client.get(reverse('tasks:list'))
        self.assertQuerySetEqual(response.context['tasks'], [])
        self.assertContains(response, 'Nothing to do.')

    def test_detail_of_missing_task_is_404(self):
        response = self.client.get(reverse('tasks:detail', args=[999]))
        self.assertEqual(response.status_code, 404)

The output of the runner is filtered to the lines with test results.

$ uv run python manage.py test tasks.tests.test_views -v 2 2>&1 | grep -F " ... "
test_detail_of_missing_task_is_404 (tasks.tests.test_views.TaskViewTests.test_detail_of_missing_task_is_404) ... ok
test_empty_list (tasks.tests.test_views.TaskViewTests.test_empty_list) ... ok
test_list_marks_overdue_tasks (tasks.tests.test_views.TaskViewTests.test_list_marks_overdue_tasks) ... ok
test_list_shows_pending_tasks (tasks.tests.test_views.TaskViewTests.test_list_shows_pending_tasks) ... ok

Logging in a test user

Only logged-in users may add tasks. The view task_create is protected with @login_required and uses a ModelForm; when the new task has the highest priority, it sends an email to the addresses in TASKS_NOTIFY. send_mail() with None as the sender uses DEFAULT_FROM_EMAIL.

tasks/views.py
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.core.mail import send_mail
from django.shortcuts import get_object_or_404, redirect, render

from .forms import TaskForm
from .models import Task


def task_list(request):
    tasks = Task.objects.pending()
    return render(request, 'tasks/task_list.html', {'tasks': tasks})


def task_detail(request, pk):
    task = get_object_or_404(Task, pk=pk)
    return render(request, 'tasks/task_detail.html', {'task': task})


@login_required
def task_create(request):
    form = TaskForm(request.POST or None)
    if form.is_valid():
        task = form.save()
        if task.priority == 5 and settings.TASKS_NOTIFY:
            send_mail(f'Urgent task: {task.title}',
                      f'{request.user.username} added an urgent task.',
                      None, settings.TASKS_NOTIFY)
        return redirect('tasks:list')
    return render(request, 'tasks/task_form.html', {'form': form})

The form contains the fields a user may set; done keeps its default value.

tasks/forms.py
from django import forms

from .models import Task


class TaskForm(forms.ModelForm):
    class Meta:
        model = Task
        fields = ['title', 'priority', 'due']

The URLconf gets the third URL.

tasks/urls.py
from django.urls import path

from . import views

app_name = 'tasks'
urlpatterns = [
    path('', views.task_list, name='list'),
    path('<int:pk>/', views.task_detail, name='detail'),
    path('new/', views.task_create, name='create'),
]

The form template renders the form with its CSRF token.

tasks/templates/tasks/task_form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>New task</title>
</head>
<body>
<h1>New task</h1>
<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Save</button>
</form>
</body>
</html>

The client has two ways to log in. login() goes through the authentication backends with a user name and a password and returns False when they do not match. force_login() logs a user in directly; it is faster, because it skips the password hashing, and it is the usual choice when the login itself is not what the test is about. The anonymous request is redirected to LOGIN_URL. This project has no login page, so fetch_redirect_response=False stops assertRedirects() from loading the target and expecting status 200.

tasks/tests/test_login.py
from django.contrib.auth.models import User
from django.test import TestCase
from django.urls import reverse


class TaskCreateAccessTests(TestCase):

    @classmethod
    def setUpTestData(cls):
        cls.user = User.objects.create_user('alice', password='s3cret-pass')

    def test_anonymous_user_is_redirected(self):
        url = reverse('tasks:create')
        response = self.client.get(url)
        self.assertRedirects(response, f'/accounts/login/?next={url}',
                             fetch_redirect_response=False)

    def test_login_with_password(self):
        logged_in = self.client.login(username='alice', password='s3cret-pass')
        self.assertTrue(logged_in)
        response = self.client.get(reverse('tasks:create'))
        self.assertContains(response, '<form method="post">')

    def test_wrong_password(self):
        logged_in = self.client.login(username='alice', password='guess')
        self.assertFalse(logged_in)

    def test_force_login(self):
        self.client.force_login(self.user)
        response = self.client.get(reverse('tasks:create'))
        self.assertEqual(response.context['user'], self.user)
        self.assertContains(response, 'name="title"')

These tests take longer than the others, because creating a user with a password and checking it run the password hasher.

$ uv run python manage.py test tasks.tests.test_login -v 2 2>&1 | grep -F " ... "
test_anonymous_user_is_redirected (tasks.tests.test_login.TaskCreateAccessTests.test_anonymous_user_is_redirected) ... ok
test_force_login (tasks.tests.test_login.TaskCreateAccessTests.test_force_login) ... ok
test_login_with_password (tasks.tests.test_login.TaskCreateAccessTests.test_login_with_password) ... ok
test_wrong_password (tasks.tests.test_login.TaskCreateAccessTests.test_wrong_password) ... ok

Posting forms

self.client.post() sends form data. The user is logged in in setUp(), because the client is new for every test. A valid form redirects, which assertRedirects() checks together with the status of the target page. assertFormError() checks an error of a form field; the form is taken from the context of the response. With follow=True the client follows the redirects and records them in redirect_chain. The client does not check CSRF tokens unless it is created with Client(enforce_csrf_checks=True).

tasks/tests/test_forms.py
from django.contrib.auth.models import User
from django.test import TestCase
from django.urls import reverse

from tasks.models import Task


class TaskCreateTests(TestCase):

    @classmethod
    def setUpTestData(cls):
        cls.user = User.objects.create_user('alice')

    def setUp(self):
        self.client.force_login(self.user)
        self.url = reverse('tasks:create')

    def test_valid_post_creates_task(self):
        response = self.client.post(self.url, {'title': 'Water plants', 'priority': 2})
        self.assertRedirects(response, reverse('tasks:list'))
        task = Task.objects.get()
        self.assertEqual((task.title, task.priority, task.due), ('Water plants', 2, None))

    def test_invalid_priority(self):
        response = self.client.post(self.url, {'title': 'Water plants', 'priority': 9})
        self.assertEqual(response.status_code, 200)
        self.assertFormError(response.context['form'], 'priority',
                             'Ensure this value is less than or equal to 5.')
        self.assertFalse(Task.objects.exists())

    def test_missing_title(self):
        response = self.client.post(self.url, {'priority': 2})
        self.assertFormError(response.context['form'], 'title', 'This field is required.')

    def test_follow_redirect(self):
        response = self.client.post(self.url, {'title': 'Water plants', 'priority': 2},
                                    follow=True)
        self.assertEqual(response.redirect_chain, [('/tasks/', 302)])
        self.assertContains(response, 'Water plants')

The error message for the priority comes from the MaxValueValidator of the model field, which the ModelForm inherits.

$ uv run python manage.py test tasks.tests.test_forms
Found 4 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
....
----------------------------------------------------------------------
Ran 4 tests in 0.025s

OK
Destroying test database for alias 'default'...

Testing email

The test runner replaces the email backends of MAILERS with the in-memory backend. Messages are not sent; they are collected in the list django.core.mail.outbox, which is emptied before every test. The tests check the subject, the recipients, the sender, and the body of the message (see Django email for sending email).

tasks/tests/test_email.py
from django.contrib.auth.models import User
from django.core import mail
from django.test import TestCase
from django.urls import reverse


class UrgentTaskEmailTests(TestCase):

    @classmethod
    def setUpTestData(cls):
        cls.user = User.objects.create_user('alice')

    def setUp(self):
        self.client.force_login(self.user)

    def test_urgent_task_sends_email(self):
        self.client.post(reverse('tasks:create'), {'title': 'Fix the roof', 'priority': 5})
        self.assertEqual(len(mail.outbox), 1)
        message = mail.outbox[0]
        self.assertEqual(message.subject, 'Urgent task: Fix the roof')
        self.assertEqual(message.to, ['boss@example.com'])
        self.assertEqual(message.from_email, 'webmaster@localhost')
        self.assertIn('alice', message.body)

    def test_normal_task_sends_no_email(self):
        self.client.post(reverse('tasks:create'), {'title': 'Water plants', 'priority': 3})
        self.assertEqual(mail.outbox, [])

An urgent task produces one message; a normal one none.

$ uv run python manage.py test tasks.tests.test_email -v 2 2>&1 | grep -F " ... "
test_normal_task_sends_no_email (tasks.tests.test_email.UrgentTaskEmailTests.test_normal_task_sends_no_email) ... ok
test_urgent_task_sends_email (tasks.tests.test_email.UrgentTaskEmailTests.test_urgent_task_sends_email) ... ok

Overriding settings

The settings of a test should not depend on the settings file. override_settings changes settings for a whole class or for one method, and self.settings() for a block of code; after the test, or the block, the original values return. The method decorator wins over the class decorator. The view reads settings.TASKS_NOTIFY when the request is processed, so it sees the overridden value.

tasks/tests/test_settings.py
from django.conf import settings
from django.contrib.auth.models import User
from django.core import mail
from django.test import TestCase, override_settings
from django.urls import reverse

URGENT = {'title': 'Fix the roof', 'priority': 5}


@override_settings(TASKS_NOTIFY=['team@example.com', 'boss@example.com'])
class NotifySettingsTests(TestCase):

    @classmethod
    def setUpTestData(cls):
        cls.user = User.objects.create_user('alice')

    def setUp(self):
        self.client.force_login(self.user)

    def test_class_override(self):
        self.client.post(reverse('tasks:create'), URGENT)
        self.assertEqual(mail.outbox[0].to, ['team@example.com', 'boss@example.com'])

    @override_settings(TASKS_NOTIFY=[])
    def test_method_override(self):
        self.client.post(reverse('tasks:create'), URGENT)
        self.assertEqual(mail.outbox, [])

    def test_context_manager(self):
        with self.settings(TASKS_NOTIFY=['ops@example.com']):
            self.client.post(reverse('tasks:create'), URGENT)
        self.assertEqual(mail.outbox[0].to, ['ops@example.com'])
        self.assertEqual(len(settings.TASKS_NOTIFY), 2)

The last assertion of test_context_manager() checks that after the block the class override, with its two addresses, is active again.

$ uv run python manage.py test tasks.tests.test_settings -v 2 2>&1 | grep -F " ... "
test_class_override (tasks.tests.test_settings.NotifySettingsTests.test_class_override) ... ok
test_context_manager (tasks.tests.test_settings.NotifySettingsTests.test_context_manager) ... ok
test_method_override (tasks.tests.test_settings.NotifySettingsTests.test_method_override) ... ok

RequestFactory

RequestFactory creates request objects that we pass straight to a view function. There is no URL resolution and no middleware, so the request has no session and no user, and no CSRF check runs; we set request.user ourselves. The response is the plain HttpResponse of the view, without context and templates. Such tests are useful for the logic of a view, for decorators, and for views that are not mapped to a URL yet; the path of the request does not have to exist.

tasks/tests/test_factory.py
from django.contrib.auth.models import AnonymousUser, User
from django.core import mail
from django.test import RequestFactory, TestCase

from tasks.models import Task
from tasks.views import task_create, task_list


class ViewFunctionTests(TestCase):

    @classmethod
    def setUpTestData(cls):
        cls.user = User.objects.create_user('alice')
        Task.objects.create(title='Pay rent', priority=5)

    def setUp(self):
        self.factory = RequestFactory()

    def test_list_view(self):
        request = self.factory.get('/any/path/')
        response = task_list(request)
        self.assertContains(response, 'Pay rent')

    def test_anonymous_user(self):
        request = self.factory.get('/tasks/new/')
        request.user = AnonymousUser()
        response = task_create(request)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.url, '/accounts/login/?next=/tasks/new/')

    def test_post_without_csrf_token(self):
        request = self.factory.post('/tasks/new/', {'title': 'Fix the roof', 'priority': 5})
        request.user = self.user
        response = task_create(request)
        self.assertEqual(response.status_code, 302)
        self.assertEqual(Task.objects.count(), 2)
        self.assertEqual(len(mail.outbox), 1)

The login_required decorator redirects the anonymous user, and the POST works without a CSRF token.

$ uv run python manage.py test tasks.tests.test_factory -v 2 2>&1 | grep -F " ... "
test_anonymous_user (tasks.tests.test_factory.ViewFunctionTests.test_anonymous_user) ... ok
test_list_view (tasks.tests.test_factory.ViewFunctionTests.test_list_view) ... ok
test_post_without_csrf_token (tasks.tests.test_factory.ViewFunctionTests.test_post_without_csrf_token) ... ok

Fixtures

A fixture is a file with serialized data. Django looks for fixtures in the fixtures directory of each app. The file can be written by hand or produced by dumpdata from an existing database (see Django management commands).

tasks/fixtures/tasks.json
[
  {
    "model": "tasks.task",
    "pk": 1,
    "fields": {"title": "Renew passport", "priority": 4, "due": "2026-12-15", "done": false}
  },
  {
    "model": "tasks.task",
    "pk": 2,
    "fields": {"title": "Book flights", "priority": 3, "due": null, "done": false}
  },
  {
    "model": "tasks.task",
    "pk": 3,
    "fields": {"title": "Pack bags", "priority": 2, "due": null, "done": true}
  }
]

The attribute fixtures of a TestCase lists fixtures to load; the name is given without the extension. TestCase loads them once for the class, and the transaction of each test is rolled back as with setUpTestData(). Fixtures do not change with the model, so a renamed or a new required field breaks them; data created in code is easier to maintain.

tasks/tests/test_fixtures.py
from django.test import TestCase
from django.urls import reverse

from tasks.models import Task


class FixtureTests(TestCase):
    fixtures = ['tasks']

    def test_fixture_is_loaded(self):
        self.assertEqual(Task.objects.count(), 3)
        self.assertEqual(Task.objects.get(pk=1).title, 'Renew passport')

    def test_list_page(self):
        response = self.client.get(reverse('tasks:list'))
        self.assertQuerySetEqual(response.context['tasks'],
                                 ['Renew passport', 'Book flights'], transform=str)

    def test_detail_page(self):
        response = self.client.get(reverse('tasks:detail', args=[1]))
        self.assertContains(response, 'Due: Dec. 15, 2026')

The detail page shows the due date in the default date format.

$ uv run python manage.py test tasks.tests.test_fixtures -v 2 2>&1 | grep -F " ... "
test_detail_page (tasks.tests.test_fixtures.FixtureTests.test_detail_page) ... ok
test_fixture_is_loaded (tasks.tests.test_fixtures.FixtureTests.test_fixture_is_loaded) ... ok
test_list_page (tasks.tests.test_fixtures.FixtureTests.test_list_page) ... ok

Running the whole suite

The package now contains nine modules. Without a label, the runner executes all 31 tests. The option --parallel runs the test classes in several processes, each with its own copy of the test database. For a suite as small as ours, starting the processes and cloning the database cost more than they save; parallel runs pay off for suites that take minutes.

$ tree -I __pycache__ tasks/tests
tasks/tests
├── __init__.py
├── test_email.py
├── test_factory.py
├── test_fixtures.py
├── test_forms.py
├── test_login.py
├── test_models.py
├── test_queries.py
├── test_settings.py
└── test_views.py

0 directories, 10 files
$ uv run python manage.py test
Found 31 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
...............................
----------------------------------------------------------------------
Ran 31 tests in 0.752s

OK
Destroying test database for alias 'default'...
$ uv run python manage.py test --parallel 4
Found 31 test(s).
Creating test database for alias 'default'...
Cloning test database for alias 'default'...
Cloning test database for alias 'default'...
Cloning test database for alias 'default'...
Cloning test database for alias 'default'...
System check identified no issues (0 silenced).
...............................
----------------------------------------------------------------------
Ran 31 tests in 0.966s

OK
Destroying test database for alias 'default'...
Destroying test database for alias 'default'...
Destroying test database for alias 'default'...
Destroying test database for alias 'default'...
Destroying test database for alias 'default'...

Measuring coverage

The coverage package records which lines run during the tests. We install it as a development dependency with uv add --dev coverage, which adds the group dev to pyproject.toml. The section [tool.coverage.run] limits the measurement to the app and leaves out the tests and the migrations.

pyproject.toml
[project]
name = "tasklist"
version = "0.1.0"
requires-python = ">=3.15"
dependencies = [
    "django>=6.1.3",
]

[dependency-groups]
dev = [
    "coverage>=7.17.4",
]

[tool.coverage.run]
source = ["tasks"]
omit = ["tasks/tests/*", "tasks/migrations/*"]

coverage run starts the test runner under the measurement, and coverage report -m prints the result with the numbers of the lines that never ran. We first run only the model and view tests. The report shows that line 17 of views.py, the rendering of an existing task, never ran: the view tests check only a missing task. Lines 22–30 are the body of task_create, and line 25 of the model is __str__().

$ uv run coverage run manage.py test tasks.tests.test_models tasks.tests.test_views
Found 8 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
........
----------------------------------------------------------------------
Ran 8 tests in 0.011s

OK
Destroying test database for alias 'default'...
$ uv run coverage report -m
Name                Stmts   Miss  Cover   Missing
-------------------------------------------------
tasks/__init__.py       0      0   100%
tasks/admin.py          1      0   100%
tasks/apps.py           3      0   100%
tasks/forms.py          6      0   100%
tasks/models.py        21      1    95%   25
tasks/urls.py           4      0   100%
tasks/views.py         21      8    62%   17, 22-30
-------------------------------------------------
TOTAL                  56      9    84%

Coverage of the whole suite

The whole suite covers every line. Full coverage shows that all lines ran, not that every case was tested: the detail page is covered only by the fixture test, and nothing tests a task with a due date in the future.

$ uv run coverage run manage.py test
Found 31 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
...............................
----------------------------------------------------------------------
Ran 31 tests in 0.753s

OK
Destroying test database for alias 'default'...
$ uv run coverage report
Name                Stmts   Miss  Cover
---------------------------------------
tasks/__init__.py       0      0   100%
tasks/admin.py          1      0   100%
tasks/apps.py           3      0   100%
tasks/forms.py          6      0   100%
tasks/models.py        21      0   100%
tasks/urls.py           4      0   100%
tasks/views.py         21      0   100%
---------------------------------------
TOTAL                  56      0   100%

Source

Django documentation: Testing in Django

Django documentation: Testing tools

Django documentation: Advanced testing topics

Coverage.py documentation

In this article we have tested a Django application with the built-in test runner: model methods with SimpleTestCase, queries with TestCase and setUpTestData(), views with the test client, logged-in users, forms, and email with mail.outbox, settings with override_settings, view functions with RequestFactory, data from fixtures, and the coverage of the suite. The article Django testing with pytest writes such tests with pytest and pytest-django. Related articles are Django views, Django forms, Django authentication, and Django query performance, which tests the number of queries with assertNumQueries.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Django tutorials.