Advertisement
Advanced Python, Async Generators & Async Context Managers

How do you correctly test async generators and async context managers using pytest and pytest-asyncio?

Short answer

Mark the test function with @pytest.mark.asyncio (or use pytest-asyncio's auto mode), then use 'async for' or 'async with' directly inside the async test function exactly as you would in application code — assertions can be made on collected values or on side effects observed…

Save Python mock interview
Advertisement
AModel answer
Mark the test function with @pytest.mark.asyncio (or use pytest-asyncio's auto mode), then use 'async for' or 'async with' directly inside the async test function exactly as you would in application code — assertions can be made on collected values or on side effects observed during/after iteration.
import pytest

@pytest.mark.asyncio
async def test_fetch_pages():
    results = [page async for page in fetch_pages()]
    assert results == ["page-0", "page-1", "page-2"]

@pytest.mark.asyncio
async def test_async_connection():
    async with async_connection() as conn:
        assert conn.is_open
Real-world example
Writing reliable unit tests for an async data pipeline or async resource manager as part of a CI test suite.
Likely follow-ups
  • What pytest-asyncio configuration option controls whether every async test needs the explicit @pytest.mark.asyncio decorator?
Related topics