Skip to content
Myr

Fix inconsistent exception for JSONDecode error (#6097)

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

When calling .json() it was possible to raise a requests.exceptions.JSONDecodeError or ValueError depending on whether the encoding is set.

authored by Nate Prewitt · committed by GitHub · parent 8bce583 · Browse files · 2 files+26 added−0 removed
This commit

State

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

Diff stats

2 files+26 added−0 removed

  • tests:+24 added−0 removed
  • other:+2 added−0 removed

2 files+26 added−0 removed

modified:requests/models.py+2 added
898 unmodified lines
899 # but some other 8-bit codec. This is an RFC violation,900 # and the server didn't bother to tell us what codec *was*901 # used.902 pass903 except JSONDecodeError as e:904 raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)905906 try:907 return complexjson.loads(self.text, **kwargs)908 except JSONDecodeError as e:
59 unmodified lines
modified:tests/test_lowlevel.py+24 added
4 unmodified lines
5import requests67from tests.testserver.server import Server, consume_socket_content89from requests.compat import JSONDecodeError10from .utils import override_environ111213def echo_response_handler(sock):
389 unmodified lines
403 # Verify previous fragment is used and not the original.404 assert r.url == 'http://{}:{}/final-url/#relevant-section'.format(host, port)405406 close_server.set()407408def test_json_decode_compatibility_for_alt_utf_encodings():409410 def response_handler(sock):411 consume_socket_content(sock, timeout=0.5)412 sock.send(413 b'HTTP/1.1 200 OK\r\n'414 b'Content-Length: 18\r\n\r\n'415 b'\xff\xfe{\x00"\x00K0"\x00=\x00"\x00\xab0"\x00\r\n'416 )417418 close_server = threading.Event()419 server = Server(response_handler, wait_to_close_event=close_server)420421 with server as (host, port):422 url = 'http://{}:{}/'.format(host, port)423 r = requests.get(url)424 r.encoding = None425 with pytest.raises(requests.exceptions.JSONDecodeError) as excinfo:426 r.json()427 assert isinstance(excinfo.value, requests.exceptions.RequestException)428 assert isinstance(excinfo.value, JSONDecodeError)429 assert r.text not in str(excinfo.value)