diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c5015b..794be97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index f1fd4e4..7e351e0 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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. diff --git a/pytest_httpx/_httpx_mock.py b/pytest_httpx/_httpx_mock.py index e35ac4f..245e703 100644 --- a/pytest_httpx/_httpx_mock.py +++ b/pytest_httpx/_httpx_mock.py @@ -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). """ @@ -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). """ @@ -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). """ @@ -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 [ @@ -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) diff --git a/pytest_httpx/_request_matcher.py b/pytest_httpx/_request_matcher.py index b73a01f..fd56335 100644 --- a/pytest_httpx/_request_matcher.py +++ b/pytest_httpx/_request_matcher.py @@ -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 @@ -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, ): @@ -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) @@ -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: @@ -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 @@ -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) diff --git a/tests/test_httpx_async.py b/tests/test_httpx_async.py index 8dfa039..951e0f4 100644 --- a/tests/test_httpx_async.py +++ b/tests/test_httpx_async.py @@ -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 """ + ) + + +@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 """ + ) + + +@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") diff --git a/tests/test_httpx_sync.py b/tests/test_httpx_sync.py index da52f61..272d675 100644 --- a/tests/test_httpx_sync.py +++ b/tests/test_httpx_sync.py @@ -2520,3 +2520,134 @@ def test_multi_response_matched_twice(httpx_mock: HTTPXMock) -> None: response2 = client.get("https://test_url") assert response1.content == b"" assert response2.content == b"" + + +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}, + ) + + with httpx.Client() as client: + response = client.get("https://test_url") + assert response.json() == {"ok": True} + + +@pytest.mark.httpx_mock(assert_all_requests_were_expected=False) +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, + ) + + with httpx.Client() as client: + with pytest.raises(httpx.TimeoutException) as exception_info: + 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 """ + ) + + +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} + ) + + with httpx.Client() as client: + response = client.get("https://test_url") + assert response.json() == {"matched": True} + + response = client.get("https://test_url", headers={"X-Foo": "bar"}) + assert response.json() == {"matched": False} + + +@pytest.mark.httpx_mock(assert_all_requests_were_expected=False) +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, + ) + + with httpx.Client() as client: + with pytest.raises(httpx.TimeoutException) as exception_info: + 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 """ + ) + + +def test_custom_matcher_request_retrieval(httpx_mock: HTTPXMock) -> None: + httpx_mock.add_response(is_reusable=True) + + with httpx.Client() as client: + client.get("https://test_url") + 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" + + +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, + ) + + with httpx.Client() as client: + response = client.get("https://test_url") + assert response.text == "matched" + + +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, + ) + + with httpx.Client() as client, pytest.raises(httpx.ReadTimeout): + client.get("https://test_url") + + +@pytest.mark.httpx_mock(assert_all_requests_were_expected=False) +def test_custom_matcher_callable_object(httpx_mock: HTTPXMock) -> None: + class WithoutHeader: + def __call__(self, request: httpx.Request) -> bool: + return "X-Foo" not in request.headers + + httpx_mock.add_response(match_request=WithoutHeader(), is_optional=True) + + with httpx.Client() as client: + with pytest.raises(httpx.TimeoutException) as exception_info: + 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 WithoutHeader""" + ) diff --git a/tests/test_plugin.py b/tests/test_plugin.py index 13ed9ea..0743e13 100644 --- a/tests/test_plugin.py +++ b/tests/test_plugin.py @@ -40,6 +40,30 @@ def test_httpx_mock_unused_response(httpx_mock): ) +def test_httpx_mock_unused_response_with_custom_matcher(testdir: Testdir) -> None: + """ + Unused responses registered with a custom matcher should mention it. + """ + testdir.makepyfile(""" + def test_httpx_mock_unused_response_with_custom_matcher(httpx_mock): + def no_x_foo(request): + return "X-Foo" not in request.headers + + httpx_mock.add_response(match_request=no_x_foo) + """) + result = testdir.runpytest() + result.assert_outcomes(errors=1, passed=1) + result.stdout.fnmatch_lines( + [ + "*AssertionError: The following responses are mocked but not requested:", + "* - Match any request with custom matcher no_x_foo", + "* ", + "* If this is on purpose, refer to https://github.com/Colin-b/pytest_httpx/blob/master/README.md#allow-to-register-more-responses-than-what-will-be-requested", + ], + consecutive=True, + ) + + def test_httpx_mock_unused_response_without_assertion(testdir: Testdir) -> None: """ Unused responses should not fail test case if