TExcelTAD
Home › Django › Django Testing

Django Testing

Automated tests let you change code with confidence: run one command and know within seconds whether the models, views and forms still behave. Django builds on Python's unittest and adds a test runner that creates a fresh test database, a test client for fake requests (which you've used throughout this course), and assertion helpers for responses and templates.

Where tests live and how they run

startapp creates tests.py in each app; larger apps use a tests/ package with test_models.py, test_views.py and so on. Test classes subclass django.test.TestCase, and every method whose name starts with test is a test:

python
# books/tests.py
from django.test import TestCase
from django.urls import reverse
from .models import Book

class BookTests(TestCase):
    @classmethod
    def setUpTestData(cls):             # runs once for the class
        cls.book = Book.objects.create(title="Dune", year=1965)

    def test_str(self):
        self.assertEqual(str(self.book), "Dune")

    def test_list_page(self):
        response = self.client.get(reverse("book_list"))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Dune")
        self.assertTemplateUsed(response, "books/book_list.html")
bash · try it yourself
python manage.py test books
Found 2 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
..
----------------------------------------------------------------------
Ran 2 tests in 0.012s

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

Each dot is a passing test; a failure shows F plus a detailed report. TestCase wraps every test in a transaction that is rolled back afterwards, so tests can't affect each other.

Test class Database Use for
SimpleTestCase not allowed pure functions, forms, templates, URL resolving
TestCase yes, each test rolled back most tests — fast
TransactionTestCase yes, tables truncated code that depends on real commits
LiveServerTestCase yes + a real server browser tests with Selenium/Playwright

Running Django tests in the playground

Under the hood, manage.py test uses unittest. We can do the same here: define a TestCase, load it with unittest, run it, and print a summary. (We print our own summary instead of unittest's report, because the report includes timing that changes from run to run.)

python · try it yourself
import sys, types, unittest, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
sys.modules["demo"] = types.ModuleType("demo")      # stand-in demo app (setUpTestData needs it)
sys.modules["demo"].__file__ = "demo/__init__.py"
settings.configure(SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"],
                   INSTALLED_APPS=["demo"],
                   DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django.db import models, connection
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.urls import path
from django.test import TestCase

class Book(models.Model):
    title = models.CharField(max_length=100)
    year = models.IntegerField()
    class Meta:
        app_label = "demo"
    def is_classic(self):
        return self.year < 1950

with connection.schema_editor() as editor:
    editor.create_model(Book)

def book_detail(request, pk):
    book = get_object_or_404(Book, pk=pk)
    return HttpResponse(f"<h1>{book.title}</h1>")

urls.urlpatterns = [path("books/<int:pk>/", book_detail)]

class BookTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.old = Book.objects.create(title="Emma", year=1815)
        cls.new = Book.objects.create(title="Klara and the Sun", year=2021)

    def test_is_classic(self):
        self.assertTrue(self.old.is_classic())
        self.assertFalse(self.new.is_classic())

    def test_detail_page(self):
        response = self.client.get(f"/books/{self.old.pk}/")
        self.assertContains(response, "<h1>Emma</h1>", html=True)

    def test_missing_book_is_404(self):
        self.assertEqual(self.client.get("/books/999/").status_code, 404)

    def test_rows_are_rolled_back(self):
        Book.objects.create(title="Temp", year=2000)
        self.assertEqual(Book.objects.count(), 3)

suite = unittest.defaultTestLoader.loadTestsFromTestCase(BookTests)
result = unittest.TestResult()
suite.run(result)
print("ran:", result.testsRun, "| failures:", len(result.failures), "| errors:", len(result.errors))
print("successful:", result.wasSuccessful())
print("books after the tests:", Book.objects.count())
ran: 4 | failures: 0 | errors: 0
successful: True
books after the tests: 0

Even the rows created in setUpTestData were rolled back after the class finished — the database is exactly as it was before.

Seeing a failure

When an assertion fails, the test is recorded with a helpful message. Here a deliberately buggy function meets its tests:

python · try it yourself
import unittest, django
from django.conf import settings
settings.configure()
django.setup()
from django.test import SimpleTestCase
from django.utils.text import slugify

def make_username(full_name):
    # bug: forgets to drop accents and doesn't use "." between names
    return full_name.lower().replace(" ", "")

class UsernameTests(SimpleTestCase):
    def test_simple(self):
        self.assertEqual(make_username("Ada Lovelace"), "ada.lovelace")

    def test_slugify_reference(self):
        self.assertEqual(slugify("Nguyễn Văn An"), "nguyen-van-an")

result = unittest.TestResult()
unittest.defaultTestLoader.loadTestsFromTestCase(UsernameTests).run(result)
print("ran:", result.testsRun, "failures:", len(result.failures))
for test, traceback_text in result.failures:
    print("FAILED:", test.id().split(".")[-1])
    print(next(line for line in traceback_text.splitlines() if line.startswith("AssertionError")))
ran: 2 failures: 1
FAILED: test_simple
AssertionError: 'adalovelace' != 'ada.lovelace'

Useful assertions

Assertion Checks
assertEqual(a, b), assertTrue(x), assertIn(a, b) standard unittest checks
assertContains(response, text, status_code=200) status code + text in the body
assertNotContains(response, text) text absent
assertRedirects(response, url) redirect to url (and that page loads)
assertTemplateUsed(response, name) a template was rendered
assertFormError(form, field, errors) a form field has these errors
assertNumQueries(n) a block runs exactly n queries
assertRaises(Exception) code raises

Testing forms and query counts

Forms and query performance are easy to test without any view at all:

python · try it yourself
import unittest, django
from django.conf import settings
settings.configure(DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}})
django.setup()
from django import forms
from django.db import models, connection
from django.test import TestCase

class Tag(models.Model):
    name = models.CharField(max_length=20)
    class Meta:
        app_label = "demo"

with connection.schema_editor() as editor:
    editor.create_model(Tag)

class TagForm(forms.Form):
    name = forms.CharField(max_length=20)
    def clean_name(self):
        return self.cleaned_data["name"].lower()

class TagTests(TestCase):
    def test_form_lowercases(self):
        form = TagForm({"name": "Django"})
        self.assertTrue(form.is_valid())
        self.assertEqual(form.cleaned_data["name"], "django")

    def test_form_rejects_long_names(self):
        form = TagForm({"name": "x" * 21})
        self.assertFormError(form, "name", "Ensure this value has at most 20 characters (it has 21).")

    def test_bulk_create_is_one_query(self):
        with self.assertNumQueries(1):
            Tag.objects.bulk_create([Tag(name=n) for n in "abc"])

result = unittest.TestResult()
unittest.defaultTestLoader.loadTestsFromTestCase(TagTests).run(result)
print(result.testsRun, "tests,", len(result.failures) + len(result.errors), "problems")
for test, text in result.failures + result.errors:
    print(test.id().split(".")[-1], "->", text.strip().splitlines()[-1])
3 tests, 0 problems

Tip: Run tests often (python manage.py test --parallel speeds up big suites) and in CI on every push. Measure which lines your tests cover with coverage run manage.py test and coverage report.

Test yourself

What happens to database changes made inside a django.test.TestCase test?

  1. They are saved permanently
  2. They are rolled back after the test
  3. They are copied to production
  4. They cause an error

Which assertion checks both the status code and that some text appears in a response?

  1. assertEqual
  2. assertContains
  3. assertIn
  4. assertTemplateUsed

Which test class should you use for code that never touches the database?

  1. TestCase
  2. TransactionTestCase
  3. SimpleTestCase
  4. LiveServerTestCase