respx - HTTPX Mocking Utility
respx is a powerful and flexible utility for mocking out the Python HTTPX and HTTP Core libraries, essential for writing fast and reliable tests for applications that make HTTP requests. It allows developers to intercept HTTP requests and provide predefined responses. The library is actively maintained with frequent releases, currently at version 0.23.1, often updating to align with new HTTPX versions.
Warnings
- breaking respx dropped support for Python 3.7 in version 0.22.0 to align with HTTPX 0.25.0. Projects using Python 3.7 must pin respx to <0.22.0.
- breaking Since version 0.20.0, `Call.response` and `CallList.last` now raise an `AttributeError` (or similar for missing calls) instead of returning `None` if a response or call is not found. This changes the expected behavior for type-hinted code or code implicitly handling `None`.
- gotcha A regression in version 0.23.0 caused `params` pattern matching to stop working under some conditions, especially with `ANY` in multi-item patterns. This was fixed in 0.23.1.
- gotcha Prior to version 0.23.0, the `ANY` wildcard in `MultiItems` patterns (used for headers, params, or data with multiple values) might not have been handled properly, potentially leading to unexpected mismatches.
- gotcha Before version 0.21.0, direct matching on `files` (multipart/form-data uploads) was not officially supported and might have required custom workarounds. The `files` pattern was added in 0.21.0.
- gotcha Combining the `@respx.mock` decorator with `pytest` fixtures prior to version 0.19.3 could sometimes lead to unexpected behavior or conflicts, such as the mock not being active or pytest's function wrapping being incorrect.
Install
-
pip install respx
Imports
- respx
import respx
- Response
from httpx import Response
- mock (decorator)
@respx.mock
- ANY
from respx import ANY
Quickstart
import respx
import httpx
from httpx import Response
@respx.mock
def test_mocked_api_call():
# Define a mock response for a GET request to a specific URL
respx.get("https://api.example.com/users/1")\
.mock(return_value=Response(200, json={
"id": 1,
"name": "Jane Doe",
"email": "jane.doe@example.com"
}))
# Make the actual HTTPX request, which will be intercepted by respx
response = httpx.get("https://api.example.com/users/1")
# Assertions to verify the mocked response
assert response.status_code == 200
assert response.json()["name"] == "Jane Doe"
print(f"Mocked response received: {response.json()}")
# Verify that the mock was called
assert respx.calls.call_count == 1
assert respx.calls.called
if __name__ == '__main__':
print("Running mocked API call example...")
test_mocked_api_call()
print("Example finished successfully.")