Skip to content

Lesson 7 of 9 · 25m

Testing Async Python

Use pytest-asyncio deliberately, test concurrency behavior without sleeping races, and isolate event-loop boundaries with deterministic controls.

Async tests fail in ways synchronous tests do not: tasks leak, timeouts never fire, ordering races pass locally and collapse in CI. The fix is not sprinkling async everywhere. It is making concurrency explicit and controlling time.

Mark async tests explicitly

With pytest-asyncio, the simple form is:

@pytest.mark.asyncio
async def test_fetch_user():
    user = await fetch_user(7)
    assert user.id == 7

Or set asyncio_mode = auto in pytest.ini; auto mode reduces decorator noise but makes async tests less visually explicit. On mixed teams, explicit markers are often clearer. Whichever you choose, standardize.

Do not test sleep order

This is a race disguised as a test:

async def test_worker_processes_jobs():
    task = asyncio.create_task(worker.run_once())
    await asyncio.sleep(0.1)
    assert queue.empty()

The correct move is synchronization, not sleeping longer. Await the task or use events:

async def test_worker_processes_jobs():
    done = asyncio.Event()
    worker.on_empty = done.set
    task = asyncio.create_task(worker.run_once())
    await asyncio.wait_for(done.wait(), timeout=1)
    task.cancel()
    assert queue.empty()

Timeouts are still necessary, but they are failure guards, not scheduling logic.

Control the clock

Time-dependent async code should accept a clock or sleep function:

async def retry(operation, sleep=asyncio.sleep, attempts=3):
    for attempt in range(attempts):
        try:
            return await operation()
        except TemporaryError:
            if attempt == attempts - 1:
                raise
            await sleep(2 ** attempt)

In tests, inject a fake sleep that records delays without waiting:

async def test_retry_backs_off():
    delays = []
    async def fake_sleep(seconds):
        delays.append(seconds)
    result = await retry(flaky_operation, sleep=fake_sleep)
    assert delays == [1, 2]

This tests backoff policy deterministically in milliseconds.

Use anyio or asyncio consistently

Libraries built on anyio may run under asyncio or trio. Their test patterns differ. Do not mix mental models casually in one module. For application code, testing the event loop you deploy under is usually enough; for a library, test each supported backend.

Field notes

  • Failure output mentioning "Task was destroyed but it is pending" means your test leaked a task; cancellation and cleanup are part of the behavior.
  • Use pytest-asyncio fixture support carefully — async fixtures need the plugin and often confuse collection when defined as plain generators.
  • Never call asyncio.run() inside a test already running under an event loop; use direct awaits.
  • Set strict timeouts around waits so deadlocks fail fast instead of hanging CI for thirty minutes.
  • Real concurrency bugs often need integration tests with real tasks, not only unit tests with mocked coroutines.

Was this lesson helpful?

Sign in to rate