From cb4c2c0b6507d0978859cf824ca396902ba81064 Mon Sep 17 00:00:00 2001 From: messense Date: Thu, 5 May 2016 11:15:53 +0800 Subject: [PATCH] Fix TypeError when get json-encoded content of a response ``self.content`` could be ``None``, so ``len(self.content)`` may raise ``TypeError: object of type 'NoneType' has no len()`` --- requests/models.py | 2 +- tests/test_requests.py | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/requests/models.py b/requests/models.py index fe4bec1b..0c10eef1 100644 --- a/requests/models.py +++ b/requests/models.py @@ -792,7 +792,7 @@ class Response(object): :param \*\*kwargs: Optional arguments that ``json.loads`` takes. """ - if not self.encoding and len(self.content) > 3: + if not self.encoding and self.content and len(self.content) > 3: # No encoding set. JSON RFC 4627 section 3 states we should expect # UTF-8, -16 or -32. Detect which one to use; If the detection or # decoding fails, fall back to `self.text` (using chardet to make diff --git a/tests/test_requests.py b/tests/test_requests.py index 0a87b52c..d01749d2 100755 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -1227,6 +1227,17 @@ class TestRequests: proxies['one'].clear.assert_called_once_with() proxies['two'].clear.assert_called_once_with() + def test_response_json_when_content_is_None(self, httpbin): + r = requests.get(httpbin('/status/204')) + # Make sure r.content is None + r.status_code = 0 + r._content = False + r._content_consumed = False + + assert r.content is None + with pytest.raises(ValueError): + r.json() + class TestCaseInsensitiveDict: