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 httmockVerified import paths — ran on the pinned version, not inferred.
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.
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.
Always verify the library's GitHub repository or PyPI page to confirm it's the correct Python `httmock` (patrys/httmock).
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.
Install the library using pip: `pip install httmock`
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.
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')`.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.