|
| 1 | +import asyncio |
| 2 | +import sys |
| 3 | + |
| 4 | +import pytest |
| 5 | + |
| 6 | +from asgiref.timeout import timeout |
| 7 | + |
| 8 | + |
| 9 | +@pytest.mark.asyncio |
| 10 | +async def test_timeout_restores_cancellation_count() -> None: |
| 11 | + if sys.version_info < (3, 11): |
| 12 | + pytest.skip("Task cancellation counts were added in Python 3.11") |
| 13 | + |
| 14 | + task = asyncio.current_task() |
| 15 | + assert task is not None |
| 16 | + cancelling = task.cancelling() |
| 17 | + |
| 18 | + with pytest.raises(asyncio.TimeoutError): |
| 19 | + async with timeout(0): |
| 20 | + await asyncio.sleep(0) |
| 21 | + |
| 22 | + assert task.cancelling() == cancelling |
| 23 | + |
| 24 | + |
| 25 | +@pytest.mark.asyncio |
| 26 | +async def test_timeout_restores_count_when_cancellation_is_suppressed() -> None: |
| 27 | + if sys.version_info < (3, 11): |
| 28 | + pytest.skip("Task cancellation counts were added in Python 3.11") |
| 29 | + |
| 30 | + task = asyncio.current_task() |
| 31 | + assert task is not None |
| 32 | + cancelling = task.cancelling() |
| 33 | + |
| 34 | + async with timeout(0): |
| 35 | + try: |
| 36 | + await asyncio.sleep(0) |
| 37 | + except asyncio.CancelledError: |
| 38 | + pass |
| 39 | + |
| 40 | + assert task.cancelling() == cancelling |
| 41 | + |
| 42 | + |
| 43 | +@pytest.mark.asyncio |
| 44 | +async def test_timeout_preserves_external_cancellation() -> None: |
| 45 | + if sys.version_info < (3, 11): |
| 46 | + pytest.skip("Task cancellation counts were added in Python 3.11") |
| 47 | + |
| 48 | + task = asyncio.current_task() |
| 49 | + assert task is not None |
| 50 | + cancelling = task.cancelling() |
| 51 | + |
| 52 | + try: |
| 53 | + with pytest.raises(asyncio.CancelledError): |
| 54 | + async with timeout(0): |
| 55 | + asyncio.get_running_loop().call_soon(task.cancel) |
| 56 | + await asyncio.sleep(0) |
| 57 | + |
| 58 | + assert task.cancelling() == cancelling + 1 |
| 59 | + finally: |
| 60 | + while task.cancelling() > cancelling: |
| 61 | + task.uncancel() |
0 commit comments