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

# Creating, cloning, and tearing down test databases

How does `DiscoverRunner` spin up isolated test databases, serialize initial state, and clone databases across `--parallel` workers?

Typing `"python manage.py test"` invokes Django's test runner — **`DiscoverRunner`** (`django/test/runner.py:DiscoverRunner`). Before a single `test_*` method executes, `DiscoverRunner.run_tests` (`django/test/runner.py:DiscoverRunner.run_tests`) orchestrates environment patching, database discovery, schema migration, optional JSON state serialization, parallel database cloning, and system checks.

## Skipping unused databases and `BaseDatabaseCreation.create_test_db`

Open `DiscoverRunner.run_tests` and `DiscoverRunner._get_databases` (`django/test/runner.py:DiscoverRunner._get_databases`):

1. **`setup_test_environment()`:** Switches `"EMAIL_BACKEND"` to in-memory `django.core.mail.backends.locmem.EmailBackend` (populating `"mail.outbox"`), forces `DEBUG = False`, installs template instrumentation (`instrumented_test_render`) so `Client` can record rendered templates and contexts, and disables `ALLOWED_HOSTS` errors for `"testserver"`.
2. **Smart database discovery (`_get_databases`):** Before touching any database, `DiscoverRunner` walks every test case in the discovered `unittest.TestSuite` inspecting two class attributes: `"databases"` (empty `{}` on `SimpleTestCase`, `{"default"}` on `TestCase` and `TransactionTestCase`) and `"serialized_rollback"`. If your test run contains only `SimpleTestCase` classes, **`DiscoverRunner` creates ZERO test databases!**
3. **Creating & migrating (`BaseDatabaseCreation.create_test_db`, `django/db/backends/base/creation.py:BaseDatabaseCreation.create_test_db`):** For every needed non-mirror alias, Django computes the isolated database name (`"test_<NAME>"` on PostgreSQL/MySQL, or `":memory:"` / shared-cache `"file:memorydb_default?mode=memory&cache=shared"` on SQLite), creates the empty DB (or reuses it under `"--keepdb"`), rewrites `"settings.DATABASES[alias]['NAME']"` in place, and runs `call_command("migrate", verbosity=..., interactive=False, run_syncdb=True)` (skipping migration files only if `"TEST['MIGRATE'] = False"`). Notice `DiscoverRunner.run_checks(databases)` runs *after* test DB creation so `Tags.database` checks can validate the migrated schema!

## `serialize_db_to_string` and `--parallel` cloning via `clone_test_db`

Two subtle mechanisms keep multi-test and multi-core runs both accurate and fast:

- **Initial data serialization via `BaseDatabaseCreation.serialize_db_to_string` (`django/db/backends/base/creation.py:BaseDatabaseCreation.serialize_db_to_string`):** Migrations often insert reference rows (such as `"django_content_type"`, `"auth_permission"`, or custom data migrations). Because `TransactionTestCase` runs `flush` after every test (wiping all tables!), any test class with `"serialized_rollback = True"` tells `DiscoverRunner` to snapshot the post-migration database into a JSON string on `"connection._test_serialized_contents"` once at startup (note that Django `6.1` deprecates passing `serialize=True` directly to `create_test_db`, emitting `RemovedInDjango2028Warning` so serialization runs once all test databases are set up!) and reload it via `BaseDatabaseCreation.deserialize_db_from_string` after every flush!
- **Parallel worker cloning via `BaseDatabaseCreation.clone_test_db` (`django/db/backends/base/creation.py:BaseDatabaseCreation.clone_test_db`):** Running `"manage.py test --parallel 4"` does **not** run your 200 migrations four times! Instead, the parent process creates and migrates **one** primary test database and then calls `clone_test_db(suffix=str(worker_id))` to duplicate it cleanly per worker (using PostgreSQL's fast `"CREATE DATABASE test_db_1 WITH TEMPLATE test_db"`, SQLite's native `sqlite3.Connection.backup` API, or file copy), letting `N` worker processes execute test classes concurrently with zero lock contention!

Watch `DiscoverRunner._get_databases` distinguish `SimpleTestCase`, `TestCase`, and `serialized_rollback=True` `TransactionTestCase` — and watch `serialize_db_to_string()` snapshot `"desk/"`'s migrated database (`15,830` JSON chars) live:

```text recording=ch13-tooling
4. DiscoverRunner database discovery and test DB serialization
  runner_databases: SimpleTestCase={} TestCase={'default': False} serialized_TransactionTestCase={'default': True}
  serialize_db_to_string: json_chars=15830 contains_story_model=True
```

Now that the test database is migrated and ready, why can `TestCase` execute 15 database-writing tests in `8.62 ms` while `TransactionTestCase` takes `178.03 ms` — and why does `django.db.transaction.on_commit` behave completely differently inside `TestCase`? We open the exact transaction layers next in [Why TestCase is fast and when TransactionTestCase is required](testcase-rollbacks.md).
