|
17 | 17 |
|
18 | 18 | import asyncio
|
19 | 19 | import sys
|
20 |
| -from test.utils import async_get_pool, get_pool, one |
| 20 | +import traceback |
| 21 | + |
| 22 | +from test.utils import async_get_pool, get_pool, one, delay |
21 | 23 |
|
22 | 24 | sys.path[0:0] = [""]
|
23 | 25 |
|
24 |
| -from test.asynchronous import AsyncIntegrationTest, connected |
| 26 | +from test.asynchronous import AsyncIntegrationTest, connected, async_client_context |
25 | 27 |
|
26 | 28 |
|
27 | 29 | class TestAsyncCancellation(AsyncIntegrationTest):
|
28 |
| - async def test_async_cancellation_does_not_close_connection(self): |
29 |
| - client = await self.async_rs_or_single_client(maxPoolSize=1, retryReads=False) |
| 30 | + async def test_async_cancellation_closes_connection(self): |
| 31 | + client = await self.async_rs_or_single_client() |
30 | 32 | pool = await async_get_pool(client)
|
31 | 33 | await connected(client)
|
32 | 34 | conn = one(pool.conns)
|
33 | 35 |
|
34 | 36 | async def task():
|
35 |
| - while True: |
36 |
| - await client.db.test.insert_one({"x": 1}) |
37 |
| - await asyncio.sleep(0.005) |
| 37 | + await client.db.test.find_one({"$where": delay(1.0)}) |
| 38 | + |
| 39 | + task = asyncio.create_task(task()) |
| 40 | + |
| 41 | + await asyncio.sleep(0.1) |
| 42 | + |
| 43 | + task.cancel() |
| 44 | + with self.assertRaises(asyncio.CancelledError): |
| 45 | + await task |
| 46 | + |
| 47 | + self.assertTrue(conn.closed) |
| 48 | + |
| 49 | + @async_client_context.require_transactions |
| 50 | + async def test_async_cancellation_aborts_transaction(self): |
| 51 | + client = await self.async_rs_or_single_client() |
| 52 | + await connected(client) |
| 53 | + |
| 54 | + session = client.start_session() |
| 55 | + |
| 56 | + async def callback(session): |
| 57 | + await client.db.test.find_one({"$where": delay(1.0)}) |
| 58 | + |
| 59 | + async def task(): |
| 60 | + await session.with_transaction(callback) |
38 | 61 |
|
39 | 62 | task = asyncio.create_task(task())
|
40 | 63 |
|
41 |
| - # Make sure the task successfully runs a few operations to simulate a long-running user task |
42 |
| - await asyncio.sleep(0.01) |
| 64 | + await asyncio.sleep(0.1) |
43 | 65 |
|
44 | 66 | task.cancel()
|
45 | 67 | with self.assertRaises(asyncio.CancelledError):
|
46 | 68 | await task
|
47 | 69 |
|
48 |
| - self.assertFalse(conn.closed) |
| 70 | + self.assertFalse(session.in_transaction) |
| 71 | + |
0 commit comments