Skip to content
Myr

Ensure JSON representation is compact. #3363 (#3367)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by BERRADA-Omar · committed by GitHub · parent 8e36f2b · Browse files · 7 files+53 added−14 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Tom Christie <tom@tomchristie.com>

Diff stats

7 files+53 added−14 removed

  • tests:+50 added−13 removed
  • other:+3 added−1 removed

7 files+53 added−14 removed

modified:httpx/_content.py+3 added-1 removed
172 unmodified lines
173 return headers, ByteStream(body)174175176def encode_json(json: Any) -> tuple[dict[str, str], ByteStream]:177 body = json_dumps(json).encode("utf-8")177 body = json_dumps(178 json, ensure_ascii=False, separators=(",", ":"), allow_nan=False179 ).encode("utf-8")180 content_length = str(len(body))181 content_type = "application/json"182 headers = {"Content-Length": content_length, "Content-Type": content_type}183 return headers, ByteStream(body)
57 unmodified lines
modified:tests/client/test_auth.py+2 added-2 removed
741 unmodified lines
742 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:743 response = await client.get(url, auth=auth)744745 assert response.status_code == 200746 assert response.json() == {"auth": '{"auth": "xyz"}'}746 assert response.json() == {"auth": '{"auth":"xyz"}'}747748749def test_sync_auth_reads_response_body() -> None:750 """
7 unmodified lines
758 with httpx.Client(transport=httpx.MockTransport(app)) as client:759 response = client.get(url, auth=auth)760761 assert response.status_code == 200762 assert response.json() == {"auth": '{"auth": "xyz"}'}762 assert response.json() == {"auth": '{"auth":"xyz"}'}763764765@pytest.mark.anyio766async def test_async_auth() -> None:
29 unmodified lines
modified:tests/models/test_requests.py+4 added-4 removed
60 unmodified lines
61 request = httpx.Request("POST", "http://example.org", json={"test": 123})62 request.read()6364 assert request.headers["Content-Type"] == "application/json"65 assert request.content == b'{"test": 123}'65 assert request.content == b'{"test":123}'666768def test_headers():69 request = httpx.Request("POST", "http://example.org", json={"test": 123})7071 assert request.headers == {72 "Host": "example.org",73 "Content-Type": "application/json",74 "Content-Length": "13",74 "Content-Length": "12",75 }767778def test_read_and_stream_data():
103 unmodified lines
182 pickle_request = pickle.loads(pickle.dumps(request))183 assert pickle_request.method == "POST"184 assert pickle_request.url.path == "/"185 assert pickle_request.headers["Content-Type"] == "application/json"186 assert pickle_request.content == b'{"test": 123}'186 assert pickle_request.content == b'{"test":123}'187 assert pickle_request.stream is not None188 assert request.headers == {189 "Host": "example.org",190 "Content-Type": "application/json",191 "content-length": "13",191 "content-length": "12",192 }193194195@pytest.mark.anyio
33 unmodified lines
modified:tests/models/test_responses.py+2 added-2 removed
79 unmodified lines
80 response = httpx.Response(200, json={"hello": "world"})8182 assert response.status_code == 20083 assert response.reason_phrase == "OK"84 assert response.json() == {"hello": "world"}84 assert str(response.json()) == "{'hello': 'world'}"85 assert response.headers == {86 "Content-Length": "18",86 "Content-Length": "17",87 "Content-Type": "application/json",88 }8990
947 unmodified lines
modified:tests/models/test_whatwg.py+1 added-1 removed
8 unmodified lines
9from httpx._urlparse import urlparse1011# URL test cases from...12# https://github.com/web-platform-tests/wpt/blob/master/url/resources/urltestdata.json13with open("tests/models/whatwg.json", "r") as input:13with open("tests/models/whatwg.json", "r", encoding="utf-8") as input:14 test_cases = json.load(input)15 test_cases = [16 item17 for item in test_cases
35 unmodified lines
modified:tests/test_content.py+40 added-3 removed
2 unmodified lines
34import pytest56import httpx7from httpx._content import encode_json89method = "POST"10url = "https://www.example.com"11
161 unmodified lines
173 async_content = b"".join([part async for part in request.stream])174175 assert request.headers == {176 "Host": "www.example.com",176 "Content-Length": "19",177 "Content-Length": "18",178 "Content-Type": "application/json",179 }179 assert sync_content == b'{"Hello": "world!"}'180 assert async_content == b'{"Hello": "world!"}'180 assert sync_content == b'{"Hello":"world!"}'181 assert async_content == b'{"Hello":"world!"}'182183184@pytest.mark.anyio185async def test_urlencoded_content():
298 unmodified lines
484485def test_response_invalid_argument():486 with pytest.raises(TypeError):487 httpx.Response(200, content=123) # type: ignore488489490def test_ensure_ascii_false_with_french_characters():491 data = {"greeting": "Bonjour, ça va ?"}492 headers, byte_stream = encode_json(data)493 json_output = b"".join(byte_stream).decode("utf-8")494495 assert (496 "ça va" in json_output497 ), "ensure_ascii=False should preserve French accented characters"498 assert headers["Content-Type"] == "application/json"499500501def test_separators_for_compact_json():502 data = {"clé": "valeur", "liste": [1, 2, 3]}503 headers, byte_stream = encode_json(data)504 json_output = b"".join(byte_stream).decode("utf-8")505506 assert (507 json_output == '{"clé":"valeur","liste":[1,2,3]}'508 ), "separators=(',', ':') should produce a compact representation"509 assert headers["Content-Type"] == "application/json"510511512def test_allow_nan_false():513 data_with_nan = {"nombre": float("nan")}514 data_with_inf = {"nombre": float("inf")}515516 with pytest.raises(517 ValueError, match="Out of range float values are not JSON compliant"518 ):519 encode_json(data_with_nan)520 with pytest.raises(521 ValueError, match="Out of range float values are not JSON compliant"522 ):523 encode_json(data_with_inf)
modified:tests/test_main.py+1 added-1 removed
112 unmodified lines
113 "server: uvicorn",114 "content-type: text/plain",115 "Transfer-Encoding: chunked",116 "",117 '{"hello": "world"}',117 '{"hello":"world"}',118 ]119120121def test_verbose(server):
66 unmodified lines