Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix inconsistent exception for JSONDecode error #6097

Merged
merged 1 commit into from Mar 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions requests/models.py
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
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)