Skip to content

Commit 17ef431

Browse files
bpo-41891: ensure asyncio.wait_for waits for task completion (#22461)
1 parent 2179349 commit 17ef431

File tree

3 files changed

+66
-1
lines changed

3 files changed

+66
-1
lines changed

Lib/asyncio/tasks.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -437,7 +437,10 @@ async def wait_for(fut, timeout):
437437
return fut.result()
438438
else:
439439
fut.remove_done_callback(cb)
440-
fut.cancel()
440+
# We must ensure that the task is not running
441+
# after wait_for() returns.
442+
# See https://bugs.python.org/issue32751
443+
await _cancel_and_wait(fut, loop=loop)
441444
raise
442445

443446
if fut.done():
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import asyncio
2+
import unittest
3+
import time
4+
5+
def tearDownModule():
6+
asyncio.set_event_loop_policy(None)
7+
8+
9+
class SlowTask:
10+
""" Task will run for this defined time, ignoring cancel requests """
11+
TASK_TIMEOUT = 0.2
12+
13+
def __init__(self):
14+
self.exited = False
15+
16+
async def run(self):
17+
exitat = time.monotonic() + self.TASK_TIMEOUT
18+
19+
while True:
20+
tosleep = exitat - time.monotonic()
21+
if tosleep <= 0:
22+
break
23+
24+
try:
25+
await asyncio.sleep(tosleep)
26+
except asyncio.CancelledError:
27+
pass
28+
29+
self.exited = True
30+
31+
class AsyncioWaitForTest(unittest.TestCase):
32+
33+
async def atest_asyncio_wait_for_cancelled(self):
34+
t = SlowTask()
35+
36+
waitfortask = asyncio.create_task(asyncio.wait_for(t.run(), t.TASK_TIMEOUT * 2))
37+
await asyncio.sleep(0)
38+
waitfortask.cancel()
39+
await asyncio.wait({waitfortask})
40+
41+
self.assertTrue(t.exited)
42+
43+
def test_asyncio_wait_for_cancelled(self):
44+
asyncio.run(self.atest_asyncio_wait_for_cancelled())
45+
46+
async def atest_asyncio_wait_for_timeout(self):
47+
t = SlowTask()
48+
49+
try:
50+
await asyncio.wait_for(t.run(), t.TASK_TIMEOUT / 2)
51+
except asyncio.TimeoutError:
52+
pass
53+
54+
self.assertTrue(t.exited)
55+
56+
def test_asyncio_wait_for_timeout(self):
57+
asyncio.run(self.atest_asyncio_wait_for_timeout())
58+
59+
60+
if __name__ == '__main__':
61+
unittest.main()
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Ensure asyncio.wait_for waits for task completion

0 commit comments

Comments
 (0)