Async Testing with pytest-asyncio & Code Coverage
1Concept
`pytest-asyncio` allows writing `async def test_*()` functions to test coroutines directly. `pytest-cov` measures line and branch code coverage, generating HTML coverage reports.
2Architecture Diagram
pytest --cov=app --cov-report=html ---> Generates visual test coverage heatmap
3Code Example
Python 3.12
async_test_sample = '''
import pytest
import asyncio
async def async_sum(a: int, b: int) -> int:
await asyncio.sleep(0.01)
return a + b
@pytest.mark.asyncio
async def test_async_sum():
result = await async_sum(15, 25)
assert result == 40
'''
print("=== Async PyTest Pattern ===")
print(async_test_sample.strip())4Expected Output
=== Async PyTest Pattern ===
import pytest
import asyncio
async def async_sum(a: int, b: int) -> int:
await asyncio.sleep(0.01)
return a + b
@pytest.mark.asyncio
async def test_async_sum():
result = await async_sum(15, 25)
assert result == 405Key Takeaways
- ✓Configure `asyncio_mode = auto` in `pyproject.toml` to omit `@pytest.mark.asyncio` on every test.
- ✓Use `httpx.AsyncClient` with `ASGITransport` to test FastAPI endpoints asynchronously.
- ✓Target 80%+ branch code coverage for enterprise production services.