SyntaxStudy
Sign Up
Python Advanced 4 min read

Testing Async Code

Async Tests

Use pytest-asyncio or anyio to run async test functions with async def.

Example
import pytest
import httpx

@pytest.mark.asyncio
async def test_async_endpoint():
    async with httpx.AsyncClient(app=app, base_url="http://test") as client:
        resp = await client.get("/api/users")
        assert resp.status_code == 200

# pytest.ini
[pytest]
asyncio_mode = auto   # auto-detect async tests

@pytest.fixture
async def async_db():
    db = await create_test_db()
    yield db
    await db.close()
Pro Tip

Set asyncio_mode = auto in pytest.ini to avoid decorating every async test manually.