Registry / testing / httmock

httmock

JSON →
library1.4.0pypypi✓ verified 23d ago

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.

pip install httmock
INSTALL
IMPORT
SIG · HTTMOCK
H
httmock
testingpythonv1.4.0
Install
2.1s avg
Import
351ms
Disk
19MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.4.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.364s · 21.1MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.1s · import 0.338s · 22MB
19MB installed
● package 19MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

HTTMock
from httmock import HTTMock
urlmatch
from httmock import urlmatch
all_requests
from httmock import all_requests
response
from httmock import response

This quickstart demonstrates how to use `httmock` with the `urlmatch` decorator to intercept and respond to HTTP requests made by the `requests` library. The `HTTMock` context manager ensures that the mock is active only for the duration of the `with` block.

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})")
Debug
Known issues
gotchaThe `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.
fix
Thoroughly test `httmock` with your specific Python and `requests` versions. Consider alternative mocking libraries like `requests-mock` or `respx` if you encounter compatibility problems with newer environments.
affects: 1.4.0
gotchaThere 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).
fix
Always verify the library's GitHub repository or PyPI page to confirm it's the correct Python `httmock` (patrys/httmock).
affects: All
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.
fix
Always wrap your mocked HTTP requests within a `with HTTMock(...)` block to ensure mocks are applied and cleaned up correctly, limiting their scope to the test or function where they are needed.
affects: All
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'httmock'
The `httmock` library is not installed in the Python environment where the code is being run.
fix
Install the library using pip: `pip install httmock`
AttributeError: 'NoneType' object has no attribute 'read'
This error typically occurs when an `httmock` handler returns a dictionary or other non-streamable object, and the client code (e.g., using `requests.iter_lines()`) attempts to access a stream-like attribute (`read`) that is not available on the mocked response.
fix
Ensure that your `httmock` handler returns a properly constructed `requests.Response` object or a dictionary that `httmock` can fully convert, especially if the client code expects streamable content. If directly returning a dictionary, ensure it contains sufficient keys for `httmock` to build a complete response object, or return a `response` object using `httmock.response` with appropriate content.
TypeError: Dont know how to handle response of type <class '...'>
This error indicates that an `httmock` handler function returned an object type that `httmock` does not know how to convert into a mockable HTTP response (expected types include `requests.Response`, `dict`, `str`, or `bytes`).
fix
Modify the `httmock` handler to return one of the supported types: a `requests.Response` object, a dictionary representing the response, a string for the content, or bytes for the content. For example, `return {'status_code': 200, 'content': 'Hello'}` or `return httmock.response(200, 'Hello')`.
requests.exceptions.ConnectionError: HTTPConnectionPool(host='...', port=...): Max retries exceeded with url: / (Caused by <class 'socket.gaierror'>: [Errno 8] nodename nor servname provided, or not known)
This `requests` library error occurs when `httmock` fails to intercept an HTTP request, causing the request to be sent to a real (and often non-existent or unreachable) network location, typically because the `urlmatch` pattern did not match or the `HTTMock` context was not active.
fix
Verify that your `urlmatch` pattern correctly matches the URL being requested. Ensure that the `HTTMock` context manager (`with HTTMock(my_mock_handler):`) or decorator (`@with_httmock(my_mock_handler)`) is active and encompasses the `requests` call you intend to mock.
Upgrade
Version history
1.4.0latest on PyPI · released Oct 28, 2020
Audit
Dependencies
requestsrequiredHTTMock is a mocking library specifically designed for the 'requests' HTTP library, making 'requests' a functional dependency for its intended use.
Agent activity
9 hits · last 30 days
node
8
Resources