aiohttp mock library that routes requests through a real test server
Actively maintained. Last release 7 weeks ago, commits in 24 of the last 26 weeks. A safe choice.
pip install aiointerceptaiointercept
Mock aiohttp HTTP requests by routing them through a real aiohttp.web test server. Inspired by aioresponses, with a largely compatible API.
import aiohttp
from aiointercept import aiointercept
async with aiointercept() as m:
m.get(f"{m.server_url}/users", payload=[{"id": 1}])
async with aiohttp.ClientSession() as session:
resp = await session.get(f"{m.server_url}/users")
assert await resp.json() == [{"id": 1}]
Why aiointercept?
Testing code that makes HTTP requests usually means either hitting a real server (slow, fragile, requires network) or replacing the HTTP layer with fake objects (fast, but disconnected from reality).
aiointercept takes a third path: it starts a real aiohttp.web server on localhost and redirects your client's requests to it — either by pointing the client at m.server_url directly, or by patching the DNS resolver so existing URLs are transparently intercepted. Your code runs its full HTTP stack; only the remote endpoint is replaced.
- Real serialization. Headers, body encoding, and content-type negotiation all go through the actual aiohttp stack.
- Inspectable requests. Callbacks receive a real
aiohttp.web.Request— read the body, headers, and query params the server saw. - Minimal patching. The default mode touches nothing globally. When you need to intercept hardcoded URLs, only the DNS resolver is patched, so redirects and connection pooling still behave as in production.
Using other HTTP clients
With the default mock_external_urls=False, the mock is a plain HTTP server, so , (sync or async), or any other client can call . The server runs on its own thread, so blocking clients work directly from async tests with static responses or synchronous callbacks. When using an async callback, offload the blocking client call so the test's event loop remains available: