respx - HTTPX Mocking Utility

0.23.1 · active · verified Thu Apr 09

respx is a powerful and flexible utility for mocking out the Python HTTPX and HTTP Core libraries, essential for writing fast and reliable tests for applications that make HTTP requests. It allows developers to intercept HTTP requests and provide predefined responses. The library is actively maintained with frequent releases, currently at version 0.23.1, often updating to align with new HTTPX versions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the `@respx.mock` decorator to intercept an HTTPX GET request. It defines a mock response for a specific URL, then performs an HTTPX request that transparently receives the mocked data. Finally, it asserts the response and verifies that the mock was called.

import respx
import httpx
from httpx import Response

@respx.mock
def test_mocked_api_call():
    # Define a mock response for a GET request to a specific URL
    respx.get("https://api.example.com/users/1")\
        .mock(return_value=Response(200, json={
            "id": 1,
            "name": "Jane Doe",
            "email": "jane.doe@example.com"
        }))

    # Make the actual HTTPX request, which will be intercepted by respx
    response = httpx.get("https://api.example.com/users/1")

    # Assertions to verify the mocked response
    assert response.status_code == 200
    assert response.json()["name"] == "Jane Doe"
    print(f"Mocked response received: {response.json()}")

    # Verify that the mock was called
    assert respx.calls.call_count == 1
    assert respx.calls.called

if __name__ == '__main__':
    print("Running mocked API call example...")
    test_mocked_api_call()
    print("Example finished successfully.")

view raw JSON →