aioresponses

0.7.8 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

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())

view raw JSON →