← Back to FastAPI, page 2

fastapi-0037 · Hard senior

How do you write async tests for a FastAPI app, and when do you need them instead of TestClient?

Use httpx.AsyncClient with ASGITransport(app=app) inside async test functions run by the AnyIO pytest plugin (@pytest.mark.anyio) or pytest-asyncio. You need async tests when the test itself must await things: async database fixtures, async service calls, or checking state with async clients on the same event loop. ASGITransport does not run lifespan events, so wrap the app with asgi-lifespan's LifespanManager or set up resources in fixtures.

Full answer

TestClient is synchronous: it runs the app in a separate thread with its own event loop. That is simple and covers most endpoint tests. It becomes awkward when:

  • fixtures are async (creating rows with an AsyncSession, seeding Redis with an async client),
  • the test needs to call async functions directly alongside HTTP calls,
  • async resources are bound to one event loop (asyncpg connections, async engines) and the test and app must share it.

An async test:

python
@pytest.mark.anyio
async def test_create_book():
    transport = ASGITransport(app=app)
    async with AsyncClient(transport=transport, base_url="http://test") as client:
        r = await client.post("/books", json={...})
    assert r.status_code == 201

Setup choices:

  • AnyIO's pytest plugin ships with AnyIO (a Starlette dependency). Mark tests with @pytest.mark.anyio and define an anyio_backend fixture returning "asyncio" to avoid also running on trio.
  • pytest-asyncio works too (@pytest.mark.asyncio or asyncio_mode = "auto").
  • ASGITransport calls the app in-process; no network. It does not send lifespan events. Use asgi_lifespan.LifespanManager(app) or create resources in fixtures and inject them with dependency_overrides.
  • Use base_url="http://test"; the host is required but not contacted.
  • Starlette 1.x's TestClient builds on the httpx2 package; httpx2 keeps the same AsyncClient and ASGITransport API, so either package works for these tests.

Patterns for reliable async tests:

  • Database per test: open a connection, begin a transaction, bind the session to it, override get_db, and roll back at teardown. Fast and isolated.
  • Override outbound HTTP clients with fakes, or use respx to mock httpx calls.
  • Keep event-loop scope consistent: session-scoped async fixtures need the matching loop scope in pytest-asyncio.
  • Test concurrency bugs explicitly with asyncio.gather on several requests when behaviour under parallel calls matters (idempotency, locking).
python
import asyncio

import httpx
import pytest
from fastapi import Depends, FastAPI

app = FastAPI()


class AsyncStore:                       # stands in for an async repository
    def __init__(self):
        self.rows = {}

    async def add(self, roll_no, name):
        await asyncio.sleep(0)
        self.rows[roll_no] = name

    async def get(self, roll_no):
        await asyncio.sleep(0)
        return self.rows.get(roll_no)


async def get_store():
    raise RuntimeError("real store not used in tests")


@app.post("/students/{roll_no}", status_code=201)
async def add_student(roll_no: str, name: str, store: AsyncStore = Depends(get_store)):
    if await store.get(roll_no):
        return {"created": False}
    await store.add(roll_no, name)
    return {"created": True}


@pytest.fixture
def anyio_backend():
    return "asyncio"


@pytest.fixture
async def store():
    s = AsyncStore()
    await s.add("BCA-01", "Existing Student")   # async fixture setup
    app.dependency_overrides[get_store] = lambda: s
    yield s
    app.dependency_overrides.clear()


@pytest.fixture
async def client():
    transport = httpx.ASGITransport(app=app)
    async with httpx.AsyncClient(transport=transport, base_url="http://test") as c:
        yield c


@pytest.mark.anyio
async def test_add_and_read_back(client, store):
    r = await client.post("/students/BCA-02", params={"name": "Neel"})
    assert r.status_code == 201 and r.json() == {"created": True}
    assert await store.get("BCA-02") == "Neel"            # check state with an async call


@pytest.mark.anyio
async def test_duplicate(client, store):
    r = await client.post("/students/BCA-01", params={"name": "Someone"})
    assert r.json() == {"created": False}


@pytest.mark.anyio
async def test_parallel_requests(client, store):
    results = await asyncio.gather(*(client.post(f"/students/R{i}", params={"name": "x"}) for i in range(5)))
    assert all(r.status_code == 201 for r in results)
    assert len(store.rows) == 6


if __name__ == "__main__":
    code = pytest.main([__file__, "-qq", "-p", "no:cacheprovider", "-p", "no:warnings"])
    print("pytest exit code:", int(code))

Standalone pytest file using AnyIO's pytest plugin (bundled with AnyIO). Run with `python file.py` or `pytest file.py`; needs `pip install pytest httpx`. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0, pytest 9.2.0): ... [100%] pytest exit code: 0

Key points

  • httpx.AsyncClient + ASGITransport for in-process async calls
  • Run with @pytest.mark.anyio or pytest-asyncio
  • Needed when fixtures or checks are async or loop-bound
  • ASGITransport skips lifespan; use LifespanManager or fixtures
  • Roll back a transaction per test for isolation

Common mistakes

  • Mixing TestClient with async fixtures bound to another event loop
  • Expecting ASGITransport to run lifespan startup code
  • Forgetting the anyio_backend fixture and running tests twice on trio
  • Sharing state between tests without resetting dependency overrides

Follow-ups

  • How would you give each async test its own database transaction?
  • How do you mock outbound httpx calls in async tests?
  • What is the difference between pytest-anyio and pytest-asyncio?

Tips

  • Explain why TestClient is not enough in some cases
  • Mention ASGITransport and the lifespan gap
  • Describe a database isolation strategy