pytest-httpx
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
- breaking Versions prior to 1.0.0 are subject to breaking changes without notice. Users should review the `CHANGELOG.md` when upgrading between minor versions, especially before 0.31.0 where significant behavioral changes occurred.
- gotcha By default, `pytest-httpx` asserts that all issued HTTPX requests were matched by a registered response. If your test intentionally issues requests that are not meant to be mocked (e.g., to external services), this will cause a test failure.
- gotcha By default, `pytest-httpx` asserts that all registered responses were requested during test execution. If you register responses that are optional and might not be used in every test run, this will cause a test failure.
- breaking Prior to version `0.31.0`, the last registered matching response would be reused indefinitely. Since `0.31.0`, responses are no longer reused by default if all matching responses have already been sent, to help spot regressions where requests are issued more times than expected.
- deprecated The `non_mocked_hosts` option for specifying hosts that should not be mocked has been removed.
- breaking The expected return type for callbacks registered with `add_callback` changed significantly.
Install
-
pip install pytest-httpx
Imports
- httpx_mock
from pytest_httpx import httpx_mock
- HTTPXMock
from pytest_httpx import HTTPXMock
Quickstart
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