pytest-asyncio allows testing async functions with pytest.
1import pytest2import asyncio3from httpx import AsyncClient45# Install: pip install pytest-asyncio67# Mark test as async8@pytest.mark.asyncio9async def test_fetch_data():10 async with AsyncClient() as client:11 response = await client.get("http://localhost:8000/api/items")12 assert response.status_code == 20013 assert len(response.json()) > 01415# Async fixture16@pytest.fixture17async def async_db():18 db = await create_async_engine()19 yield db20 await db.dispose()2122@pytest.mark.asyncio23async def test_create_user(async_db):24 user = User(name="Alice")25 async_db.add(user)26 await async_db.commit()27 result = await async_db.get(User, user.id)28 assert result.name == "Alice"2930# Async mock31@pytest.mark.asyncio32async def test_with_mock():33 with patch("mymodule.fetch") as mock_fetch:34 mock_fetch.return_value = {"data": "test"}35 result = await my_async_function()36 assert result == {"data": "test"}3738# conftest.py — async fixture for entire session39@pytest.fixture(scope="session")40async def event_loop():41 loop = asyncio.get_event_loop_policy().new_event_loop()42 yield loop43 loop.close()
Configuration (pytest.ini):
1[pytest]2asyncio_mode = auto