pytest-aiohttp
pytest-aiohttp is a pytest plugin that provides useful fixtures for testing aiohttp applications. It simplifies the creation and interaction with aiohttp servers and clients within your pytest test suite. The current version is 1.1.0 and releases are typically made as needed, often following updates to `aiohttp` or `pytest`.
Warnings
- breaking The `loop` fixture was removed in version 1.0.0. If your tests explicitly depended on `loop` for asyncio event loop access, you should now use `asyncio.get_event_loop()` or `asyncio.current_task()` where appropriate.
- breaking Python 3.7 and 3.8 support was dropped in version 1.0.0. Users on these Python versions must upgrade to Python 3.9 or newer to use `pytest-aiohttp` v1.0.0 and later.
- gotcha You must configure `pytest-asyncio` by adding `asyncio_mode = auto` to your `pytest.ini` or `pyproject.toml` file. Without this, your async tests using `pytest-aiohttp` fixtures will not run correctly.
- gotcha `pytest-aiohttp` has specific `pytest` version requirements. For example, `pytest-aiohttp>=1.0.0` requires `pytest>=7.0.0`. Using an incompatible version of `pytest` can lead to unexpected errors or fixtures not being discovered.
Install
-
pip install pytest-aiohttp
Quickstart
import pytest
from aiohttp import web
# test_app.py
@pytest.fixture
async def cli(aiohttp_client):
"""Client fixture that returns a test client for your aiohttp application."""
app = web.Application()
async def hello_handler(request):
return web.Response(text="Hello from aiohttp app!")
app.router.add_get('/', hello_handler)
return await aiohttp_client(app)
async def test_hello_world(cli):
"""Test that the application responds correctly."""
resp = await cli.get('/')
assert resp.status == 200
text = await resp.text()
assert 'Hello from aiohttp app!' in text