From 4290acf5e71f292f13ed09c0bb05fd501015e264 Mon Sep 17 00:00:00 2001 From: Nate Prewitt Date: Mon, 28 Mar 2022 11:46:57 -0600 Subject: [PATCH] Fix inconsistent exception for JSONDecode error When calling .json() it was possible to raise a requests.exceptions.JSONDecodeError or ValueError depending on whether the encoding is set. --- requests/models.py | 2 ++ tests/test_lowlevel.py | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/requests/models.py b/requests/models.py index 539879feb3..df0f8b3e13 100644 --- a/requests/models.py +++ b/requests/models.py @@ -900,6 +900,8 @@ def json(self, **kwargs): # and the server didn't bother to tell us what codec *was* # used. pass + except JSONDecodeError as e: + raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) try: return complexjson.loads(self.text, **kwargs) diff --git a/tests/test_lowlevel.py b/tests/test_lowlevel.py index 7256eda943..1d8cbde64a 100644 --- a/tests/test_lowlevel.py +++ b/tests/test_lowlevel.py @@ -6,6 +6,7 @@ from tests.testserver.server import Server, consume_socket_content +from requests.compat import JSONDecodeError from .utils import override_environ @@ -403,3 +404,26 @@ def response_handler(sock): assert r.url == 'http://{}:{}/final-url/#relevant-section'.format(host, port) close_server.set() + +def test_json_decode_compatibility_for_alt_utf_encodings(): + + def response_handler(sock): + consume_socket_content(sock, timeout=0.5) + sock.send( + b'HTTP/1.1 200 OK\r\n' + b'Content-Length: 18\r\n\r\n' + b'\xff\xfe{\x00"\x00K0"\x00=\x00"\x00\xab0"\x00\r\n' + ) + + close_server = threading.Event() + server = Server(response_handler, wait_to_close_event=close_server) + + with server as (host, port): + url = 'http://{}:{}/'.format(host, port) + r = requests.get(url) + r.encoding = None + with pytest.raises(requests.exceptions.JSONDecodeError) as excinfo: + r.json() + assert isinstance(excinfo.value, requests.exceptions.RequestException) + assert isinstance(excinfo.value, JSONDecodeError) + assert r.text not in str(excinfo.value)