13.4 Commands, checks, and testing
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 invokes Django’s test runner — DiscoverRunner. Before a single test_* method executes, DiscoverRunner 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 and DiscoverRunner:
setup_test_environment(): Switches"EMAIL_BACKEND"to in-memorydjango(populating.core .mail .backends .locmem .EmailBackend "mail.outbox"), forcesDEBUG = False, installs template instrumentation (instrumented_test_render) soClientcan record rendered templates and contexts, and disablesALLOWED_HOSTSerrors for"testserver".- Smart database discovery (
_get_databases): Before touching any database,DiscoverRunnerwalks every test case in the discoveredunittestinspecting two class attributes:.TestSuite "databases"(empty{}onSimpleTestCase,{"default"}onTestCaseandTransactionTestCase) and"serialized_rollback". If your test run contains onlySimpleTestCaseclasses,DiscoverRunnercreates ZERO test databases! - Creating & migrating (
BaseDatabaseCreation,.create_test_db BaseDatabaseCreation): For every needed non-mirror alias, Django computes the isolated database name (.create_test_db "test_<NAME>"on PostgreSQL/MySQL, or":memory:"/ shared-cache"file:on SQLite), creates the empty DB (or reuses it undermemorydb_default?mode=memory&cache=shared" "--keepdb"), rewrites"settingsin place, and runs.DATABASES[alias]['NAME']" call_command("migrate", verbosity=..., interactive=False, run_syncdb=True)(skipping migration files only if"TEST['MIGRATE'] = False"). NoticeDiscoverRunnerruns after test DB creation so.run_checks(databases) Tags.databasechecks 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: Migrations often insert reference rows (such as.serialize_db_to_string "django_content_type","auth_permission", or custom data migrations). BecauseTransactionTestCaserunsflushafter every test (wiping all tables!), any test class with"serialized_rollback = True"tellsDiscoverRunnerto snapshot the post-migration database into a JSON string on"connectiononce at startup (note that Django._test_serialized_contents" 6.1deprecates passingserialize=Truedirectly tocreate_test_db, emittingRemovedInDjango2028Warningso serialization runs once all test databases are set up!) and reload it viaBaseDatabaseCreationafter every flush!.deserialize_db_from_string - Parallel worker cloning via
BaseDatabaseCreation: Running.clone_test_db "managedoes not run your 200 migrations four times! Instead, the parent process creates and migrates one primary test database and then calls.py test --parallel 4" 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 nativesqlite3API, or file copy), letting.Connection .backup Nworker processes execute test classes concurrently with zero lock contention!
Watch DiscoverRunner distinguish SimpleTestCase, TestCase, and serialized_rollback=True TransactionTestCase — and watch serialize_db_to_string() snapshot "desk/"'s migrated database (15,830 JSON chars) live:
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 behave completely differently inside TestCase? We open the exact transaction layers next in Why TestCase is fast and when TransactionTestCase is required.