aioresponses
aioresponses is a Python library that allows you to easily mock out HTTP requests made by `aiohttp.ClientSession` in your asynchronous tests. It intercepts `aiohttp` requests and provides predefined responses, enabling isolated and fast testing of `asyncio` applications that interact with external services. The library is actively maintained, with a somewhat sporadic release cadence, focusing on compatibility with newer `aiohttp` versions and API refinements.
Warnings
- breaking Version 0.4.0 dropped support for `aiohttp 1.x` and introduced compatibility with `aiohttp 3.x`. Using `aioresponses >= 0.4.0` with older `aiohttp` versions will lead to errors.
- breaking Version 0.5.0 introduced significant internal API renames: `MockedResponse` became `RequestMatch`, `method_call` became `RequestCall`, and the internal `_responses` attribute was renamed to `_matches`. This may affect advanced usage or direct inspection of the mock object.
- gotcha Prior to version 0.5.0, a mocked request would only be matched once. Subsequent requests to the same URL or pattern would not use the mock and would either hit the real network or fail.
- gotcha The `aioresponses` context manager (or fixture) must encompass the entire lifecycle of the `aiohttp.ClientSession` and all requests you intend to mock. If the context manager exits before a `ClientSession` makes its request, the mock will no longer be active, leading to real network calls or connection errors.
Install
-
pip install aioresponses
Imports
- aioresponses
from aioresponses import aioresponses
Quickstart
import asyncio
from aiohttp import ClientSession
from aioresponses import aioresponses
async def fetch_data(url):
async with ClientSession() as session:
async with session.get(url) as response:
response.raise_for_status() # Raise an exception for bad status codes
return await response.json()
async def main():
test_url = "http://example.com/api/data"
# Mocking the GET request to test_url
with aioresponses() as m:
m.get(test_url, status=200, payload={"key": "value"})
data = await fetch_data(test_url)
print(f"Fetched data: {data}")
# Assert that the mock was called
assert m.called
assert test_url in m.calls[0].url
if __name__ == "__main__":
asyncio.run(main())