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.
pip install aioresponsesVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to use `aioresponses` as a context manager to mock an HTTP GET request made by `aiohttp.ClientSession`. It sets up a mock for `http://example.com/api/data` to return a 200 status and a JSON payload, then calls an `async` function that uses `aiohttp` to fetch data, and finally asserts that the mock was engaged.
Ensure your project uses `aiohttp >= 3.0.0` to be compatible with `aioresponses >= 0.4.0`. The library currently explicitly requires `aiohttp>=3.0.0`.
Update any code that directly accesses or expects the old class or attribute names to use the new `RequestMatch`, `RequestCall`, and `_matches` names respectively.
Upgrade to `aioresponses >= 0.5.0` to enable repeated executions of mocked requests. If upgrading is not possible, ensure your tests only make a single request per mock setup or explicitly add multiple mocks for the same URL.
Structure your code to ensure the `with aioresponses() as m:` block (or the `aioresponses` fixture in `pytest`) is active for the duration of the `aiohttp.ClientSession` that performs the requests. For example, pass the `ClientSession` into the mocked function, or create the `ClientSession` within the mock's scope.
To check if any request was made and matched within the `aioresponses` context, you can inspect `m.calls` (e.g., `assert len(m.calls) > 0`). For specific mocks, use methods like `assert_called()` on the `RequestMatch` object returned when defining the mock (e.g., `mock_obj = m.get(...)`, then `mock_obj.assert_called()`).
To check if a specific mock was called, use `mock_object.called` where `mock_object` is the return value of `m.get()`, `m.post()`, etc. To check the history of all matched requests, use `m.history` (available from `aioresponses >= 0.6.0`). Alternatively, iterate through `m._matches` and check `RequestCall.called` for each matched request.
Install the package using pip: 'pip install aioresponses'.
Use the correct import: 'from aioresponses import aioresponses'.
Use 'aioresponses' as a decorator: '@aioresponses()' or as a context manager: 'with aioresponses() as m:'.
Ensure 'aioresponses' is used as a decorator or within a context manager, and that HTTP methods are mocked correctly within that scope.
Use 'await' directly in async functions or use 'nest_asyncio' to allow nested event loops in interactive environments.