---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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`** (`django/test/testcases.py:SimpleTestCase`), **`TransactionTestCase`** (`django/test/testcases.py:TransactionTestCase`), and **`TestCase`** (`django/test/testcases.py: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`** (`django/test/testcases.py:TestCase`):

1. **Class-level outer transaction via `TestCase.setUpClass` (`django/test/testcases.py: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`** (`django/test/testcases.py: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` (`django/test/testcases.py: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`** (`django/test/testcases.py:TransactionTestCase`) opens **no** outer transaction. Every test runs in real autocommit mode, and `TransactionTestCase._fixture_teardown` (`django/test/testcases.py: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:

- **Keep `TestCase` speed with `TestCase.captureOnCommitCallbacks` (`django/test/testcases.py:TestCase.captureOnCommitCallbacks`):** Wrapping the action in `"with self.captureOnCommitCallbacks(execute=True) as callbacks:"` captures every callback scheduled inside the block and executes them immediately on block exit (without breaking savepoint isolation!).
- **Switch to `TransactionTestCase` ONLY when testing real transaction boundaries:** Use `TransactionTestCase` when verifying real `"COMMIT"` visibility across two threads or processes (such as `LiveServerTestCase` serving a real browser!), testing `select_for_update` row locks between two connections, or verifying database-level `on_commit` behavior 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`:

```text recording=ch13-tooling
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
```

```text recording=ch13-bench
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](test-client.md).
