Skip to content

Commit 983fa0f

Browse files
author
8r1ef
committed
Use asyncio timeout on Python 3.11+
1 parent 157d9d4 commit 983fa0f

2 files changed

Lines changed: 32 additions & 1 deletion

File tree

asgiref/testing.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
11
import asyncio
22
import contextvars
3+
import sys
34
import time
45

56
from .compatibility import guarantee_single_callable
6-
from .timeout import timeout as async_timeout
7+
8+
if sys.version_info >= (3, 11):
9+
async_timeout = asyncio.timeout
10+
else:
11+
from .timeout import timeout as async_timeout
712

813

914
class ApplicationCommunicator:

tests/test_testing.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,32 @@ def wsgi_application(environ, start_response):
4848
assert await instance.receive_nothing(0.01) is True
4949

5050

51+
@pytest.mark.asyncio
52+
async def test_receive_output_timeout_restores_cancellation_count():
53+
"""A handled timeout must not leave its task in a cancelling state."""
54+
if not hasattr(asyncio, "timeout"):
55+
pytest.skip("Task cancellation counts were added in Python 3.11")
56+
57+
async def application(scope, receive, send):
58+
await asyncio.Event().wait()
59+
60+
instance = ApplicationCommunicator(application, {})
61+
task = asyncio.current_task()
62+
assert task is not None
63+
cancelling = getattr(task, "cancelling")
64+
uncancel = getattr(task, "uncancel")
65+
before = cancelling()
66+
67+
try:
68+
with pytest.raises(asyncio.TimeoutError):
69+
await instance.receive_output(timeout=0)
70+
71+
assert cancelling() == before
72+
finally:
73+
while cancelling() > before:
74+
uncancel()
75+
76+
5177
def test_receive_nothing_lazy_loop():
5278
"""
5379
Tests ApplicationCommunicator.receive_nothing to return the correct value.

0 commit comments

Comments
 (0)