How to Use pytest-asyncio for Async Tests in Python
Use
pytest-asyncio by installing it and marking your async test functions with @pytest.mark.asyncio. This allows pytest to run async functions using the event loop, enabling testing of asynchronous code naturally.Syntax
To use pytest-asyncio, decorate your async test functions with @pytest.mark.asyncio. This tells pytest to run the test inside an event loop.
Example syntax:
@pytest.mark.asyncio: Decorator to mark async tests.async def test_func():: Define your test as an async function.- Use
awaitinside the test to call async code.
python
import pytest @pytest.mark.asyncio async def test_example(): await some_async_function()
Example
This example shows a simple async test using pytest-asyncio. It tests an async function that returns a value after a short delay.
python
import pytest import asyncio async def async_add(x, y): await asyncio.sleep(0.1) return x + y @pytest.mark.asyncio async def test_async_add(): result = await async_add(2, 3) assert result == 5
Output
============================= test session starts =============================
collected 1 item
test_asyncio_example.py . [100%]
============================== 1 passed in 0.12s ==============================
Common Pitfalls
Common mistakes when using pytest-asyncio include:
- Forgetting to add
@pytest.mark.asyncioto async test functions, causing pytest to error or skip the test. - Defining async tests without
async def, which breaks async behavior. - Trying to run async code without
await, leading to coroutine objects instead of results.
Correct usage example:
python
import pytest import asyncio # Wrong: missing decorator async def test_wrong(): await asyncio.sleep(0.1) # Right: @pytest.mark.asyncio async def test_right(): await asyncio.sleep(0.1)
Quick Reference
| Feature | Usage |
|---|---|
| Mark async test | @pytest.mark.asyncio |
| Define async test | async def test_func(): |
| Await async calls | await async_function() |
| Run tests | pytest test_file.py |
Key Takeaways
Always decorate async test functions with @pytest.mark.asyncio to enable async support.
Define async tests using async def and use await inside them for async calls.
Install pytest-asyncio via pip before running async tests.
Avoid missing the decorator or forgetting await to prevent test failures.
Use pytest normally to run async tests once properly marked.