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-httpxVerified import paths — ran on the pinned version, not inferred.
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.
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.
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.
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.
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.
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)`.
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.
Install the library using pip: `pip install pytest-httpx`
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.
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.