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
Provenance
- Commit
9fd6f0c- Tree
ae3e6ab- Author
BERRADA-Omar <59538462+BERRADA-Omar@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
8e36f2b
7 files changed+53 added−14 removed
modified:httpx/_content.py+3 added-1 removed
172 unmodified lines173 return headers, ByteStream(body)174 175 176 def 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 linesmodified:tests/client/test_auth.py+2 added-2 removed
741 unmodified lines742 async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:743 response = await client.get(url, auth=auth)744 745 assert response.status_code == 200746- assert response.json() == {"auth": '{"auth": "xyz"}'}746+ assert response.json() == {"auth": '{"auth":"xyz"}'}747 748 749 def test_sync_auth_reads_response_body() -> None:750 """7 unmodified lines758 with httpx.Client(transport=httpx.MockTransport(app)) as client:759 response = client.get(url, auth=auth)760 761 assert response.status_code == 200762- assert response.json() == {"auth": '{"auth": "xyz"}'}762+ assert response.json() == {"auth": '{"auth":"xyz"}'}763 764 765 @pytest.mark.anyio766 async def test_async_auth() -> None:29 unmodified linesmodified:tests/models/test_requests.py+4 added-4 removed
60 unmodified lines61 request = httpx.Request("POST", "http://example.org", json={"test": 123})62 request.read()63 64 assert request.headers["Content-Type"] == "application/json"65- assert request.content == b'{"test": 123}'65+ assert request.content == b'{"test":123}'66 67 68 def test_headers():69 request = httpx.Request("POST", "http://example.org", json={"test": 123})70 71 assert request.headers == {72 "Host": "example.org",73 "Content-Type": "application/json",74- "Content-Length": "13",74+ "Content-Length": "12",75 }76 77 78 def test_read_and_stream_data():103 unmodified lines182 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 }193 194 195 @pytest.mark.anyio33 unmodified linesmodified:tests/models/test_responses.py+2 added-2 removed
79 unmodified lines80 response = httpx.Response(200, json={"hello": "world"})81 82 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 }89 90 947 unmodified linesmodified:tests/models/test_whatwg.py+1 added-1 removed
8 unmodified lines9 from httpx._urlparse import urlparse10 11 # URL test cases from...12 # https://github.com/web-platform-tests/wpt/blob/master/url/resources/urltestdata.json13-with open("tests/models/whatwg.json", "r") as input:13+with 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_cases35 unmodified linesmodified:tests/test_content.py+40 added-3 removed
2 unmodified lines3 4 import pytest5 6 import httpx7+from httpx._content import encode_json8 9 method = "POST"10 url = "https://www.example.com"11 161 unmodified lines173 async_content = b"".join([part async for part in request.stream])174 175 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!"}'182 183 184 @pytest.mark.anyio185 async def test_urlencoded_content():298 unmodified lines484 485 def test_response_invalid_argument():486 with pytest.raises(TypeError):487 httpx.Response(200, content=123) # type: ignore488+489+490+def 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")494+495+ assert (496+ "ça va" in json_output497+ ), "ensure_ascii=False should preserve French accented characters"498+ assert headers["Content-Type"] == "application/json"499+500+501+def 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")505+506+ assert (507+ json_output == '{"clé":"valeur","liste":[1,2,3]}'508+ ), "separators=(',', ':') should produce a compact representation"509+ assert headers["Content-Type"] == "application/json"510+511+512+def test_allow_nan_false():513+ data_with_nan = {"nombre": float("nan")}514+ data_with_inf = {"nombre": float("inf")}515+516+ 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 lines113 "server: uvicorn",114 "content-type: text/plain",115 "Transfer-Encoding: chunked",116 "",117- '{"hello": "world"}',117+ '{"hello":"world"}',118 ]119 120 121 def test_verbose(server):66 unmodified lines