diff options
| author | Mariusz Felisiak <felisiak.mariusz@gmail.com> | 2024-02-19 14:08:30 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-02-19 14:08:30 +0100 |
| commit | 9350308f374cad475312de3e648249d8b6f17341 (patch) | |
| tree | 5573d05e4fba5c77ff942b18d3e7aa3cf4d1d62a /tests/test_utils | |
| parent | f65f8ab84ebd2fc9772d23a159e6178e1335bd8b (diff) | |
Fixed closing connections in test_utils.tests.AllowedDatabaseQueriesTests.
Diffstat (limited to 'tests/test_utils')
| -rw-r--r-- | tests/test_utils/tests.py | 28 |
1 files changed, 25 insertions, 3 deletions
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): |
