Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python unittest + asyncio hangs forever

Why does the following test hang forever?

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()
like image 580
Andrey Moiseev Avatar asked Sep 12 '25 01:09

Andrey Moiseev


1 Answers

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
like image 62
Pynchia Avatar answered Sep 14 '25 15:09

Pynchia