Encoding detection in Response.json (#116)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Use response text on `json` Pass kwargs to the loads call * Add failing test demonstrating corner case * Copy `guess_json_utf` function from requests * "Fix" type hinting and lint * Actually add tests_utils.py
authored by Yeray Diaz Diaz · committed by Tom Christie · parent 561fb84 · Browse files · 4 files·+127 added−3 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+127 added−3 removed
- tests:+77 added−0 removed
- other:+50 added−3 removed
Provenance
- Commit
5442006- Tree
5960f6d- Author
Yeray Diaz Diaz <yeraydiazdiaz@gmail.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
561fb84
4 files changed+127 added−3 removed
modified:http3/models.py+15 added-3 removed
26 unmodified lines27 StreamConsumed,28 )29 from .multipart import multipart_encode30 from .status_codes import StatusCode31-from .utils import is_known_encoding, normalize_header_key, normalize_header_value31+from .utils import (32+ guess_json_utf,33+ is_known_encoding,34+ normalize_header_key,35+ normalize_header_value,36+)37 38 URLTypes = typing.Union["URL", str]39 40 QueryParamTypes = typing.Union[771 unmodified lines812 813 if message:814 raise HttpError(message)815 811- def json(self) -> typing.Any:812- return jsonlib.loads(self.content.decode("utf-8"))816+ def json(self, **kwargs: typing.Any) -> typing.Union[dict, list]:817+ if self.charset_encoding is None and self.content and len(self.content) > 3:818+ encoding = guess_json_utf(self.content)819+ if encoding is not None:820+ try:821+ return jsonlib.loads(self.content.decode(encoding), **kwargs)822+ except UnicodeDecodeError:823+ pass824+ return jsonlib.loads(self.text, **kwargs)825 826 @property827 def cookies(self) -> "Cookies":828 if not hasattr(self, "_cookies"):340 unmodified linesmodified:http3/utils.py+35 added
27 unmodified lines28 codecs.lookup(encoding)29 except LookupError:30 return False31 return True32+33+34+# Null bytes; no need to recreate these on each call to guess_json_utf35+_null = "\x00".encode("ascii") # encoding to ASCII for Python 336+_null2 = _null * 237+_null3 = _null * 338+39+40+def guess_json_utf(data: bytes) -> typing.Optional[str]:41+ # JSON always starts with two ASCII characters, so detection is as42+ # easy as counting the nulls and from their location and count43+ # determine the encoding. Also detect a BOM, if present.44+ sample = data[:4]45+ if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):46+ return "utf-32" # BOM included47+ if sample[:3] == codecs.BOM_UTF8:48+ return "utf-8-sig" # BOM included, MS style (discouraged)49+ if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):50+ return "utf-16" # BOM included51+ nullcount = sample.count(_null)52+ if nullcount == 0:53+ return "utf-8"54+ if nullcount == 2:55+ if sample[::2] == _null2: # 1st and 3rd are null56+ return "utf-16-be"57+ if sample[1::2] == _null2: # 2nd and 4th are null58+ return "utf-16-le"59+ # Did not detect 2 valid UTF-16 ascii-range characters60+ if nullcount == 3:61+ if sample[:3] == _null3:62+ return "utf-32-be"63+ if sample[1:] == _null3:64+ return "utf-32-le"65+ # Did not detect a valid UTF-32 ascii-range character66+ return Nonemodified:tests/models/test_responses.py+38 added
1+import json2+from unittest import mock3+4 import pytest5 6 import http37 244 unmodified lines252 response = http3.Response(600)253 assert response.status_code == 600254 assert response.reason_phrase == ""255 assert response.text == ""256+257+258+def test_json_with_specified_encoding():259+ data = dict(greeting="hello", recipient="world")260+ content = json.dumps(data).encode("utf-16")261+ headers = {"Content-Type": "application/json, charset=utf-16"}262+ response = http3.Response(200, content=content, headers=headers)263+ assert response.json() == data264+265+266+def test_json_with_options():267+ data = dict(greeting="hello", recipient="world", amount=1)268+ content = json.dumps(data).encode("utf-16")269+ headers = {"Content-Type": "application/json, charset=utf-16"}270+ response = http3.Response(200, content=content, headers=headers)271+ assert response.json(parse_int=str)["amount"] == "1"272+273+274+def test_json_without_specified_encoding():275+ data = dict(greeting="hello", recipient="world")276+ content = json.dumps(data).encode("utf-32-be")277+ headers = {"Content-Type": "application/json"}278+ response = http3.Response(200, content=content, headers=headers)279+ assert response.json() == data280+281+282+def test_json_without_specified_encoding_decode_error():283+ data = dict(greeting="hello", recipient="world")284+ content = json.dumps(data).encode("utf-32-be")285+ headers = {"Content-Type": "application/json"}286+ # force incorrect guess from `guess_json_utf` to trigger error287+ with mock.patch("http3.models.guess_json_utf", return_value="utf-32"):288+ response = http3.Response(200, content=content, headers=headers)289+ with pytest.raises(json.JSONDecodeError):290+ response.json()added:tests/test_utils.py+39 added
1+import pytest2+3+from http3.utils import guess_json_utf4+5+6+@pytest.mark.parametrize(7+ "encoding",8+ (9+ "utf-32",10+ "utf-8-sig",11+ "utf-16",12+ "utf-8",13+ "utf-16-be",14+ "utf-16-le",15+ "utf-32-be",16+ "utf-32-le",17+ ),18+)19+def test_encoded(encoding):20+ data = "{}".encode(encoding)21+ assert guess_json_utf(data) == encoding22+23+24+def test_bad_utf_like_encoding():25+ assert guess_json_utf(b"\x00\x00\x00\x00") is None26+27+28+@pytest.mark.parametrize(29+ ("encoding", "expected"),30+ (31+ ("utf-16-be", "utf-16"),32+ ("utf-16-le", "utf-16"),33+ ("utf-32-be", "utf-32"),34+ ("utf-32-le", "utf-32"),35+ ),36+)37+def test_guess_by_bom(encoding, expected):38+ data = u"\ufeff{}".encode(encoding)39+ assert guess_json_utf(data) == expected