diff --git a/tests/test_utils/tests.py b/tests/test_utils/tests.py index 23e430cdc6..7e9505f762 100644 --- a/tests/test_utils/tests.py +++ b/tests/test_utils/tests.py @@ -2132,12 +2132,34 @@ class AllowedDatabaseQueriesTests(SimpleTestCase): next(Car.objects.iterator(), None) def test_allowed_threaded_database_queries(self): + connections_dict = {} + def thread_func(): + # Passing django.db.connection between threads doesn't work while + # connections[DEFAULT_DB_ALIAS] does. + from django.db import connections + + connection = connections["default"] + next(Car.objects.iterator(), None) - t = threading.Thread(target=thread_func) - t.start() - t.join() + # Allow thread sharing so the connection can be closed by the main + # thread. + connection.inc_thread_sharing() + connections_dict[id(connection)] = connection + + try: + t = threading.Thread(target=thread_func) + t.start() + t.join() + finally: + # Finish by closing the connections opened by the other threads + # (the connection opened in the main thread will automatically be + # closed on teardown). + for conn in connections_dict.values(): + if conn is not connection and conn.allow_thread_sharing: + conn.close() + conn.dec_thread_sharing() class DatabaseAliasTests(SimpleTestCase):