diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c5015b..9740faf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Explicit support for python `3.15`. ### Fixed +- Explicit JSON `null` values can now be returned and matched. - `match_params` now preserves `unittest.mock.ANY` inside tuple values, as it already does for lists. - Sending a non UTF8 body while having a `json` matcher registered will not raise a `UnicodeDecodeError` anymore. - `match_params` is now handling `bool`, `int` and `float` values in addition to `str`. Only str values were previously expected. diff --git a/pytest_httpx/_httpx_mock.py b/pytest_httpx/_httpx_mock.py index e35ac4f..0657e61 100644 --- a/pytest_httpx/_httpx_mock.py +++ b/pytest_httpx/_httpx_mock.py @@ -8,7 +8,7 @@ from pytest_httpx import _httpx_internals from pytest_httpx._options import _HTTPXMockOptions from pytest_httpx._pretty_print import RequestDescription -from pytest_httpx._request_matcher import _RequestMatcher +from pytest_httpx._request_matcher import _JSON_UNSET, _RequestMatcher class HTTPXMock: @@ -42,7 +42,7 @@ def add_response( text: str | None = None, html: str | None = None, stream: Any = None, - json: Any = None, + json: Any = _JSON_UNSET, **matchers: Any, ) -> None: """ @@ -72,15 +72,30 @@ def add_response( :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). """ - json = copy.deepcopy(json) if json is not None else None + json = copy.deepcopy(json) if json is not _JSON_UNSET else _JSON_UNSET def response_callback(request: httpx.Request) -> httpx.Response: + response_content = content + response_headers = headers + response_json = json + if ( + json is None + and content is None + and text is None + and html is None + and stream is None + ): + response_content = b"null" + response_headers = httpx.Headers(headers) + response_headers.setdefault("content-type", "application/json") + response_json = _JSON_UNSET + return httpx.Response( status_code=status_code, extensions={"http_version": http_version.encode("ascii")}, - headers=headers, - json=json, - content=content, + headers=response_headers, + json=None if response_json is _JSON_UNSET else response_json, + content=response_content, text=text, html=html, stream=stream, diff --git a/pytest_httpx/_request_matcher.py b/pytest_httpx/_request_matcher.py index b73a01f..caccf0c 100644 --- a/pytest_httpx/_request_matcher.py +++ b/pytest_httpx/_request_matcher.py @@ -11,6 +11,8 @@ from pytest_httpx._httpx_internals import PrimitiveData, _proxy_url from pytest_httpx._options import _HTTPXMockOptions +_JSON_UNSET = object() + def convert_back_mock_any(original: dict, new: dict) -> None: """ @@ -70,7 +72,7 @@ def __init__( proxy_url: str | Pattern[str] | httpx.URL | None = None, match_headers: dict[str, Any] | None = None, match_content: bytes | None = None, - match_json: Any | None = None, + match_json: Any = _JSON_UNSET, match_data: dict[str, Any] | None = None, match_files: Any | None = None, match_extensions: dict[str, Any] | None = None, @@ -130,7 +132,7 @@ def __init__( def expect_body(self) -> bool: matching_ways = [ self.content is not None, - self.json is not None, + self.json is not _JSON_UNSET, self.files is not None, ] return sum(matching_ways) == 1 @@ -138,7 +140,7 @@ def expect_body(self) -> bool: def _is_matching_body_more_than_one_way(self) -> bool: matching_ways = [ self.content is not None, - self.json is not None, + self.json is not _JSON_UNSET, self.files is not None, ] return sum(matching_ways) > 1 @@ -204,7 +206,7 @@ def _content_match(self, request: httpx.Request) -> bool: if self.content is not None: return request.content == self.content - if self.json is not None: + if self.json is not _JSON_UNSET: try: # httpx._content.encode_json hard codes utf-8 encoding. return json.loads(request.content.decode("utf-8")) == self.json @@ -273,7 +275,7 @@ def _extra_description(self) -> str: extra_description.append(f"{self.headers} headers") if self.content is not None: extra_description.append(f"{self.content!r} body") - if self.json is not None: + if self.json is not _JSON_UNSET: extra_description.append(f"{self.json} json body") if self.data is not None: extra_description.append(f"{self.data} multipart data") diff --git a/tests/test_httpx_async.py b/tests/test_httpx_async.py index 8dfa039..b41f3be 100644 --- a/tests/test_httpx_async.py +++ b/tests/test_httpx_async.py @@ -1861,6 +1861,21 @@ async def test_json_matching(httpx_mock: HTTPXMock) -> None: assert response.read() == b"" +@pytest.mark.asyncio +async def test_json_null_matching_and_response(httpx_mock: HTTPXMock) -> None: + httpx_mock.add_response(status_code=201, json=None, match_json=None) + httpx_mock.add_response(status_code=202) + + async with httpx.AsyncClient() as client: + non_null_response = await client.post("https://test_url", json=1) + null_response = await client.post("https://test_url", content=b"null") + + assert non_null_response.status_code == 202 + assert null_response.status_code == 201 + assert null_response.content == b"null" + assert null_response.headers["content-type"] == "application/json" + + @pytest.mark.asyncio async def test_json_partial_matching(httpx_mock: HTTPXMock) -> None: httpx_mock.add_response(match_json={"a": 1, "b": ANY}) diff --git a/tests/test_httpx_sync.py b/tests/test_httpx_sync.py index da52f61..b0a335e 100644 --- a/tests/test_httpx_sync.py +++ b/tests/test_httpx_sync.py @@ -1592,6 +1592,20 @@ def test_json_matching(httpx_mock: HTTPXMock) -> None: assert response.read() == b"" +def test_json_null_matching_and_response(httpx_mock: HTTPXMock) -> None: + httpx_mock.add_response(status_code=201, json=None, match_json=None) + httpx_mock.add_response(status_code=202) + + with httpx.Client() as client: + non_null_response = client.post("https://test_url", json=1) + null_response = client.post("https://test_url", content=b"null") + + assert non_null_response.status_code == 202 + assert null_response.status_code == 201 + assert null_response.content == b"null" + assert null_response.headers["content-type"] == "application/json" + + def test_json_partial_matching(httpx_mock: HTTPXMock) -> None: httpx_mock.add_response(match_json={"a": 1, "b": ANY})