|
| 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) |
0 commit comments