HTTMock

1.4.0 · active · verified Fri Apr 10

HTTMock is a Python library designed for mocking the 'requests' library, enabling developers to simulate third-party API responses and test internal components that rely on HTTP interactions. The current version is 1.4.0, released in October 2020. While functional, its release cadence is slow, suggesting a mature but less actively developed project.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `httmock` with the `urlmatch` decorator to intercept and respond to HTTP requests made by the `requests` library. The `HTTMock` context manager ensures that the mock is active only for the duration of the `with` block.

from httmock import urlmatch, HTTMock
import requests

@urlmatch(netloc=r'(.*\.)?example\.com$')
def example_mock(url, request):
    """Mocks requests to example.com."""
    print(f"Mocking request to: {url.geturl()} with method {request.method}")
    if request.path == '/data' and request.method == 'GET':
        return {'status': 'success', 'data': 'mocked content'}
    return {'status': 'error', 'message': 'Not found'}

# Use HTTMock as a context manager
with HTTMock(example_mock):
    # This request will be intercepted by example_mock
    r = requests.get('http://example.com/data')
    print(f"Response from mocked URL: {r.json()}")

    # This request will also be intercepted, but return 'Not found'
    r_post = requests.post('https://www.example.com/other')
    print(f"Response from another mocked URL: {r_post.json()}")

    # This request will NOT be mocked and will go to the actual internet
    r_google = requests.get('http://google.com/')
    print(f"Response from real Google (status: {r_google.status_code})")

view raw JSON →