HTTPretty is an HTTP client mocking tool for Python (current version 1.1.4) that works by monkey-patching the standard library's `socket` and `ssl` modules. This allows it to intercept HTTP requests at a low level, faking responses for any HTTP client that relies on these modules, such as `requests` or `urllib3`. It is suitable for testing API integrations and handling external service dependencies. Releases are somewhat irregular but include bug fixes and Python version support updates.
pip install httprettyVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to use the `@httpretty.activate` decorator to mock an HTTP GET request to `http://example.com/api/data`. It registers a URI with a specific JSON response body and status code, then uses the `requests` library to make the call. Assertions verify both the received response and properties of the intercepted request. The `allow_net_connect=False` argument prevents accidental real network connections during tests.
Upgrade to Python 3 or pin httpretty to a version less than 1.0.0.
Use the `@httpretty.activate` decorator for unit tests or ensure `httpretty.enable()` is paired with `httpretty.disable()` in a controlled scope.
Ensure exact URL matching or use regular expressions (e.g., `re.compile(r'http://example.com/api/data/?')`) for more flexible matching.
Pin `urllib3` to a version less than 2.3.0 (e.g., `<2.3.0`) or consider alternative mocking libraries if this is a blocker.
Verify that your specific HTTP client library and usage pattern are compatible with httpretty's monkey-patching. This may require reviewing `httpretty`'s issue tracker for known client-specific incompatibilities.
Install httpretty using pip: `pip install httpretty`
Register the URI that is being requested or set `allow_net_connect=True` when enabling httpretty: `httpretty.register_uri(httpretty.GET, "http://example.com/", body="mocked response")` or `@httpretty.activate(allow_net_connect=True)`.
Ensure you are using a compatible version of `urllib3` (e.g., downgrade `urllib3` if it's too new, or upgrade `httpretty` if a fix exists). When using regex, ensure the pattern is correctly formed and `httpretty` can handle it, sometimes explicitly including `http://` or `https://` in the regex helps, or in some cases, a specific bug fix might be required from the library itself.
Explicitly register all URIs that your code will hit, especially when `httpretty.activate(allow_net_connect=False)` is used. If you intend to allow real network connections, ensure the target service is running and accessible. If conflicts arise with other socket-manipulating libraries, consider isolating `httpretty`'s activation and deactivation or checking for known incompatibilities.