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 hooks and multi-thread DB tests behave differently there?
Choosing the wrong base class in django/ 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:
- Class-level outer transaction via
TestCase: Opens an outer atomic block on every database in.setUpClass SimpleTestCase(.databases "cls), loads class.cls_atomics = cls ._enter_atomics()" fixtures, and runsTestCaseexactly once for the entire class! Even better, lines 1446–1448 wrap every new attribute attached to.setUpTestData cls(such ascls) in a.desk = Desk .objects .get(slug="metro") TestDatadescriptor that callscopy.deepcopy()when accessed onself— so if"test_a"mutates"selfin memory,.desk .name = 'Mutated In Test A'" "test_b"still reads fresh'Metro'! - Per-test inner savepoint (
TestCase&._fixture_setup TestCase): Before every._fixture_teardown test_*method,_fixture_setupcallsTestCasea second time — which, because we are already inside._enter_atomics "cls_atomics", creates a cheap SQL"SAVEPOINT"(Chapter 9)! When the test finishes,_fixture_teardownchecks deferred constraints and callsTestCase(._rollback_atomics(self .atomics) transaction+.set_rollback(True) ROLLBACK TO SAVEPOINT), erasing every"INSERT","UPDATE", and"DELETE"from that test in microseconds without touchingsetUpTestDatarows! - Class teardown (
TestCase): Rolls back the outer.tearDownClass "cls_atomics"transaction and closes connections, erasingsetUpTestDatacleanly.
By contrast, TransactionTestCase opens no outer transaction. Every test runs in real autocommit mode, and TransactionTestCase 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 callbacks NEVER execute automatically! Because the database transaction surrounding your test method is rolled back rather than committed, every callback registered via django (such as enqueueing a django.tasks job or sending an email after saving a "Story") sits quietly in "connection and gets discarded on teardown!
You have two clean solutions depending on what you are testing:
- Keep
TestCasespeed withTestCase: Wrapping the action in.captureOnCommitCallbacks "with selfcaptures every callback scheduled inside the block and executes them immediately on block exit (without breaking savepoint isolation!)..captureOnCommitCallbacks(execute=True) as callbacks: " - Switch to
TransactionTestCaseONLY when testing real transaction boundaries: UseTransactionTestCasewhen verifying real"COMMIT"visibility across two threads or processes (such asLiveServerTestCaseserving a real browser!), testingselect_for_updaterow locks between two connections, or verifying database-levelon_commitbehavior across real commits and rollbacks.
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:
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
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.