Registry / testing / pytest-httpx

pytest-httpx

JSON →
library0.36.2pypypi✓ verified 26d ago

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.

pip install pytest-httpx
INSTALL
IMPORT
SIG · PYTEST-HTTPX
P
pytest-httpx
testingpythonv0.36.2
Install
3.3s avg
Import
667ms
Disk
34MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.36.2 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.702s · 34.8MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 3.3s · import 0.632s · 35MB
34MB installed
● package 34MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

httpx_mock
from pytest_httpx import httpx_mock
The primary pytest fixture for mocking HTTPX requests.
HTTPXMock
from pytest_httpx import HTTPXMock
Primarily used for type hinting the `httpx_mock` fixture.

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
Debug
Known issues
breakingVersions 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.
fix
Always consult the `CHANGELOG.md` on the GitHub repository when upgrading to understand potential breaking changes. Pay close attention to changes in assertion defaults and callback signatures.
affects: <1.0.0
gotchaBy 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.
fix
To disable this assertion for specific tests or modules, use the `pytest.mark.httpx_mock(assert_all_requests_were_expected=False)` marker. For selective mocking, consider the `should_mock` parameter.
affects: >=0.31.0
gotchaBy 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.
fix
To mark a specific response as optional, set `is_optional=True` when calling `add_response`. To disable this assertion globally for a test, use the `pytest.mark.httpx_mock(assert_all_responses_were_requested=False)` marker.
affects: >=0.31.0
breakingPrior 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.
fix
If you require the old behavior where the last matching response is reused, use the `pytest.mark.httpx_mock(can_send_already_matched_responses=True)` marker.
affects: >=0.31.0
deprecatedThe `non_mocked_hosts` option for specifying hosts that should not be mocked has been removed.
fix
Use the `should_mock` parameter in `pytest.mark.httpx_mock` instead. This parameter expects a callable that takes an `httpx.Request` object and returns `True` if the request should be mocked, or `False` if it should pass through unmocked. Example: `pytest.mark.httpx_mock(should_mock=lambda request: 'my_local_test_host' not in request.url.host)`.
affects: <0.31.0 (removed in 0.31.0)
breakingThe expected return type for callbacks registered with `add_callback` changed significantly.
fix
Before `0.20.0`, callbacks were expected to return a tuple representing the HTTP response. As of `0.20.0` and later, callbacks are expected to return an `httpx.Response` instance directly.
affects: <0.20.0
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'pytest_httpx'
The 'pytest-httpx' package is not installed in the Python environment where pytest is being executed.
fix
Install the library using pip: `pip install pytest-httpx`
httpx.ConnectError: [Errno 111] Connection refused
The `pytest-httpx` mock was not successfully applied or an actual network request was attempted because the mock did not intercept the call. This often happens if the `httpx_mock` fixture is not passed to the test function, or if the HTTPX client instance used by the test subject is not the one being mocked.
fix
Ensure `httpx_mock` is a parameter in your test function (`def test_something(httpx_mock):`) and that you have defined expectations using `httpx_mock.add_response()` or `httpx_mock.expect_request()` *before* the application code makes the HTTPX call.
AssertionError: Expected 1 call to GET https://example.com/api but 0 were made.
The HTTP request made by the code under test did not match the expectations set with `httpx_mock.expect_request()` (e.g., incorrect URL, method, headers, or body), or the request was simply not executed.
fix
Verify that the URL, HTTP method, headers, and request body in your application code's `httpx` call exactly match the parameters provided to `httpx_mock.expect_request()`. Also, confirm that the code path leading to the HTTP request is actually exercised during the test.
Upgrade
Version history
0.36.2latest on PyPI · released Apr 9, 2026
Audit
Dependencies
httpxrequiredCore HTTP client library that pytest-httpx mocks. Requires >=0.28.
pytestrequiredTesting framework that pytest-httpx extends. Requires >=3.10 (for Python compatibility) and implicitly a modern pytest version (e.g., >=5.4.0 mentioned in older changelogs).
pytest-asynciooptionalRequired for asynchronous test functions if not using pytest's native async support.
Agent activity
9 hits · last 30 days
node
6
Amazon
1
Resources
pytest-httpx — pip install pytest-httpx · libregistry