aresponses

raw JSON →
3.0.0 verified Fri May 01 auth: no python

Asyncio response mocking library for aiohttp-based code, similar to responses for requests. Version 3.0.0 supports asyncio and aiohttp. Released sporadically.

pip install aresponses
error AttributeError: module 'aresponses' has no attribute 'match'
cause Trying to use old API pattern (aresponses.match) in version 3.0.0.
fix
Use 'ResponsesMockServer' class with 'add' method instead: 'from aresponses import ResponsesMockServer' and use 'server.add(...)'.
error RuntimeError: cannot use async context manager outside of an async function
cause Using 'with ResponsesMockServer()' instead of 'async with' inside an async function.
fix
Change 'with' to 'async with' inside an async function.
gotcha ResponsesMockServer must be used as an async context manager, not a regular context manager. Forgetting 'async with' will cause a RuntimeError.
fix Use 'async with ResponsesMockServer() as server:'
breaking Version 3.0.0 changed the API from the old 'aresponses' function-based approach to the class-based 'ResponsesMockServer'. Old code using 'aresponses.match' or 'aresponses.add' directly no longer works.
fix Replace 'aresponses.match(...)' with 'ResponsesMockServer().add(...)' and use async context manager.
deprecated The 'aresponses' module-level functions like 'aresponses.add' and 'aresponses.match' are removed in 3.0.0. Direct attribute access to 'RequestsMock' is no longer supported.
fix Import 'ResponsesMockServer' and use its async context manager.
gotcha responses (the synchronous library) is sometimes confused with aresponses. Ensure you import from 'aresponses' not 'responses'.
fix Use 'from aresponses import ...'

Basic usage of ResponsesMockServer context manager with aiohttp.

import aiohttp
import asyncio
from aresponses import ResponsesMockServer

async def test_fetch():
    async with aiohttp.ClientSession() as session:
        async with session.get('http://example.com/api') as resp:
            data = await resp.json()
            assert data == {'key': 'value'}

async def main():
    async with ResponsesMockServer() as server:
        server.add('http://example.com/api', 'GET', response={'key': 'value'})
        await test_fetch()

asyncio.run(main())