Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 38 ยท Testing Real Projects

Testing Async Code

Test asyncio code with pytest: how async tests are run, pytest-asyncio modes and fixtures, AsyncMock, timeouts and concurrency, with a runnable stand-in that shows what the plugin does.

Modern Python services use async and await for network and file work. A coroutine function does not run when you call it: it returns a coroutine object that needs an event loop to drive it. So a plain pytest test like def test_x(): assert fetch(1) == 2 fails in an obvious way (you compare a coroutine object to 2), and async def test_x() is not run by pytest on its own: since pytest 8.4 such a test fails with a message telling you to install an async plugin.

This lesson explains what an async plugin does, shows how to use pytest-asyncio (the most common choice) and AsyncMock, and covers the traps: timeouts, concurrency and shared state.

The in-browser Python already runs inside a browser event loop, and the real pytest-asyncio plugin wants to start its own. For that reason the plugin code below is shown as read-only, and the runnable examples use a tiny stand-in (a few lines in conftest.py) that runs coroutines which never actually wait. It demonstrates the idea; on your machine, use the real plugin.

What the plugin does

flowchart LR
    P["pytest calls<br/>async def test"] --> H["async plugin hook<br/>(pytest_pyfunc_call)"]
    H --> L["create / reuse event loop"]
    L --> R["run the coroutine until it finishes"]
    R --> O["report pass / fail"]

The plugin intercepts the call, runs the coroutine on a loop, and reports the result like any other test.

Real usage: pytest-asyncio (read-only)

Terminal
pip install pytest-asyncio
TOML
[tool.pytest.ini_options]
asyncio_mode = "auto"                 # or "strict" (the default)
asyncio_default_fixture_loop_scope = "function"

In strict mode you mark each async test or fixture explicitly; in auto mode every async def test and fixture is handled without markers. Auto is convenient in an all-async project, strict plays safer when you mix several async libraries.

Python
import asyncio
import pytest

async def fetch_user(client, user_id):
    data = await client.get(f"/users/{user_id}")
    return data["name"]

@pytest.mark.asyncio                      # not needed in auto mode
async def test_fetch_user(fake_client):
    assert await fetch_user(fake_client, 1) == "Ada"

@pytest.fixture
async def connection():                   # async fixture: setup, yield, teardown
    conn = await open_connection()
    yield conn
    await conn.close()

@pytest.mark.asyncio
async def test_concurrent_calls(connection):
    results = await asyncio.gather(connection.ping(), connection.ping())
    assert results == ["pong", "pong"]

Other options worth knowing: @pytest.mark.asyncio(loop_scope="module") shares one loop across a module (needed when a fixture opens a long-lived connection); anyio ships its own plugin (@pytest.mark.anyio) if you target both asyncio and trio; framework helpers such as httpx.AsyncClient(transport=ASGITransport(app)) let you test ASGI apps like FastAPI in-process.

A runnable stand-in

Here is the core idea in a few lines of conftest.py, as a plain hook (see conftest hooks). It drives a coroutine by hand. It only works for coroutines that finish without really waiting, which is exactly the situation when all dependencies are fakes, so it is enough to demonstrate the testing patterns.

Python Stand-in async plugin and first async tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at how little is special about the tests themselves: async def, await, and pytest.raises around an await. A fake with async def methods plays the part of the real client. With the real plugin the same test file works unchanged.

AsyncMock

unittest.mock.AsyncMock is the async twin of Mock: calling it returns an awaitable, and await mock() gives return_value. All the usual assertions exist with an await flavour: assert_awaited_once_with, await_count, assert_not_awaited. patch and mocker.patch create an AsyncMock automatically when the target is an async def.

Python AsyncMock return values, errors and await assertions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Traps in async tests

  • Forgetting await. result = fetch() gives a coroutine, and assert result == 4 fails confusingly. Python also warns "coroutine ... was never awaited"; treat that warning as an error with filterwarnings = ["error"].
  • Real waiting. A test that does await asyncio.sleep(5) takes 5 seconds. Patch asyncio.sleep with an AsyncMock, inject the delay, or use a fake clock library.
  • Hanging tests. A task that never completes hangs the whole run. Wrap awaits in asyncio.timeout(1) (Python 3.11+) or asyncio.wait_for(...), or add the pytest-timeout plugin.
  • Shared loops and state. Objects created on one event loop (locks, queues, connections) generally cannot be used on another. Keep fixture and test loop scopes consistent.
  • Unobserved background tasks. A task started with asyncio.create_task and never awaited can fail silently or outlive the test. Keep a reference and await or cancel it before the test ends.
  • Testing concurrency. To prove two operations overlap, use asyncio.Events to control the order instead of relying on timing.
Python
async def test_times_out_instead_of_hanging():
    with pytest.raises(TimeoutError):
        async with asyncio.timeout(0.1):
            await asyncio.sleep(10)     # the code under test would be here

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can't plain pytest run an async def test?

    An event loop has to drive the coroutine. Plugins like pytest-asyncio and anyio provide that via a hook.
  2. 2. In pytest-asyncio's strict mode, how do you mark an async test?

    Strict mode requires the explicit marker. Auto mode removes the need for it.
  3. 3. What does AsyncMock give you that Mock does not?

    AsyncMock is designed for async def functions: awaiting it returns return_value, and await counts are recorded.
  4. 4. How can you keep an async test from hanging forever?

    Bounding awaits with a timeout turns a hang into a clear failure.

Summary

  • Async tests need an event loop; pytest-asyncio (or anyio) supplies it through a hook.
  • Choose strict or auto mode, and keep fixture and test loop scopes consistent.
  • AsyncMock fakes async collaborators and offers assert_awaited_* checks; hand-written async fakes work too.
  • Never wait for real time or the real network; bound awaits with timeouts.
  • The runnable demos used a labelled stand-in; the real plugin handles genuine waiting.

Next: Continuous Integration with GitHub Actions