|
| 1 | +# Test cancelling a task |
| 2 | + |
| 3 | +try: |
| 4 | + import asyncio |
| 5 | +except ImportError: |
| 6 | + print("SKIP") |
| 7 | + raise SystemExit |
| 8 | + |
| 9 | + |
| 10 | +async def task(s, allow_cancel): |
| 11 | + try: |
| 12 | + print("task start") |
| 13 | + await asyncio.sleep(s) |
| 14 | + print("task done") |
| 15 | + except asyncio.CancelledError as er: |
| 16 | + print("task cancel") |
| 17 | + if allow_cancel: |
| 18 | + raise er |
| 19 | + |
| 20 | + |
| 21 | +async def task2(allow_cancel): |
| 22 | + print("task 2") |
| 23 | + try: |
| 24 | + await asyncio.create_task(task(0.05, allow_cancel)) |
| 25 | + except asyncio.CancelledError as er: |
| 26 | + print("task 2 cancel") |
| 27 | + raise er |
| 28 | + print("task 2 done") |
| 29 | + |
| 30 | + |
| 31 | +async def main(): |
| 32 | + # Cancel task immediately doesn't mark the task as cancelled |
| 33 | + print("=" * 10) |
| 34 | + t = asyncio.create_task(task(2, True)) |
| 35 | + t.cancel() |
| 36 | + print("Expecting task to not be cancelled because it is not done:", t.cancelled()) |
| 37 | + |
| 38 | + # Cancel task immediately and wait for cancellation to complete |
| 39 | + print("=" * 10) |
| 40 | + t = asyncio.create_task(task(2, True)) |
| 41 | + t.cancel() |
| 42 | + await asyncio.sleep(0) |
| 43 | + print("Expecting Task to be Cancelled:", t.cancelled()) |
| 44 | + |
| 45 | + # Cancel task and wait for cancellation to complete |
| 46 | + print("=" * 10) |
| 47 | + t = asyncio.create_task(task(2, True)) |
| 48 | + await asyncio.sleep(0.01) |
| 49 | + t.cancel() |
| 50 | + await asyncio.sleep(0) |
| 51 | + print("Expecting Task to be Cancelled:", t.cancelled()) |
| 52 | + |
| 53 | + # Cancel task multiple times after it has started |
| 54 | + print("=" * 10) |
| 55 | + t = asyncio.create_task(task(2, True)) |
| 56 | + await asyncio.sleep(0.01) |
| 57 | + for _ in range(4): |
| 58 | + t.cancel() |
| 59 | + await asyncio.sleep(0.01) |
| 60 | + |
| 61 | + print("Expecting Task to be Cancelled:", t.cancelled()) |
| 62 | + |
| 63 | + # Cancel task after it has finished |
| 64 | + print("=" * 10) |
| 65 | + t = asyncio.create_task(task(0.01, False)) |
| 66 | + await asyncio.sleep(0.05) |
| 67 | + t.cancel() |
| 68 | + print("Expecting task to not be Cancelled:", t.cancelled()) |
| 69 | + |
| 70 | + # Nested: task2 waits on task, task2 is cancelled (should cancel task then task2) |
| 71 | + print("=" * 10) |
| 72 | + t = asyncio.create_task(task2(True)) |
| 73 | + await asyncio.sleep(0.01) |
| 74 | + t.cancel() |
| 75 | + await asyncio.sleep(0.1) |
| 76 | + |
| 77 | + print("Expecting task 2 to be Cancelled:", t.cancelled()) |
| 78 | + |
| 79 | + |
| 80 | +asyncio.run(main()) |
0 commit comments