HTTPretty

1.1.4 · active · verified Fri Apr 10

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

Install

Imports

Quickstart

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()

view raw JSON →