← Back to Django, page 3

django-0044 · Hard senior

How do you design a reliable test suite for a large Django project? Cover TestCase vs TransactionTestCase, on_commit, override_settings, mocking and factories.

Use TestCase for most tests because each test is rolled back cheaply, and TransactionTestCase only when you need real commits, such as testing database locking or behaviour across connections. Test on_commit callbacks with captureOnCommitCallbacks, change settings with override_settings, mock outside services at the boundary, build data with factories, and guard performance with assertNumQueries. Run tests in parallel on the same database engine as production.

Full answer

A good Django suite is fast, isolated and trusted. Some choices that matter:

Test classes

  • SimpleTestCase: no database. Fast for pure functions, forms without models, template filters.
  • TestCase: wraps each test in a transaction (and the class in another) and rolls back. Fast. Data from setUpTestData is shared and restored per test.
  • TransactionTestCase: truncates tables after each test instead of rolling back. Slower, but needed when code depends on actual commits, multiple connections or threads, or select_for_update behaviour.
  • LiveServerTestCase: starts a real server for browser tests (Playwright, Selenium).

on_commit callbacks never run in TestCase because the transaction never commits. Use:

python
with self.captureOnCommitCallbacks(execute=True) as callbacks:
    enrol_student(...)

Settings and time

  • @override_settings(FEATURE_X=True) or with self.settings(...).
  • Freeze time with time-machine or freezegun for fee due dates and expiry logic.

Outside services

  • Mock at the boundary you own (payments.client.charge), not deep inside libraries. unittest.mock.patch or responses/respx for HTTP.
  • Emails go to django.core.mail.outbox automatically in tests.

Data

  • Factories (factory_boy) build valid objects with sensible defaults, so each test states only what matters. Fixtures in JSON tend to rot as models change.

Speed and trust

  • python manage.py test --parallel or pytest -n auto (pytest-xdist).
  • Run on the same database engine as production; SQLite hides PostgreSQL behaviour (constraints, locking, JSON operators).
  • Use fast password hashers in test settings.
  • Keep a few query-count tests on hot endpoints with assertNumQueries.
  • Test behaviour through public interfaces (views, services), not private helpers.
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 unittest import mock

from django.core import mail
from django.db import connection, models, transaction
from django.test import TestCase, override_settings
from django.test.utils import setup_test_environment

settings.EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"


class Student(models.Model):
    name = models.CharField(max_length=40)
    email = models.EmailField()
    class Meta:
        app_label = "school"


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


class sms:
    @staticmethod
    def send(number, text):
        raise RuntimeError("real SMS gateway must not be called in tests")


def enrol(name, email):
    student = Student.objects.create(name=name, email=email)
    transaction.on_commit(lambda: mail.send_mail("Welcome", f"Hi {name}", "office@example.edu", [email]))
    if settings.SMS_ENABLED:
        sms.send("98xxxxxx00", f"{name} enrolled")
    return student


def make_student(**overrides):
    data = {"name": "Test Student", "email": "test@example.edu"}
    data.update(overrides)
    return Student(**data)


class EnrolTests(TestCase):
    @override_settings(SMS_ENABLED=False)
    def test_email_sent_after_commit(self):
        with self.captureOnCommitCallbacks(execute=True) as callbacks:
            enrol("Gita", "gita@example.edu")
        self.assertEqual(len(callbacks), 1)
        self.assertEqual(mail.outbox[0].to, ["gita@example.edu"])

    @override_settings(SMS_ENABLED=False)
    def test_no_email_without_commit(self):
        enrol("Hari", "hari@example.edu")
        self.assertEqual(len(mail.outbox), 0)

    @override_settings(SMS_ENABLED=True)
    def test_sms_is_mocked(self):
        with mock.patch.object(sms, "send") as fake_send:
            enrol("Ira", "ira@example.edu")
        fake_send.assert_called_once_with("98xxxxxx00", "Ira enrolled")

    def test_factory_defaults(self):
        self.assertEqual(make_student(name="Jay").email, "test@example.edu")


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

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. make_student stands in for a factory_boy factory to keep the example dependency-free. 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 for most tests; TransactionTestCase for real commits
  • captureOnCommitCallbacks runs on_commit callbacks in TestCase
  • override_settings and time freezing for config and dates
  • Mock at your own boundary; factories for data
  • Test on the production database engine and in parallel

Common mistakes

  • Using TransactionTestCase everywhere and making the suite slow
  • Expecting on_commit callbacks to run inside TestCase
  • Mocking deep library internals instead of your own boundary
  • Testing on SQLite while production runs PostgreSQL

Follow-ups

  • How do you test code that uses select_for_update?
  • How would you make a 20-minute test suite run in 5 minutes?
  • What is the difference between a mock and a fake?

Tips

  • Explain why TestCase is fast and when it is not enough
  • Mention captureOnCommitCallbacks by name
  • Talk about suite speed and trust, not only individual tests