Skip to content

Commit 82dbfd5

Browse files
bpo-41891: ensure asyncio.wait_for waits for task completion (GH-22461) (#23840)
(cherry picked from commit 17ef431) Co-authored-by: Richard Kojedzinszky <[email protected]> Co-authored-by: Richard Kojedzinszky <[email protected]>
1 parent 1461992 commit 82dbfd5

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
@@ -471,7 +471,10 @@ async def wait_for(fut, timeout, *, loop=None):
471471
return fut.result()
472472
else:
473473
fut.remove_done_callback(cb)
474-
fut.cancel()
474+
# We must ensure that the task is not running
475+
# after wait_for() returns.
476+
# See https://bugs.python.org/issue32751
477+
await _cancel_and_wait(fut, loop=loop)
475478
raise
476479

477480
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)