From bc6d71d4de8a3f6a430ca084419e079f2e3ecf31 Mon Sep 17 00:00:00 2001 From: David Sanders Date: Fri, 22 Sep 2023 19:21:37 +1000 Subject: [PATCH] [5.0.x] Fixed #34825 -- Avoided setting unused connections when initializing parallel workers. Backport of a5905b164dbf52e59fa646af9c3d523c0804d86a from main --- django/test/runner.py | 7 ++++++- tests/test_runner/tests.py | 3 ++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/django/test/runner.py b/django/test/runner.py index 3a30674b61..eb3cea1959 100644 --- a/django/test/runner.py +++ b/django/test/runner.py @@ -406,6 +406,7 @@ def _init_worker( process_setup=None, process_setup_args=None, debug_mode=None, + used_aliases=None, ): """ Switch to databases dedicated to this worker. @@ -430,7 +431,8 @@ def _init_worker( django.setup() setup_test_environment(debug=debug_mode) - for alias in connections: + db_aliases = used_aliases or connections + for alias in db_aliases: connection = connections[alias] if start_method == "spawn": # Restore initial settings in spawned processes. @@ -491,6 +493,7 @@ class ParallelTestSuite(unittest.TestSuite): self.buffer = buffer self.initial_settings = None self.serialized_contents = None + self.used_aliases = None super().__init__() def run(self, result): @@ -520,6 +523,7 @@ class ParallelTestSuite(unittest.TestSuite): self.process_setup.__func__, self.process_setup_args, self.debug_mode, + self.used_aliases, ], ) args = [ @@ -1052,6 +1056,7 @@ class DiscoverRunner: suite.serialized_aliases = set( alias for alias, serialize in databases.items() if serialize ) + suite.used_aliases = set(databases) with self.time_keeper.timed("Total database setup"): old_config = self.setup_databases( aliases=databases, diff --git a/tests/test_runner/tests.py b/tests/test_runner/tests.py index 25b7f40e99..569fd7e862 100644 --- a/tests/test_runner/tests.py +++ b/tests/test_runner/tests.py @@ -748,8 +748,9 @@ class TestRunnerInitializerTests(SimpleTestCase): # Initializer must be a function. self.assertIs(mocked_pool.call_args.kwargs["initializer"], _init_worker) initargs = mocked_pool.call_args.kwargs["initargs"] - self.assertEqual(len(initargs), 6) + self.assertEqual(len(initargs), 7) self.assertEqual(initargs[5], True) # debug_mode + self.assertEqual(initargs[6], {db.DEFAULT_DB_ALIAS}) # Used database aliases. class Ticket17477RegressionTests(AdminScriptTestCase):