From 44e8a274117dec3da25cfade49d8350bab9f6f30 Mon Sep 17 00:00:00 2001 From: Steven Silvester Date: Thu, 4 Jun 2026 06:51:19 -0500 Subject: [PATCH] PYTHON-3011 Fix flaky test_connections_are_only_returned_once on PyPy PyPy's tracing GC does not immediately call __del__ when a cursor goes out of scope, so the pinned connection may not be returned to the pool before the assertion. Add gc.collect() (3 rounds) before each assertEqual, matching the identical pattern already used in _test_no_gc_deadlock and test_session_gc in the same file. --- test/asynchronous/test_load_balancer.py | 9 ++++++--- test/test_load_balancer.py | 9 ++++++--- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/test/asynchronous/test_load_balancer.py b/test/asynchronous/test_load_balancer.py index 8c5d57434c..5b1cf63c1d 100644 --- a/test/asynchronous/test_load_balancer.py +++ b/test/asynchronous/test_load_balancer.py @@ -50,14 +50,17 @@ class TestLB(AsyncIntegrationTest): RUN_ON_LOAD_BALANCER = True async def test_connections_are_only_returned_once(self): - if "PyPy" in sys.version: - # Tracked in PYTHON-3011 - self.skipTest("Test is flaky on PyPy") pool = await async_get_pool(self.client) n_conns = len(pool.conns) await self.db.test.find_one({}) + # On PyPy it can take a few rounds to collect the cursor. + for _ in range(3): + gc.collect() self.assertEqual(len(pool.conns), n_conns) await (await self.db.test.aggregate([{"$limit": 1}])).to_list() + # On PyPy it can take a few rounds to collect the cursor. + for _ in range(3): + gc.collect() self.assertEqual(len(pool.conns), n_conns) @async_client_context.require_load_balancer diff --git a/test/test_load_balancer.py b/test/test_load_balancer.py index de4b14e546..a4e09fce68 100644 --- a/test/test_load_balancer.py +++ b/test/test_load_balancer.py @@ -50,14 +50,17 @@ class TestLB(IntegrationTest): RUN_ON_LOAD_BALANCER = True def test_connections_are_only_returned_once(self): - if "PyPy" in sys.version: - # Tracked in PYTHON-3011 - self.skipTest("Test is flaky on PyPy") pool = get_pool(self.client) n_conns = len(pool.conns) self.db.test.find_one({}) + # On PyPy it can take a few rounds to collect the cursor. + for _ in range(3): + gc.collect() self.assertEqual(len(pool.conns), n_conns) (self.db.test.aggregate([{"$limit": 1}])).to_list() + # On PyPy it can take a few rounds to collect the cursor. + for _ in range(3): + gc.collect() self.assertEqual(len(pool.conns), n_conns) @client_context.require_load_balancer