Django 6.1.3

13.5 Commands, checks, and testing

Why TestCase is fast and when TransactionTestCase is required

How does TestCase isolate every test method in milliseconds via a rolled-back outer transaction, and why do django.db.transaction.on_commit hooks and multi-thread DB tests behave differently there?

Choosing the wrong base class in django/test/testcases.py is the single biggest reason Django test suites become either painfully slow or mysteriously flaky. Django provides a three-step hierarchy — SimpleTestCase, TransactionTestCase, and TestCase — where the surprising twist is inheritance order: TestCase subclasses TransactionTestCase, overriding its expensive table-flushing teardown with nested database transactions!

How TestCase isolates tests in two transaction layers

Trace the exact lifecycle of TestCase:

  1. Class-level outer transaction via TestCase.setUpClass: Opens an outer atomic block on every database in SimpleTestCase.databases ("cls.cls_atomics = cls._enter_atomics()"), loads class fixtures, and runs TestCase.setUpTestData exactly once for the entire class! Even better, lines 1446–1448 wrap every new attribute attached to cls (such as cls.desk = Desk.objects.get(slug="metro")) in a TestData descriptor that calls copy.deepcopy() when accessed on self — so if "test_a" mutates "self.desk.name = 'Mutated In Test A'" in memory, "test_b" still reads fresh 'Metro'!
  2. Per-test inner savepoint (TestCase._fixture_setup & TestCase._fixture_teardown): Before every test_* method, _fixture_setup calls TestCase._enter_atomics a second time — which, because we are already inside "cls_atomics", creates a cheap SQL "SAVEPOINT" (Chapter 9)! When the test finishes, _fixture_teardown checks deferred constraints and calls TestCase._rollback_atomics(self.atomics) (transaction.set_rollback(True) + ROLLBACK TO SAVEPOINT), erasing every "INSERT", "UPDATE", and "DELETE" from that test in microseconds without touching setUpTestData rows!
  3. Class teardown (TestCase.tearDownClass): Rolls back the outer "cls_atomics" transaction and closes connections, erasing setUpTestData cleanly.

By contrast, TransactionTestCase opens no outer transaction. Every test runs in real autocommit mode, and TransactionTestCase._fixture_teardown executes call_command("flush", ...) — truncating/deleting every table in the database — and closes all connections after every single test method! And SimpleTestCase forbids database access completely (installing _DatabaseFailure guards that raise AssertionError if any code tries to open a cursor).

The on_commit trap — and when you genuinely need TransactionTestCase

That outer uncommitted "cls_atomics" transaction explains the #1 surprise in Django testing: inside TestCase, django.db.transaction.on_commit callbacks NEVER execute automatically! Because the database transaction surrounding your test method is rolled back rather than committed, every callback registered via django.db.transaction.on_commit (such as enqueueing a django.tasks job or sending an email after saving a "Story") sits quietly in "connection.run_on_commit" and gets discarded on teardown!

You have two clean solutions depending on what you are testing:

Watch TestCase verify savepoint depth (1), TestData deepcopy isolation (test_b_desk_name='Metro'), inner rollback (test_b_temp_exists=False), and uncaptured_on_commit_fired=False vs. captured_on_commit_fired=True — followed by our 15-method benchmark proving TestCase is 20.65x faster than TransactionTestCase:

Recorded on Django 6.1.3 ch13-tooling script
5. TestCase savepoints, TestData isolation, and on_commit
  suite_ok=True events=['in_test_a_savepoints=1', 'captured_on_commit_ran', 'captured_count=1', "test_b_desk_name='Metro'", 'test_b_temp_exists=False']
  uncaptured_on_commit_fired=False captured_on_commit_fired=True
Recorded on Django 6.1.3 ch13-bench script
1. Running 15 test methods: SimpleTestCase vs TestCase vs TransactionTestCase (5 trials, ms)
  test_class (15 methods)                   median_ms  speedup
  TransactionTestCase (flush/test)             178.03    1.00x
  TestCase (savepoint rollback)                  8.62   20.65x
  SimpleTestCase (no DB access)                  0.42  429.00x

Database isolation explains how test state stays clean. Next we open the other half of Django’s test toolkit — how Client and RequestFactory run your HTTP views without a socket, and the four subtle ways ClientHandler diverges from production WSGIHandler — in How Client bypasses the socket.