← Back to Django, page 1

django-0017 · Easy fresher

How do you write tests in Django using TestCase and the test Client?

Subclass django.test.TestCase, put setup data in setUpTestData or setUp, and write test_ methods with assertions. Each test runs inside a transaction that is rolled back, so tests do not affect each other. self.client sends fake requests through URLs, middleware and views, and helpers like assertContains, assertRedirects and assertNumQueries check the result. Run with python manage.py test.

Full answer

Django's test tools build on Python's unittest.

django.test.TestCase:

  • Creates a separate test database (named test_<name>) before the run and destroys it after.
  • Wraps each test method in a transaction and rolls it back, so data created in one test never leaks into the next. This is fast.
  • setUpTestData(cls) runs once per class for shared read-only data; setUp(self) runs before every test.

The test Client (self.client) acts like a browser without a server:

  • self.client.get("/books/"), self.client.post(url, data).
  • self.client.force_login(user) skips the login form.
  • The response has status_code, content, context (template context) and templates.

Helpful assertions:

  • assertContains(response, "Wings of Fire"), assertNotContains
  • assertRedirects(response, "/login/?next=/books/")
  • assertTemplateUsed(response, "books/list.html")
  • assertNumQueries(2) as a context manager, to catch N+1 problems early
  • assertFormError for form errors

Other tools: RequestFactory builds requests for calling a view function directly (no middleware), SimpleTestCase for tests that need no database, TransactionTestCase when code depends on real commits (for example on_commit hooks).

Run with python manage.py test or with pytest plus pytest-django. A healthy test checks one behaviour, sets up only the data it needs and reads clearly as "given, when, then".

python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

import unittest
from django.db import models, connection
from django.http import HttpResponse
from django.test import TestCase
from django.test.utils import setup_test_environment
from django.urls import path


class Book(models.Model):
    title = models.CharField(max_length=60)
    class Meta:
        app_label = "school"


def book_list(request):
    titles = ", ".join(Book.objects.order_by("title").values_list("title", flat=True))
    return HttpResponse(titles or "No books")


urlpatterns = [path("books/", book_list)]
settings.ROOT_URLCONF = __name__

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


class BookListTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        Book.objects.create(title="Wings of Fire")

    def test_lists_titles(self):
        response = self.client.get("/books/")
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "Wings of Fire")

    def test_one_query(self):
        with self.assertNumQueries(1):
            self.client.get("/books/")

    def test_data_is_rolled_back(self):
        Book.objects.create(title="Gitanjali")
        self.assertEqual(Book.objects.count(), 2)

    def test_count_is_back_to_one(self):
        self.assertEqual(Book.objects.count(), 1)


setup_test_environment()
suite = unittest.defaultTestLoader.loadTestsFromTestCase(BookListTests)
result = unittest.TextTestRunner(verbosity=0, stream=open("/dev/null", "w")).run(suite)
print("ran:", result.testsRun, "failures:", len(result.failures), "errors:", len(result.errors))

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Normally you run tests with `python manage.py test`; this script runs the TestCase through unittest directly. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): ran: 4 failures: 0 errors: 0

Key points

  • TestCase wraps each test in a rolled-back transaction
  • setUpTestData for shared data, setUp per test
  • self.client runs URLs, middleware and views
  • assertNumQueries catches N+1 regressions
  • RequestFactory calls a view without middleware

Common mistakes

  • Using unittest.TestCase so the database is not reset between tests
  • Creating heavy data in setUp when setUpTestData would run it once
  • Testing on_commit callbacks inside TestCase without captureOnCommitCallbacks
  • Asserting only status codes and not the content

Follow-ups

  • When do you need TransactionTestCase?
  • How do you test a view that requires login?
  • How would you test that an email was sent?

Tips

  • Explain the rollback behaviour, it is the key idea
  • Mention assertNumQueries as a performance guard
  • Know both manage.py test and pytest-django