Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
- Loading branch information
1 parent
e2f6bb4
commit f5051a7
Showing
3 changed files
with
66 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
import asyncio | ||
import unittest | ||
import time | ||
|
||
def tearDownModule(): | ||
asyncio.set_event_loop_policy(None) | ||
|
||
|
||
class SlowTask: | ||
""" Task will run for this defined time, ignoring cancel requests """ | ||
TASK_TIMEOUT = 0.2 | ||
|
||
def __init__(self): | ||
self.exited = False | ||
|
||
async def run(self): | ||
exitat = time.monotonic() + self.TASK_TIMEOUT | ||
|
||
while True: | ||
tosleep = exitat - time.monotonic() | ||
if tosleep <= 0: | ||
break | ||
|
||
try: | ||
await asyncio.sleep(tosleep) | ||
except asyncio.CancelledError: | ||
pass | ||
|
||
self.exited = True | ||
|
||
class AsyncioWaitForTest(unittest.TestCase): | ||
|
||
async def atest_asyncio_wait_for_cancelled(self): | ||
t = SlowTask() | ||
|
||
waitfortask = asyncio.create_task(asyncio.wait_for(t.run(), t.TASK_TIMEOUT * 2)) | ||
await asyncio.sleep(0) | ||
waitfortask.cancel() | ||
await asyncio.wait({waitfortask}) | ||
|
||
self.assertTrue(t.exited) | ||
|
||
def test_asyncio_wait_for_cancelled(self): | ||
asyncio.run(self.atest_asyncio_wait_for_cancelled()) | ||
|
||
async def atest_asyncio_wait_for_timeout(self): | ||
t = SlowTask() | ||
|
||
try: | ||
await asyncio.wait_for(t.run(), t.TASK_TIMEOUT / 2) | ||
except asyncio.TimeoutError: | ||
pass | ||
|
||
self.assertTrue(t.exited) | ||
|
||
def test_asyncio_wait_for_timeout(self): | ||
asyncio.run(self.atest_asyncio_wait_for_timeout()) | ||
|
||
|
||
if __name__ == '__main__': | ||
unittest.main() |
1 change: 1 addition & 0 deletions
1
Misc/NEWS.d/next/Library/2020-09-30-13-35-29.bpo-41891.pNAeYI.rst
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
Ensure asyncio.wait_for waits for task completion |