Using pytest-asyncio for Asynchronous Testing in Python
This article introduces the pytest-asyncio plugin, explains how to install it, and provides multiple code examples demonstrating how to test asynchronous functions, fixtures, marked tests, parameterized tests, and exception handling with pytest in Python projects.
pytest-asyncio is a plugin for the pytest framework that simplifies testing of asynchronous code, especially code based on Python's asyncio library. It adds native support for async test functions and coroutines, allowing you to write tests using the familiar async def syntax and run them with pytest's test runner.
Installation pip install pytest pytest-asyncio Example 1: Simple test of an async function
Scenario: Test a simple async function that fetches data from a remote API and returns a dictionary.
import pytest
import aiohttp
from your_async_library import fetch_data_from_api
async def test_fetch_data_from_api():
async with aiohttp.ClientSession() as session:
result = await fetch_data_from_api(session, "https://api.example.com/data")
assert isinstance(result, dict)
assert "key" in result
assert result["key"] == "expected_value"Example 2: Using an async fixture to initialize test resources
Scenario: Define an async fixture that simulates a WebSocket connection and use it in a test.
import pytest
import websockets
import json
@pytest.fixture
async def websocket_connection():
async with websockets.connect("ws://localhost:8765/ws") as ws:
yield ws
async def test_send_and_receive(websocket_connection):
await websocket_connection.send(json.dumps({"action": "subscribe", "channel": "news"}))
response = await websocket_connection.recv()
assert json.loads(response) == {"status": "success", "message": "Subscribed to news channel"}Example 3: Marking async test functions with pytest.mark.asyncio
Scenario: Use the pytest.mark.asyncio decorator so pytest recognizes and executes the async test.
import pytest
import asyncio
from your_async_library import long_running_task
@pytest.mark.asyncio
async def test_long_running_task():
task_future = asyncio.create_task(long_running_task())
await asyncio.sleep(2) # wait for the task to run a bit
assert task_future.done()
assert task_future.result() == expected_resultExample 4: Parameterizing async tests with pytest.mark.parametrize
Scenario: Run multiple test cases for an async function by parameterizing inputs and expected outputs.
import pytest
from your_async_library import async_function
@pytest.mark.asyncio
@pytest.mark.parametrize("input_value, expected_output", [
(1, "result_1"),
("hello", "result_hello"),
({"key": "value"}, "result_dict"),
])
async def test_async_function(input_value, expected_output):
result = await async_function(input_value)
assert result == expected_outputExample 5: Testing async exception handling
Scenario: Verify that an async function raises the expected exceptions under error conditions.
import pytest
from your_async_library import async_function_that_raises
@pytest.mark.asyncio
async def test_exception_handling():
with pytest.raises(ValueError, match="Invalid input"):
await async_function_that_raises("invalid_input")
with pytest.raises(TimeoutError):
await async_function_that_raises("timeout")These examples demonstrate how to use pytest-asyncio for asynchronous testing, covering testing of async functions, async fixtures, marking tests, parameterizing tests, and handling async exceptions, helping you apply the plugin effectively in real-world asyncio projects.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
