HTTPretty
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.
Warnings
- breaking HTTPretty dropped support for Python 2 in version 1.0.0. Projects still on Python 2 must use an older version.
- gotcha Failing to disable HTTPretty after tests can lead to unexpected behavior in subsequent code or tests, as it monkey-patches the global socket module. Always use the `@httpretty.activate` decorator for test functions or explicitly call `httpretty.enable()` and `httpretty.disable()` in a `try...finally` block.
- gotcha URL matching with `httpretty.register_uri` can be very strict. Minor differences, such as a missing trailing slash, can prevent the mock from being matched, leading to an `httpretty.errors.UnmockedError` if `allow_net_connect` is `False`.
- breaking HTTPretty has known compatibility issues with `urllib3` versions 2.3.0 and higher when `allow_net_connect=False`. This can lead to `UnmockedError` or other unexpected networking issues, as `httpretty` may fail to intercept requests correctly.
- gotcha In certain scenarios, HTTPretty may not correctly intercept requests made using Python's `http.client.HTTPConnection`, which can lead to `socket.gaierror` (getaddrinfo error) if the real network connection is attempted and fails.
Install
-
pip install httpretty
Imports
- httpretty
import httpretty
Quickstart
import requests
import httpretty
# httpretty monkey-patches the socket module.
# The @httpretty.activate decorator ensures it's enabled for the test function
# and disabled afterwards, isolating the mock.
@httpretty.activate(verbose=False, allow_net_connect=False)
def quickstart_example():
test_url = "http://example.com/api/data"
mock_body = '{"message": "Hello from mock!"}'
# Register a URI to mock with GET method and a JSON body
httpretty.register_uri(
httpretty.GET,
test_url,
body=mock_body,
status=200,
content_type="application/json"
)
# Make a request using a common HTTP client (e.g., requests)
response = requests.get(test_url)
# Assertions on the response
assert response.status_code == 200
assert response.json() == {"message": "Hello from mock!"}
# Assertions on the intercepted request itself
assert httpretty.last_request().method == "GET"
assert httpretty.last_request().path == "/api/data"
print("Mocked request successful!")
# To run the example (e.g., in a script or interactive session)
if __name__ == "__main__":
quickstart_example()