Registry / testing / httpretty

httpretty

JSON →
library1.1.4pypypi✓ verified 23d ago

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 httpretty
INSTALL
IMPORT
SIG · HTTPRETTY
H
httpretty
testingpythonv1.1.4
Install
2.4s avg
Import
192ms
Disk
17MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.1.4 · 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.202s · 19.3MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.4s · import 0.182s · 20MB
17MB installed
● package 17MB
Code
Verified usage

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

httpretty
import httpretty

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.

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()
Debug
Known issues
breakingHTTPretty dropped support for Python 2 in version 1.0.0. Projects still on Python 2 must use an older version.
fix
Upgrade to Python 3 or pin httpretty to a version less than 1.0.0.
affects: <1.0.0 to 1.0.0+
gotchaFailing 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.
fix
Use the `@httpretty.activate` decorator for unit tests or ensure `httpretty.enable()` is paired with `httpretty.disable()` in a controlled scope.
affects: All versions
gotchaURL 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`.
fix
Ensure exact URL matching or use regular expressions (e.g., `re.compile(r'http://example.com/api/data/?')`) for more flexible matching.
affects: All versions
breakingHTTPretty 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.
fix
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.
affects: 1.1.x with urllib3>=2.3.0
gotchaIn 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.
fix
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.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'httpretty'
The 'httpretty' package is not installed in the Python environment where the code is being executed.
fix
Install httpretty using pip: `pip install httpretty`
httpretty.errors.UnmockedError: Failed to socket.connect because a real socket does not exist (no requests made to 'http://example.com/')
This error occurs when `httpretty` is active with `allow_net_connect=False` (the default when using `@httpretty.activate` or `httpretty.enable()`) and an HTTP request is made to a URL that has not been registered with `httpretty.register_uri()`.
fix
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)`.
TypeError: wrap_socket() missing 1 required positional argument: 'sock'
This error often arises from compatibility issues between `httpretty` and specific versions of `urllib3` or Python, particularly when using regular expressions in `register_uri` or due to changes in how `ssl.wrap_socket` expects arguments.
fix
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.
ConnectionRefusedError: [Errno 111] Connection refused
This error can occur when `httpretty` is enabled (e.g., using `@httpretty.activate`) but a request is made to an unregistered URI while `allow_net_connect` is `True`, causing `httpretty` to attempt a real network connection which then fails. It can also happen due to conflicts with other libraries that monkey-patch sockets or if an external service is genuinely unavailable when `httpretty` passes the request through.
fix
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.
Upgrade
Version history
1.1.4latest on PyPI · released Aug 16, 2021
Audit
Dependencies
requestsoptionalCommonly used HTTP client library in examples and real-world usage with httpretty.
urllib3requiredHTTPretty interacts at the socket level, and urllib3 is a fundamental HTTP client that many libraries (including requests) build upon. Recent versions (>=2.3.0) have known incompatibilities.
sureoptionalUsed in some official examples for fluent assertions.
Agent activity
7 hits · last 30 days
node
6
Resources
httpretty — pip install httpretty · libregistry