From 6a9db1e626952ffb37633586e6647319ea53467d Mon Sep 17 00:00:00 2001 From: fowczrek Date: Sat, 8 Feb 2025 14:19:58 +0100 Subject: Fixed #34865 -- Released memory earlier than garbage collection on database wrapping layers. Thank you Florian Apolloner, Jake Howard and Patryk Zawadzki for the clarifying comments and reviews. --- tests/backends/base/test_base.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) (limited to 'tests') diff --git a/tests/backends/base/test_base.py b/tests/backends/base/test_base.py index 4418d010ea..8f47e30172 100644 --- a/tests/backends/base/test_base.py +++ b/tests/backends/base/test_base.py @@ -1,3 +1,4 @@ +import gc from unittest.mock import MagicMock, patch from django.db import DEFAULT_DB_ALIAS, connection, connections, transaction @@ -60,6 +61,36 @@ class DatabaseWrapperTests(SimpleTestCase): with patch.object(connection.features, "minimum_database_version", None): connection.check_database_version_supported() + def test_release_memory_without_garbage_collection(self): + # Schedule the restore of the garbage collection settings. + self.addCleanup(gc.set_debug, 0) + self.addCleanup(gc.enable) + + # Disable automatic garbage collection to control when it's triggered, + # then run a full collection cycle to ensure `gc.garbage` is empty. + gc.disable() + gc.collect() + + # The garbage list isn't automatically populated to avoid CPU overhead, + # so debugging needs to be enabled to track all unreachable items and + # have them stored in `gc.garbage`. + gc.set_debug(gc.DEBUG_SAVEALL) + + # Create a new connection that will be closed during the test, and also + # ensure that a `DatabaseErrorWrapper` is created for this connection. + test_connection = connection.copy() + with test_connection.wrap_database_errors: + self.assertEqual(test_connection.queries, []) + + # Close the connection and remove references to it. This will mark all + # objects related to the connection as garbage to be collected. + test_connection.close() + test_connection = None + + # Enforce garbage collection to populate `gc.garbage` for inspection. + gc.collect() + self.assertEqual(gc.garbage, []) + class DatabaseWrapperLoggingTests(TransactionTestCase): available_apps = ["backends"] -- cgit v1.3