HTTMock
HTTMock is a Python library designed for mocking the 'requests' library, enabling developers to simulate third-party API responses and test internal components that rely on HTTP interactions. The current version is 1.4.0, released in October 2020. While functional, its release cadence is slow, suggesting a mature but less actively developed project.
Warnings
- gotcha The `httmock` library (patrys/httmock) has not seen updates since October 2020. While it specifies Python 2.7 and 3.4+ support, compatibility with newer Python versions (e.g., 3.9+) or very recent releases of the `requests` library may be untested or have subtle, undocumented issues.
- gotcha There are multiple HTTP mocking libraries across different languages (Rust, Go, Node.js) that share similar names like 'httpmock'. Ensure you are referencing documentation and examples specifically for the Python `httmock` library (github.com/patrys/httmock).
- gotcha `HTTMock` is designed to be used as a context manager (e.g., `with HTTMock(...)`). Not using it as such, or failing to properly manage its scope, can lead to mocks persisting longer than intended, interfering with other tests, or causing unexpected behavior in your application.
Install
-
pip install httmock
Imports
- HTTMock
from httmock import HTTMock
- urlmatch
from httmock import urlmatch
- all_requests
from httmock import all_requests
- response
from httmock import response
Quickstart
from httmock import urlmatch, HTTMock
import requests
@urlmatch(netloc=r'(.*\.)?example\.com$')
def example_mock(url, request):
"""Mocks requests to example.com."""
print(f"Mocking request to: {url.geturl()} with method {request.method}")
if request.path == '/data' and request.method == 'GET':
return {'status': 'success', 'data': 'mocked content'}
return {'status': 'error', 'message': 'Not found'}
# Use HTTMock as a context manager
with HTTMock(example_mock):
# This request will be intercepted by example_mock
r = requests.get('http://example.com/data')
print(f"Response from mocked URL: {r.json()}")
# This request will also be intercepted, but return 'Not found'
r_post = requests.post('https://www.example.com/other')
print(f"Response from another mocked URL: {r_post.json()}")
# This request will NOT be mocked and will go to the actual internet
r_google = requests.get('http://google.com/')
print(f"Response from real Google (status: {r_google.status_code})")