pytest-httpx

0.36.0 · active · verified Thu Apr 09

pytest-httpx is a pytest fixture that provides a convenient way to mock HTTPX requests within test cases. It supports both synchronous and asynchronous HTTPX requests, allowing developers to define custom responses, status codes, headers, and simulate various HTTP conditions without making actual network calls. The library is currently at version 0.36.0 and is considered stable, with version 1.0.0 planned for release once HTTPX itself reaches 1.0.0.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the `httpx_mock` fixture to intercept and provide mocked responses for both synchronous and asynchronous HTTPX requests within pytest. It shows how to add a JSON response for a GET request and a status code for a POST request.

import pytest
import httpx
from pytest_httpx import httpx_mock, HTTPXMock # HTTPXMock for type hinting

def test_sync_request_mocking(httpx_mock: HTTPXMock):
    httpx_mock.add_response(url="https://example.com/api/items", json={"data": ["item1", "item2"]})

    with httpx.Client() as client:
        response = client.get("https://example.com/api/items")

    assert response.status_code == 200
    assert response.json() == {"data": ["item1", "item2"]}

@pytest.mark.asyncio
async def test_async_request_mocking(httpx_mock: HTTPXMock):
    httpx_mock.add_response(url="https://example.com/api/async-items", status_code=201)

    async with httpx.AsyncClient() as client:
        response = await client.post("https://example.com/api/async-items", json={"name": "new item"})

    assert response.status_code == 201
    assert not response.content # No content for 201 by default

view raw JSON →