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()``
This commit is contained in:
messense
2016-05-05 11:15:53 +08:00
parent 989e8f15dd
commit cb4c2c0b65
2 changed files with 12 additions and 1 deletions
+1 -1
View File
@@ -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
+11
View File
@@ -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: