|
| 1 | +# Test the Task.done() method |
| 2 | + |
| 3 | +try: |
| 4 | + import asyncio |
| 5 | +except ImportError: |
| 6 | + print("SKIP") |
| 7 | + raise SystemExit |
| 8 | + |
| 9 | + |
| 10 | +async def task(t, exc=None, ret=None): |
| 11 | + if t >= 0: |
| 12 | + await asyncio.sleep(t) |
| 13 | + if exc: |
| 14 | + raise exc |
| 15 | + return ret |
| 16 | + |
| 17 | + |
| 18 | +async def main(): |
| 19 | + # Task that is not done yet raises an InvalidStateError |
| 20 | + print("=" * 10) |
| 21 | + t = asyncio.create_task(task(1)) |
| 22 | + await asyncio.sleep(0) |
| 23 | + try: |
| 24 | + t.result() |
| 25 | + assert False, "Should not get here" |
| 26 | + except Exception as e: |
| 27 | + print("InvalidStateError if still running:", repr(e)) |
| 28 | + |
| 29 | + # Task that is cancelled raises CancelledError |
| 30 | + print("=" * 10) |
| 31 | + t = asyncio.create_task(task(1)) |
| 32 | + t.cancel() |
| 33 | + await asyncio.sleep(0) |
| 34 | + try: |
| 35 | + t.result() |
| 36 | + assert False, "Should not get here" |
| 37 | + except asyncio.CancelledError as e: |
| 38 | + print("CancelledError when retrieving result from cancelled task:", repr(e)) |
| 39 | + |
| 40 | + # Task that raises immediately should raise that exception when calling result |
| 41 | + print("=" * 10) |
| 42 | + t = asyncio.create_task(task(-1, ValueError)) |
| 43 | + try: |
| 44 | + await t |
| 45 | + assert False, "Should not get here" |
| 46 | + except ValueError as e: |
| 47 | + pass |
| 48 | + |
| 49 | + try: |
| 50 | + t.result() |
| 51 | + assert False, "Should not get here" |
| 52 | + except ValueError as e: |
| 53 | + print("Error raised when result is attempted on task with error:", repr(e)) |
| 54 | + |
| 55 | + # Task that starts, runs and finishes without an exception or value should return None |
| 56 | + print("=" * 10) |
| 57 | + t = asyncio.create_task(task(0.01)) |
| 58 | + await t |
| 59 | + print("Empty Result should be None:", t.result()) |
| 60 | + assert t.result() is None |
| 61 | + |
| 62 | + # Task that starts, runs and finishes without exception should return result |
| 63 | + print("=" * 10) |
| 64 | + t = asyncio.create_task(task(0.01, None, "hello world")) |
| 65 | + await t |
| 66 | + print("Happy path, result is returned:", t.result()) |
| 67 | + |
| 68 | + |
| 69 | +asyncio.run(main()) |
0 commit comments