Isolate Async Tests and Verify Cancellation Cleanup
Core idea
IsolatedAsyncioTestCase supplies an event loop for each async test. Use events to establish that a task reached a known state before cancellation. Cancel and await tasks, assert CancelledError where appropriate and inspect cleanup effects. A timeout bounds waiting but does not establish ordering.
import asyncio, unittestclass TestWorker(unittest.IsolatedAsyncioTestCase): async def test_cleanup(self): started = asyncio.Event() cleaned = asyncio.Event() async def worker(): try: started.set() await asyncio.Event().wait() finally: cleaned.set() task = asyncio.create_task(worker()) try: await asyncio.wait_for(started.wait(), 1) finally: task.cancel() with self.assertRaises(asyncio.CancelledError): await task self.assertTrue(cleaned.is_set())r = TestWorker('test_cleanup').run()print(r.testsRun, r.wasSuccessful())The signal establishes that the worker entered its try block. Awaiting cancellation ensures finally has run before inspection.
Expected output:
1 TrueRegister async cleanup
import unittestlog = []class TestResource(unittest.IsolatedAsyncioTestCase): async def asyncSetUp(self): log.append('open') async def close(): log.append('close') self.addAsyncCleanup(close) async def test_work(self): log.append('work') self.assertEqual(log, ['open','work'])r = TestResource('test_work').run()print(log, r.wasSuccessful())The registered coroutine runs during cleanup after the test.
Expected output:
['open', 'work', 'close'] TrueCommon mistake
Do not call asyncio.run inside an already running test loop. Avoid asserting cancellation based only on sleep durations; a task cancelled before it starts may not execute its body at all.
Practice
Write an async test for a resource that records acquire and release. Force an exception after acquisition, register cleanup, and assert that release happens exactly once.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Async test isolation
Check your understanding of async test isolation.
What is printed?
import asyncio, unittestclass T(unittest.IsolatedAsyncioTestCase): async def test_a(self): self.assertTrue(asyncio.get_running_loop().is_running())print(T("test_a").run().wasSuccessful())What is printed?
import asyncioasync def main(): e=asyncio.Event(); e.set(); await e.wait(); print(e.is_set())asyncio.run(main())How can a test establish that a task has entered its body?
What should follow task.cancel()?