Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]
### Added
- `match_request` parameter is now available on responses, callbacks and exceptions registration, as well as request(s) retrieval. It expects a callable receiving the `httpx.Request` and returning a boolean. It is combined with the other match parameters: all of them must match. This allows matching on conditions such as the absence of a header ([refer to documentation](README.md#matching-with-a-custom-matcher) for more information).
- Explicit support for python `3.15`.

### Fixed
Expand Down
24 changes: 23 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ def test_headers_matching(httpx_mock: HTTPXMock):
response = client.get("https://test_url")
```

[^header-absence]: Matching on the absence of a header is currently not supported. [Retrieve the request](#check-sent-requests) after it is sent and assert that the header is absent from `request.headers`.
[^header-absence]: `match_headers` matches provided headers on equality and cannot express the absence of a header. Use a [custom matcher](#matching-with-a-custom-matcher) for that.

#### Matching on HTTP body

Expand Down Expand Up @@ -340,6 +340,28 @@ def test_timeout_matching(httpx_mock: HTTPXMock):
response = client.get("https://test_url", timeout=10)
```

#### Matching with a custom matcher

Use `match_request` to provide your own matching logic.

`match_request` must be a callable expecting the [`httpx.Request`](https://www.python-httpx.org/api/#request) as parameter and returning a boolean.

Returning `True` means that the request matches. The callable is used in addition to the other match parameters, and all of them have to match.

For instance, to reply only when a header is absent:

```python
import httpx
from pytest_httpx import HTTPXMock


def test_header_absence(httpx_mock: HTTPXMock):
httpx_mock.add_response(match_request=lambda request: "X-Foo" not in request.headers)

with httpx.Client() as client:
response = client.get("https://test_url")
```

### Add JSON response

Use `json` parameter to add a JSON response using python values.
Expand Down
5 changes: 5 additions & 0 deletions pytest_httpx/_httpx_mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ def add_response(
:param match_files: Multipart files identifying the request(s) to match. Refer to httpx documentation for more information on supported values: https://www.python-httpx.org/advanced/clients/#multipart-file-encoding
:param match_extensions: Extensions identifying the request(s) to match. Must be a dictionary.
:param match_params: Query string parameters identifying the request(s) to match (if not provided as part of URL already). Must be a dictionary with str keys (parameter name) and str, bool, int or float values (or a list of values if parameter is provided more than once).
:param match_request: Custom matcher identifying the request(s) to match. Must be a callable expecting one parameter, the received httpx.Request, and returning a boolean. It is used in addition to the other match parameters, all of them must match.
:param is_optional: True will mark this response as optional, False will expect a request matching it. Must be a boolean. Default to the opposite of assert_all_responses_were_requested option value (itself defaulting to True, meaning this parameter default to False).
:param is_reusable: True will allow re-using this response even if it already matched, False prevent re-using it. Must be a boolean. Default to the can_send_already_matched_responses option value (itself defaulting to False).
"""
Expand Down Expand Up @@ -113,6 +114,7 @@ def add_callback(
:param match_files: Multipart files identifying the request(s) to match. Refer to httpx documentation for more information on supported values: https://www.python-httpx.org/advanced/clients/#multipart-file-encoding
:param match_extensions: Extensions identifying the request(s) to match. Must be a dictionary.
:param match_params: Query string parameters identifying the request(s) to match (if not provided as part of URL already). Must be a dictionary with str keys (parameter name) and str, bool, int or float values (or a list of values if parameter is provided more than once).
:param match_request: Custom matcher identifying the request(s) to match. Must be a callable expecting one parameter, the received httpx.Request, and returning a boolean. It is used in addition to the other match parameters, all of them must match.
:param is_optional: True will mark this callback as optional, False will expect a request matching it. Must be a boolean. Default to the opposite of assert_all_responses_were_requested option value (itself defaulting to True, meaning this parameter default to False).
:param is_reusable: True will allow re-using this callback even if it already matched, False prevent re-using it. Must be a boolean. Default to the can_send_already_matched_responses option value (itself defaulting to False).
"""
Expand All @@ -135,6 +137,7 @@ def add_exception(self, exception: BaseException, **matchers: Any) -> None:
:param match_files: Multipart files identifying the request(s) to match. Refer to httpx documentation for more information on supported values: https://www.python-httpx.org/advanced/clients/#multipart-file-encoding
:param match_extensions: Extensions identifying the request(s) to match. Must be a dictionary.
:param match_params: Query string parameters identifying the request(s) to match (if not provided as part of URL already). Must be a dictionary with str keys (parameter name) and str, bool, int or float values (or a list of values if parameter is provided more than once).
:param match_request: Custom matcher identifying the request(s) to match. Must be a callable expecting one parameter, the received httpx.Request, and returning a boolean. It is used in addition to the other match parameters, all of them must match.
:param is_optional: True will mark this exception response as optional, False will expect a request matching it. Must be a boolean. Default to the opposite of assert_all_responses_were_requested option value (itself defaulting to True, meaning this parameter default to False).
:param is_reusable: True will allow re-using this exception response even if it already matched, False prevent re-using it. Must be a boolean. Default to the can_send_already_matched_responses option value (itself defaulting to False).
"""
Expand Down Expand Up @@ -296,6 +299,7 @@ def get_requests(self, **matchers: Any) -> list[httpx.Request]:
:param match_files: Multipart files identifying the requests to retrieve. Refer to httpx documentation for more information on supported values: https://www.python-httpx.org/advanced/clients/#multipart-file-encoding
:param match_extensions: Extensions identifying the requests to retrieve. Must be a dictionary.
:param match_params: Query string parameters identifying the requests to retrieve (if not provided as part of URL already). Must be a dictionary with str keys (parameter name) and str, bool, int or float values (or a list of values if parameter is provided more than once).
:param match_request: Custom matcher identifying the requests to retrieve. Must be a callable expecting one parameter, the received httpx.Request, and returning a boolean. It is used in addition to the other match parameters, all of them must match.
"""
matcher = _RequestMatcher(self._options, **matchers)
return [
Expand All @@ -320,6 +324,7 @@ def get_request(self, **matchers: Any) -> httpx.Request | None:
:param match_files: Multipart files identifying the request to retrieve. Refer to httpx documentation for more information on supported values: https://www.python-httpx.org/advanced/clients/#multipart-file-encoding
:param match_extensions: Extensions identifying the request to retrieve. Must be a dictionary.
:param match_params: Query string parameters identifying the request to retrieve (if not provided as part of URL already). Must be a dictionary with str keys (parameter name) and str, bool, int or float values (or a list of values if parameter is provided more than once).
:param match_request: Custom matcher identifying the request to retrieve. Must be a callable expecting one parameter, the received httpx.Request, and returning a boolean. It is used in addition to the other match parameters, all of them must match.
:raises AssertionError: in case more than one request match.
"""
requests = self.get_requests(**matchers)
Expand Down
16 changes: 15 additions & 1 deletion pytest_httpx/_request_matcher.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import json
import re
from collections.abc import Sequence
from collections.abc import Callable, Sequence
from re import Pattern
from typing import Any
from unittest.mock import ANY
Expand Down Expand Up @@ -75,6 +75,7 @@ def __init__(
match_files: Any | None = None,
match_extensions: dict[str, Any] | None = None,
match_params: dict[str, PrimitiveData | Sequence[PrimitiveData]] | None = None,
match_request: Callable[[httpx.Request], bool] | None = None,
is_optional: bool | None = None,
is_reusable: bool | None = None,
):
Expand All @@ -88,6 +89,7 @@ def __init__(
self.data = match_data
self.files = match_files
self.params = match_params
self.match_request = match_request
self.proxy_url = (
httpx.URL(proxy_url)
if proxy_url and isinstance(proxy_url, str)
Expand Down Expand Up @@ -167,6 +169,7 @@ def match(
and self._content_match(request)
and self._proxy_match(real_transport)
and self._extensions_match(request)
and self._match_request(request)
)

def _url_match(self, request: httpx.Request) -> bool:
Expand Down Expand Up @@ -248,6 +251,12 @@ def _extensions_match(self, request: httpx.Request) -> bool:
for extension_name, extension_value in self.extensions.items()
)

def _match_request(self, request: httpx.Request) -> bool:
if self.match_request is None:
return True

return self.match_request(request)

def should_have_matched(self) -> bool:
"""Return True if the matcher did not serve its purpose."""
return not self.is_optional and not self.nb_calls
Expand Down Expand Up @@ -283,5 +292,10 @@ def _extra_description(self) -> str:
extra_description.append(f"{self.proxy_url} proxy URL")
if self.extensions:
extra_description.append(f"{self.extensions} extensions")
if self.match_request is not None:
name = getattr(
self.match_request, "__name__", type(self.match_request).__name__
)
extra_description.append(f"custom matcher {name}")

return " and ".join(extra_description)
123 changes: 123 additions & 0 deletions tests/test_httpx_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -2864,3 +2864,126 @@ async def test_multi_response_matched_twice(httpx_mock: HTTPXMock) -> None:
response2 = await client.get("https://test_url")
assert response1.content == b""
assert response2.content == b""


@pytest.mark.asyncio
async def test_custom_matcher_matching(httpx_mock: HTTPXMock) -> None:
httpx_mock.add_response(
match_request=lambda request: "X-Foo" not in request.headers,
json={"ok": True},
)

async with httpx.AsyncClient() as client:
response = await client.get("https://test_url")
assert response.json() == {"ok": True}


@pytest.mark.asyncio
@pytest.mark.httpx_mock(assert_all_requests_were_expected=False)
async def test_custom_matcher_not_matching(httpx_mock: HTTPXMock) -> None:
httpx_mock.add_response(
match_request=lambda request: "X-Foo" not in request.headers,
is_optional=True,
)

async with httpx.AsyncClient() as client:
with pytest.raises(httpx.TimeoutException) as exception_info:
await client.get("https://test_url", headers={"X-Foo": "bar"})
assert (
str(exception_info.value)
== """No response can be found for GET request on https://test_url amongst:
- Match any request with custom matcher <lambda>"""
)


@pytest.mark.asyncio
async def test_custom_matcher_combined_with_other_matchers(
httpx_mock: HTTPXMock,
) -> None:
httpx_mock.add_response(
url="https://test_url",
method="GET",
match_request=lambda request: "X-Foo" not in request.headers,
json={"matched": True},
)
httpx_mock.add_response(
url="https://test_url", method="GET", json={"matched": False}
)

async with httpx.AsyncClient() as client:
response = await client.get("https://test_url")
assert response.json() == {"matched": True}

response = await client.get("https://test_url", headers={"X-Foo": "bar"})
assert response.json() == {"matched": False}


@pytest.mark.asyncio
@pytest.mark.httpx_mock(assert_all_requests_were_expected=False)
async def test_custom_matcher_with_other_matchers_not_matching(
httpx_mock: HTTPXMock,
) -> None:
httpx_mock.add_response(
url="https://test_url",
method="POST",
match_headers={"X-Other": "yes"},
match_request=lambda request: "X-Foo" not in request.headers,
is_optional=True,
)

async with httpx.AsyncClient() as client:
with pytest.raises(httpx.TimeoutException) as exception_info:
await client.get("https://test_url", headers={"X-Other": "yes"})
assert (
str(exception_info.value)
== """No response can be found for GET request on https://test_url with {'X-Other': 'yes'} headers amongst:
- Match POST request on https://test_url with {'X-Other': 'yes'} headers and custom matcher <lambda>"""
)


@pytest.mark.asyncio
async def test_custom_matcher_request_retrieval(httpx_mock: HTTPXMock) -> None:
httpx_mock.add_response(is_reusable=True)

async with httpx.AsyncClient() as client:
await client.get("https://test_url")
await client.get("https://test_url", headers={"X-Foo": "bar"})

without_header = httpx_mock.get_requests(
match_request=lambda request: "X-Foo" not in request.headers
)
with_header = httpx_mock.get_request(
match_request=lambda request: "X-Foo" in request.headers
)

assert len(without_header) == 1
assert "X-Foo" not in without_header[0].headers
assert with_header is not None
assert with_header.headers["X-Foo"] == "bar"


@pytest.mark.asyncio
async def test_custom_matcher_callback(httpx_mock: HTTPXMock) -> None:
def custom_response(request: httpx.Request) -> httpx.Response:
return httpx.Response(status_code=200, text="matched")

httpx_mock.add_callback(
custom_response,
match_request=lambda request: "X-Foo" not in request.headers,
)

async with httpx.AsyncClient() as client:
response = await client.get("https://test_url")
assert response.text == "matched"


@pytest.mark.asyncio
async def test_custom_matcher_exception(httpx_mock: HTTPXMock) -> None:
httpx_mock.add_exception(
httpx.ReadTimeout("Unable to read within timeout"),
match_request=lambda request: "X-Foo" not in request.headers,
)

async with httpx.AsyncClient() as client:
with pytest.raises(httpx.ReadTimeout):
await client.get("https://test_url")
Loading