0
0
PytestHow-ToBeginner ยท 3 min read

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 await inside 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.asyncio to 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

FeatureUsage
Mark async test@pytest.mark.asyncio
Define async testasync def test_func():
Await async callsawait async_function()
Run testspytest 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.