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 @@ -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.
Expand Down
27 changes: 21 additions & 6 deletions pytest_httpx/_httpx_mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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:
"""
Expand Down Expand Up @@ -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,
Expand Down
12 changes: 7 additions & 5 deletions pytest_httpx/_request_matcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
"""
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -130,15 +132,15 @@ 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

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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand Down
15 changes: 15 additions & 0 deletions tests/test_httpx_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -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})
Expand Down
14 changes: 14 additions & 0 deletions tests/test_httpx_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -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})

Expand Down