urllib3-mock
A utility library for mocking out the `urllib3` Python library. It allows intercepting HTTP requests made by `urllib3` and returning predefined responses for testing or development. The current version is 0.3.3, and the library appears to be abandoned, with no updates since 2017.
Common errors
-
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(...) Max retries exceeded with url: ... (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at ...>: Failed to establish a new connection: [Errno 111] Connection refused'))cause The `urllib3` request was not intercepted by `urllib3-mock` because no matching mock response was active or configured for the specific URL and HTTP method.fixVerify that the URL, HTTP method (GET, POST, PUT, etc.), and any required headers in your `@responses.add` configuration exactly match the outgoing `urllib3` request. Also, ensure the mock context is active (either via a called decorator or `responses.start()/stop()`). -
AssertionError: Expected the request to be mocked, but it went to the network.
cause The test or application code making the `urllib3` request did not execute within the active scope of the `urllib3-mock` `Responses` instance.fixIf using decorators, ensure the decorated function is explicitly called. If using `responses.start()`/`responses.stop()`, verify that the `urllib3` request is made between these calls or within a `with responses:` block.
Warnings
- deprecated The `urllib3-mock` library is no longer actively maintained, with the last commit and release (v0.3.3) dating back to 2017. Users should be aware of potential compatibility issues with newer Python versions or `urllib3` versions.
- gotcha This library specifically hooks into `urllib3` directly. While `requests` uses `urllib3` internally, `urllib3-mock` might not always intercept requests made via the `requests` library in the way you expect, especially with more complex `requests` features.
- gotcha When using decorators (e.g., `@responses.add`), the decorated function *must* be explicitly called for the mock to become active and intercept requests. If the function is not called, the `urllib3` request will go to the actual network.
Install
-
pip install urllib3-mock
Imports
- Responses
from urllib3_mock import Responses
Quickstart
from urllib3_mock import Responses
import urllib3
# Create an instance of Responses
responses = Responses()
@responses.add('GET', 'http://example.com/', body='hello world')
def test_mocked_request():
"""This function contains the urllib3 call that will be mocked."""
http = urllib3.PoolManager()
r = http.request('GET', 'http://example.com/')
print(f"Received: {r.data.decode('utf-8')}")
assert r.data == b'hello world'
# It's crucial to call the decorated function to execute the mocked request
test_mocked_request()