Test Async Behavior with Explicit Synchronization
Core idea
unittest.IsolatedAsyncioTestCase runs coroutine test methods with an isolated event loop and supports asyncSetUp, asyncTearDown and addAsyncCleanup. Use asyncio.Event to prove a task reached a state instead of guessing a sleep duration. A test may have a generous safety timeout to prevent a hang; a timeout alone is not evidence that a specific state was reached.
import asyncio, unittestclass FlowTest(unittest.IsolatedAsyncioTestCase): async def test_gate(self): entered=asyncio.Event() release=asyncio.Event() async def work(): entered.set() await release.wait() return 7 async with asyncio.timeout(2): async with asyncio.TaskGroup() as group: task=group.create_task(work()) await entered.wait() self.assertFalse(task.done()) release.set() self.assertEqual(task.result(),7)r=FlowTest('test_gate').run()print(r.testsRun,r.wasSuccessful())The event gives an observable synchronization point; the deadline is only a hang safeguard.
Expected output:
1 TrueAssert cleanup is awaited
import unittestlog=[]class CleanupTest(unittest.IsolatedAsyncioTestCase): async def asyncSetUp(self): async def clean(): log.append('cleanup') self.addAsyncCleanup(clean) async def test_body(self): log.append('body')r=CleanupTest('test_body').run()print(r.wasSuccessful(), log)The runner awaits the registered asynchronous cleanup after the test.
Expected output:
True ['body', 'cleanup']Common mistake
A test that calls sleep(0.1) and assumes another task has finished can be flaky. Await a task or event instead. Clean up children explicitly; isolation is not a substitute for checking cancellation and resource lifetimes.
Practice
Adapt FlowTest to cancel a task after entered is set. Assert that finally records cleanup and the task is cancelled.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Async testing
Check your understanding of async testing.
What is printed?
import unittestclass T(unittest.IsolatedAsyncioTestCase): async def test_a(self): self.assertEqual(4,4)print(T('test_a').run().wasSuccessful())What is printed?
import asyncio
async def main(): e=asyncio.Event() print(e.is_set()) e.set() print(await e.wait())
asyncio.run(main())Which tool establishes a deterministic task milestone?
Which test class supports coroutine test methods?