Registry / testing / aioresponses

aioresponses

JSON →
library0.7.8pypypi✓ verified 52d ago

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.

testinghttp-networkingweb-framework
pip install aioresponses
Install & Compatibility
Where this runs
tested against v0.7.8 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.930 runs
installs and imports cleanly · install 0.0s · import 0.810s · 28.2MB
glibc
py 3.103.930 runs
installs and imports cleanly · install 3.9s · import 0.710s · 30MB
28MB installed
● package 28MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

aioresponses
from aioresponses import aioresponses

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.

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())
Debug
Known issues
breakingVersion 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.
fix
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`.
affects: >=0.4.0
breakingVersion 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.
fix
Update any code that directly accesses or expects the old class or attribute names to use the new `RequestMatch`, `RequestCall`, and `_matches` names respectively.
affects: >=0.5.0
gotchaPrior 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.
fix
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.
affects: <0.5.0
gotchaThe `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.
fix
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.
affects: All versions
gotchaThe `aioresponses` context manager object (e.g., `m` in `with aioresponses() as m:`) does not expose a `.called` attribute similar to `unittest.mock.Mock` objects. Attempting to access it will raise an `AttributeError`.
fix
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()`).
affects: All versions
gotchaThe `aioresponses` context manager (or fixture) does not have a top-level `called` attribute to check if any mock was activated. Attempts to access `m.called` will raise an `AttributeError`. Instead, inspect the `history` attribute (available from `aioresponses >= 0.6.0`) or specific mock objects (e.g., `m.get(...).called`) to determine if requests were made and matched.
fix
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.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'aioresponses'
The 'aioresponses' package is not installed in the Python environment.
fix
Install the package using pip: 'pip install aioresponses'.
ImportError: cannot import name 'aioresponses' from 'aioresponses'
Incorrect import statement; 'aioresponses' is a class within the 'aioresponses' module.
fix
Use the correct import: 'from aioresponses import aioresponses'.
TypeError: 'aioresponses' object is not callable
Attempting to call 'aioresponses' directly without using it as a decorator or context manager.
fix
Use 'aioresponses' as a decorator: '@aioresponses()' or as a context manager: 'with aioresponses() as m:'.
AttributeError: 'aioresponses' object has no attribute 'get'
Trying to use HTTP methods like 'get' directly on the 'aioresponses' object without proper setup.
fix
Ensure 'aioresponses' is used as a decorator or within a context manager, and that HTTP methods are mocked correctly within that scope.
RuntimeError: This event loop is already running
Calling 'asyncio.run()' or 'loop.run_until_complete()' inside an already running event loop, often in interactive environments like Jupyter notebooks.
fix
Use 'await' directly in async functions or use 'nest_asyncio' to allow nested event loops in interactive environments.
Upgrade
Version history
0.7.8latest on PyPI
Audit
Dependencies
aiohttprequiredaioresponses mocks requests made by aiohttp.ClientSession, so aiohttp is a fundamental dependency for its usage context and is explicitly required by the library.
Agent activity
90 hits · last 30 days
node
12
amazonbot
4
seranking-bot
4
ahrefsbot
3
Amazon
1
petalbot
1
Resources