Skip to content

Commit

Permalink
Fix inconsistent exception for JSONDecode error (#6097)
Browse files Browse the repository at this point in the history
When calling .json() it was possible to raise a
requests.exceptions.JSONDecodeError or ValueError
depending on whether the encoding is set.
  • Loading branch information
nateprewitt authored Mar 28, 2022
1 parent 8bce583 commit 2d55176
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
2 changes: 2 additions & 0 deletions requests/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
24 changes: 24 additions & 0 deletions tests/test_lowlevel.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

from tests.testserver.server import Server, consume_socket_content

from requests.compat import JSONDecodeError
from .utils import override_environ


Expand Down Expand Up @@ -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)

0 comments on commit 2d55176

Please sign in to comment.