IsolatedAsyncioTestCase runs each asynchronous test with an event-loop lifetime managed by unittest.
Python IsolatedAsyncioTestCase: own async setup and cleanup per test
Operation contract
The fixture creates a queue in asyncSetUp, consumes one receipt in an async test and records cleanup in asyncTearDown. The runner uses an owned in-memory text stream so only stable outcome fields are printed. The event list proves setup, test and cleanup ran in that order. This checks one local queue operation, not network I/O or a production task scheduler.
Failure and ownership boundary
An asynchronous test can still leak a task whose result it never observes. Own created tasks, cancel or await them in cleanup and test the failure path as well as success. Python asyncio TaskGroup: cancel sibling work and retain failure evidence, Python asyncio.gather: a sibling can continue after the first failure and Python asyncio timeout: cancellation and cleanup ownership matter when tests create background work.
Working program
import asyncio
import io
import unittest
events = []
class QueueCase(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.queue = asyncio.Queue()
events.append("setup")
async def test_receipt(self):
await self.queue.put("R41")
self.assertEqual(await self.queue.get(), "R41")
events.append("test")
async def asyncTearDown(self):
self.assertTrue(self.queue.empty())
events.append("cleanup")
result = unittest.TextTestRunner(stream=io.StringIO()).run(
unittest.defaultTestLoader.loadTestsFromTestCase(QueueCase))
print("passed:", result.wasSuccessful())
print("events:", events)Output
passed: True
events: ['setup', 'test', 'cleanup']Costs and limits
The test pays event-loop setup/teardown cost in addition to one queue operation. It does not measure thread contention or real service time. The in-memory queue is local to this fixture and has no persistence.
Common Mistakes
- Observe every spawned task; loop cleanup is not proof that its work succeeded.
- An in-memory async test is not a deployed I/O test.
Connected lessons
Python asyncio TaskGroup: cancel sibling work and retain failure evidence, Python asyncio.gather: a sibling can continue after the first failure, Python asyncio timeout: cancellation and cleanup ownership.
