Catching the CancelledError
exception when awaiting the cancelled task makes things go smooth.
So I guess the test runner gets held up in the act.
import asyncio
import unittest
class TestCancellation(unittest.IsolatedAsyncioTestCase):
async def test_works(self):
task = asyncio.create_task(asyncio.sleep(5))
await asyncio.sleep(2)
task.cancel()
try:
await task
except asyncio.CancelledError:
print("Task Cancelled already")
if __name__ == '__main__':
unittest.main()
produces
unittest-hang $ python3.8 test.py
Task Cancelled already
.
----------------------------------------------------------------------
Ran 1 test in 2.009s
OK
I ignore whether you must await the cancelled task or not.
If you must, since you seem to be testing its cancellation fully, then catch the exception.
If not, then just avoid it, since creating a task starts it immediately and there is no need to await again
import asyncio
import unittest
class TestCancellation(unittest.IsolatedAsyncioTestCase):
async def test_works(self):
task = asyncio.create_task(asyncio.sleep(5))
await asyncio.sleep(2)
task.cancel()
# await task
if __name__ == '__main__':
unittest.main()
produces
unittest-hang $ python3.8 test.py
.
----------------------------------------------------------------------
Ran 1 test in 2.009s
OK