From eb958c52f6cf34184bb590b0e039306c3d9650c5 Mon Sep 17 00:00:00 2001 From: Markus Holtermann Date: Thu, 18 Mar 2021 21:07:17 +0100 Subject: [PATCH] Fixed #25251 -- Restored serialized test data at the end of the test suite This allows subsequent test calls with --keepdb to rely on test data, when it was preserved during database setup. --- django/test/utils.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/django/test/utils.py b/django/test/utils.py index ddb85127dc..2890334eda 100644 --- a/django/test/utils.py +++ b/django/test/utils.py @@ -368,6 +368,29 @@ def teardown_databases(old_config, verbosity, parallel=0, keepdb=False): ) connection.creation.destroy_test_db(old_name, verbosity, keepdb) + # When we keep the database and have serialized content, we need to roll back the data + # at the end of the test suite. When using a parallelized test, the data must be restored + # per clone. + if keepdb and hasattr(connection, "_test_serialized_contents"): + serialized_data = connection._test_serialized_contents + old_settings = dict(connection.settings_dict) + test_database_name = connection.creation._get_test_db_name() + if parallel > 1: + for index in range(parallel): + connection.settings_dict["NAME"] = test_database_name + settings_dict = connection.creation.get_test_db_clone_settings(str(index + 1)) + connection.settings_dict.update(settings_dict) + connection.close() + connection.creation.deserialize_db_from_string(serialized_data) + else: + connection.settings_dict["NAME"] = test_database_name + connection.close() + connection.creation.deserialize_db_from_string(serialized_data) + # Reset the connection settings + connection.settings_dict.update(old_settings) + connection.close() + + def get_runner(settings, test_runner_class=None): test_runner_class = test_runner_class or settings.TEST_RUNNER