Skip to content

Commit 18fb1ca

Browse files
committed
PYTHON-4784 - Add tests to confirm async parallelism
1 parent 49e656c commit 18fb1ca

File tree

2 files changed

+55
-1
lines changed

2 files changed

+55
-1
lines changed

test/asynchronous/test_concurrency.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Copyright 2024-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+
"""Tests to ensure that the async API is properly concurrent with asyncio."""
16+
from __future__ import annotations
17+
18+
import asyncio
19+
import time
20+
from test.asynchronous import AsyncIntegrationTest
21+
from test.utils import delay
22+
23+
_IS_SYNC = False
24+
25+
26+
class TestAsyncConcurrency(AsyncIntegrationTest):
27+
async def _task(self, client):
28+
await client.db.test.find_one({"$where": delay(1)})
29+
30+
async def test_concurrency(self):
31+
tasks = []
32+
iterations = 5
33+
34+
client = self.simple_client()
35+
await client.db.test.drop()
36+
await client.db.test.insert_one({"x": 1})
37+
38+
start = time.time()
39+
40+
for _ in range(iterations):
41+
await self._task(client)
42+
43+
sequential_time = time.time() - start
44+
start = time.time()
45+
46+
for i in range(iterations):
47+
tasks.append(self._task(client))
48+
49+
await asyncio.gather(*tasks)
50+
concurrent_time = time.time() - start
51+
52+
percent_faster = (sequential_time - concurrent_time) / concurrent_time * 100
53+
# We expect the concurrent tasks to be at least 50% faster
54+
self.assertGreaterEqual(percent_faster, 50)

tools/synchro.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@
148148

149149
def async_only_test(f: str) -> bool:
150150
"""Return True for async tests that should not be converted to sync."""
151-
return f in ["test_locks.py"]
151+
return f in ["test_locks.py", "test_concurrency.py"]
152152

153153

154154
test_files = [

0 commit comments

Comments
 (0)