Skip to content

Commit 3dd44e6

Browse files
authored
PYTHON-5087 - Convert test.test_load_balancer to async (#2103)
1 parent 1b81847 commit 3dd44e6

File tree

9 files changed

+331
-80
lines changed

9 files changed

+331
-80
lines changed

test/asynchronous/helpers.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040
except ImportError:
4141
HAVE_IPADDRESS = False
4242
from functools import wraps
43-
from typing import Any, Callable, Dict, Generator, no_type_check
43+
from typing import Any, Callable, Dict, Generator, Optional, no_type_check
4444
from unittest import SkipTest
4545

4646
from bson.son import SON
@@ -395,7 +395,7 @@ def __init__(self, **kwargs):
395395
async def start(self):
396396
self.task = create_task(self.run(), name=self.name)
397397

398-
async def join(self, timeout: float | None = 0): # type: ignore[override]
398+
async def join(self, timeout: Optional[float] = None): # type: ignore[override]
399399
if self.task is not None:
400400
await asyncio.wait([self.task], timeout=timeout)
401401

@@ -407,3 +407,18 @@ async def run(self):
407407
await self.target(*self.args)
408408
finally:
409409
self.stopped = True
410+
411+
412+
class ExceptionCatchingTask(ConcurrentRunner):
413+
"""A Task that stores any exception encountered while running."""
414+
415+
def __init__(self, **kwargs):
416+
super().__init__(**kwargs)
417+
self.exc = None
418+
419+
async def run(self):
420+
try:
421+
await super().run()
422+
except BaseException as exc:
423+
self.exc = exc
424+
raise
Lines changed: 199 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,199 @@
1+
# Copyright 2021-present MongoDB, Inc.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""Test the Load Balancer unified spec tests."""
16+
from __future__ import annotations
17+
18+
import asyncio
19+
import gc
20+
import os
21+
import pathlib
22+
import sys
23+
import threading
24+
from asyncio import Event
25+
from test.asynchronous.helpers import ConcurrentRunner, ExceptionCatchingTask
26+
27+
import pytest
28+
29+
sys.path[0:0] = [""]
30+
31+
from test.asynchronous import AsyncIntegrationTest, async_client_context, unittest
32+
from test.asynchronous.unified_format import generate_test_classes
33+
from test.utils import (
34+
async_get_pool,
35+
async_wait_until,
36+
create_async_event,
37+
)
38+
39+
from pymongo.asynchronous.helpers import anext
40+
41+
_IS_SYNC = False
42+
43+
pytestmark = pytest.mark.load_balancer
44+
45+
# Location of JSON test specifications.
46+
if _IS_SYNC:
47+
_TEST_PATH = os.path.join(pathlib.Path(__file__).resolve().parent, "load_balancer")
48+
else:
49+
_TEST_PATH = os.path.join(pathlib.Path(__file__).resolve().parent.parent, "load_balancer")
50+
51+
# Generate unified tests.
52+
globals().update(generate_test_classes(_TEST_PATH, module=__name__))
53+
54+
55+
class TestLB(AsyncIntegrationTest):
56+
RUN_ON_LOAD_BALANCER = True
57+
RUN_ON_SERVERLESS = True
58+
59+
async def test_connections_are_only_returned_once(self):
60+
if "PyPy" in sys.version:
61+
# Tracked in PYTHON-3011
62+
self.skipTest("Test is flaky on PyPy")
63+
pool = await async_get_pool(self.client)
64+
n_conns = len(pool.conns)
65+
await self.db.test.find_one({})
66+
self.assertEqual(len(pool.conns), n_conns)
67+
await (await self.db.test.aggregate([{"$limit": 1}])).to_list()
68+
self.assertEqual(len(pool.conns), n_conns)
69+
70+
@async_client_context.require_load_balancer
71+
async def test_unpin_committed_transaction(self):
72+
client = await self.async_rs_client()
73+
pool = await async_get_pool(client)
74+
coll = client[self.db.name].test
75+
async with client.start_session() as session:
76+
async with await session.start_transaction():
77+
self.assertEqual(pool.active_sockets, 0)
78+
await coll.insert_one({}, session=session)
79+
self.assertEqual(pool.active_sockets, 1) # Pinned.
80+
self.assertEqual(pool.active_sockets, 1) # Still pinned.
81+
self.assertEqual(pool.active_sockets, 0) # Unpinned.
82+
83+
@async_client_context.require_failCommand_fail_point
84+
async def test_cursor_gc(self):
85+
async def create_resource(coll):
86+
cursor = coll.find({}, batch_size=3)
87+
await anext(cursor)
88+
return cursor
89+
90+
await self._test_no_gc_deadlock(create_resource)
91+
92+
@async_client_context.require_failCommand_fail_point
93+
async def test_command_cursor_gc(self):
94+
async def create_resource(coll):
95+
cursor = await coll.aggregate([], batchSize=3)
96+
await anext(cursor)
97+
return cursor
98+
99+
await self._test_no_gc_deadlock(create_resource)
100+
101+
async def _test_no_gc_deadlock(self, create_resource):
102+
client = await self.async_rs_client()
103+
pool = await async_get_pool(client)
104+
coll = client[self.db.name].test
105+
await coll.insert_many([{} for _ in range(10)])
106+
self.assertEqual(pool.active_sockets, 0)
107+
# Cause the initial find attempt to fail to induce a reference cycle.
108+
args = {
109+
"mode": {"times": 1},
110+
"data": {
111+
"failCommands": ["find", "aggregate"],
112+
"closeConnection": True,
113+
},
114+
}
115+
async with self.fail_point(args):
116+
resource = await create_resource(coll)
117+
if async_client_context.load_balancer:
118+
self.assertEqual(pool.active_sockets, 1) # Pinned.
119+
120+
task = PoolLocker(pool)
121+
await task.start()
122+
self.assertTrue(await task.wait(task.locked, 5), "timed out")
123+
# Garbage collect the resource while the pool is locked to ensure we
124+
# don't deadlock.
125+
del resource
126+
# On PyPy it can take a few rounds to collect the cursor.
127+
for _ in range(3):
128+
gc.collect()
129+
task.unlock.set()
130+
await task.join(5)
131+
self.assertFalse(task.is_alive())
132+
self.assertIsNone(task.exc)
133+
134+
await async_wait_until(lambda: pool.active_sockets == 0, "return socket")
135+
# Run another operation to ensure the socket still works.
136+
await coll.delete_many({})
137+
138+
@async_client_context.require_transactions
139+
async def test_session_gc(self):
140+
client = await self.async_rs_client()
141+
pool = await async_get_pool(client)
142+
session = client.start_session()
143+
await session.start_transaction()
144+
await client.test_session_gc.test.find_one({}, session=session)
145+
# Cleanup the transaction left open on the server unless we're
146+
# testing serverless which does not support killSessions.
147+
if not async_client_context.serverless:
148+
self.addAsyncCleanup(self.client.admin.command, "killSessions", [session.session_id])
149+
if async_client_context.load_balancer:
150+
self.assertEqual(pool.active_sockets, 1) # Pinned.
151+
152+
task = PoolLocker(pool)
153+
await task.start()
154+
self.assertTrue(await task.wait(task.locked, 5), "timed out")
155+
# Garbage collect the session while the pool is locked to ensure we
156+
# don't deadlock.
157+
del session
158+
# On PyPy it can take a few rounds to collect the session.
159+
for _ in range(3):
160+
gc.collect()
161+
task.unlock.set()
162+
await task.join(5)
163+
self.assertFalse(task.is_alive())
164+
self.assertIsNone(task.exc)
165+
166+
await async_wait_until(lambda: pool.active_sockets == 0, "return socket")
167+
# Run another operation to ensure the socket still works.
168+
await client[self.db.name].test.delete_many({})
169+
170+
171+
class PoolLocker(ExceptionCatchingTask):
172+
def __init__(self, pool):
173+
super().__init__(target=self.lock_pool)
174+
self.pool = pool
175+
self.daemon = True
176+
self.locked = create_async_event()
177+
self.unlock = create_async_event()
178+
179+
async def lock_pool(self):
180+
async with self.pool.lock:
181+
self.locked.set()
182+
# Wait for the unlock flag.
183+
unlock_pool = await self.wait(self.unlock, 10)
184+
if not unlock_pool:
185+
raise Exception("timed out waiting for unlock signal: deadlock?")
186+
187+
async def wait(self, event: Event, timeout: int):
188+
if _IS_SYNC:
189+
return event.wait(timeout) # type: ignore[call-arg]
190+
else:
191+
try:
192+
await asyncio.wait_for(event.wait(), timeout=timeout)
193+
except asyncio.TimeoutError:
194+
return False
195+
return True
196+
197+
198+
if __name__ == "__main__":
199+
unittest.main()

test/asynchronous/test_session.py

Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,13 @@
1515
"""Test the client_session module."""
1616
from __future__ import annotations
1717

18+
import asyncio
1819
import copy
1920
import sys
2021
import time
22+
from asyncio import iscoroutinefunction
2123
from io import BytesIO
24+
from test.asynchronous.helpers import ExceptionCatchingTask
2225
from typing import Any, Callable, List, Set, Tuple
2326

2427
from pymongo.synchronous.mongo_client import MongoClient
@@ -35,7 +38,6 @@
3538
)
3639
from test.utils import (
3740
EventListener,
38-
ExceptionCatchingThread,
3941
OvertCommandListener,
4042
async_wait_until,
4143
)
@@ -184,16 +186,15 @@ async def _test_ops(self, client, *ops):
184186
f"{f.__name__} did not return implicit session to pool",
185187
)
186188

187-
@async_client_context.require_sync
188-
def test_implicit_sessions_checkout(self):
189+
async def test_implicit_sessions_checkout(self):
189190
# "To confirm that implicit sessions only allocate their server session after a
190191
# successful connection checkout" test from Driver Sessions Spec.
191192
succeeded = False
192193
lsid_set = set()
193194
failures = 0
194195
for _ in range(5):
195196
listener = OvertCommandListener()
196-
client = self.async_rs_or_single_client(event_listeners=[listener], maxPoolSize=1)
197+
client = await self.async_rs_or_single_client(event_listeners=[listener], maxPoolSize=1)
197198
cursor = client.db.test.find({})
198199
ops: List[Tuple[Callable, List[Any]]] = [
199200
(client.db.test.find_one, [{"_id": 1}]),
@@ -210,26 +211,27 @@ def test_implicit_sessions_checkout(self):
210211
(cursor.distinct, ["_id"]),
211212
(client.db.list_collections, []),
212213
]
213-
threads = []
214+
tasks = []
214215
listener.reset()
215216

216-
def thread_target(op, *args):
217-
res = op(*args)
217+
async def target(op, *args):
218+
if iscoroutinefunction(op):
219+
res = await op(*args)
220+
else:
221+
res = op(*args)
218222
if isinstance(res, (AsyncCursor, AsyncCommandCursor)):
219-
list(res) # type: ignore[call-overload]
223+
await res.to_list()
220224

221225
for op, args in ops:
222-
threads.append(
223-
ExceptionCatchingThread(
224-
target=thread_target, args=[op, *args], name=op.__name__
225-
)
226+
tasks.append(
227+
ExceptionCatchingTask(target=target, args=[op, *args], name=op.__name__)
226228
)
227-
threads[-1].start()
228-
self.assertEqual(len(threads), len(ops))
229-
for thread in threads:
230-
thread.join()
231-
self.assertIsNone(thread.exc)
232-
client.close()
229+
await tasks[-1].start()
230+
self.assertEqual(len(tasks), len(ops))
231+
for t in tasks:
232+
await t.join()
233+
self.assertIsNone(t.exc)
234+
await client.close()
233235
lsid_set.clear()
234236
for i in listener.started_events:
235237
if i.command.get("lsid"):

test/helpers.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040
except ImportError:
4141
HAVE_IPADDRESS = False
4242
from functools import wraps
43-
from typing import Any, Callable, Dict, Generator, no_type_check
43+
from typing import Any, Callable, Dict, Generator, Optional, no_type_check
4444
from unittest import SkipTest
4545

4646
from bson.son import SON
@@ -395,7 +395,7 @@ def __init__(self, **kwargs):
395395
def start(self):
396396
self.task = create_task(self.run(), name=self.name)
397397

398-
def join(self, timeout: float | None = 0): # type: ignore[override]
398+
def join(self, timeout: Optional[float] = None): # type: ignore[override]
399399
if self.task is not None:
400400
asyncio.wait([self.task], timeout=timeout)
401401

@@ -407,3 +407,18 @@ def run(self):
407407
self.target(*self.args)
408408
finally:
409409
self.stopped = True
410+
411+
412+
class ExceptionCatchingTask(ConcurrentRunner):
413+
"""A Task that stores any exception encountered while running."""
414+
415+
def __init__(self, **kwargs):
416+
super().__init__(**kwargs)
417+
self.exc = None
418+
419+
def run(self):
420+
try:
421+
super().run()
422+
except BaseException as exc:
423+
self.exc = exc
424+
raise

test/test_bson.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
sys.path[0:0] = [""]
3434

3535
from test import qcheck, unittest
36-
from test.utils import ExceptionCatchingThread
36+
from test.helpers import ExceptionCatchingTask
3737

3838
import bson
3939
from bson import (
@@ -1075,7 +1075,7 @@ def target(i):
10751075
my_int = type(f"MyInt_{i}_{j}", (int,), {})
10761076
bson.encode({"my_int": my_int()})
10771077

1078-
threads = [ExceptionCatchingThread(target=target, args=(i,)) for i in range(3)]
1078+
threads = [ExceptionCatchingTask(target=target, args=(i,)) for i in range(3)]
10791079
for t in threads:
10801080
t.start()
10811081

@@ -1114,7 +1114,7 @@ def __repr__(self):
11141114

11151115
def test_doc_in_invalid_document_error_message_mapping(self):
11161116
class MyMapping(abc.Mapping):
1117-
def keys():
1117+
def keys(self):
11181118
return ["t"]
11191119

11201120
def __getitem__(self, name):

0 commit comments

Comments
 (0)