Skip to content

Commit

Permalink
Raising RuntimeError when trying to get empty body encoding (#4481)
Browse files Browse the repository at this point in the history
  • Loading branch information
Purusah authored and asvetlov committed Jan 18, 2020
1 parent baa06c4 commit 63a0d10
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGES/4214.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Raising RuntimeError when trying to get encoding from not read body
1 change: 1 addition & 0 deletions CONTRIBUTORS.txt
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,7 @@ Vladimir Kozlovski
Vladimir Rutsky
Vladimir Shulyak
Vladimir Zakharov
Vladyslav Bohaichuk
Vladyslav Bondar
W. Trevor King
Wei Lin
Expand Down
3 changes: 3 additions & 0 deletions aiohttp/client_reqrep.py
Original file line number Diff line number Diff line change
Expand Up @@ -938,6 +938,9 @@ def get_encoding(self) -> str:
if mimetype.type == 'application' and mimetype.subtype == 'json':
# RFC 7159 states that the default encoding is UTF-8.
encoding = 'utf-8'
elif self._body is None:
raise RuntimeError('Cannot guess the encoding of '
'a not yet read body')
else:
encoding = chardet.detect(self._body)['encoding']
if not encoding:
Expand Down
3 changes: 3 additions & 0 deletions docs/client_reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1305,6 +1305,9 @@ Response object
decode a response. Some encodings detected by cchardet are not known by
Python (e.g. VISCII).

:raise RuntimeError: if called before the body has been read,
for :term:`cchardet` usage

.. versionadded:: 3.0


Expand Down
27 changes: 27 additions & 0 deletions tests/test_client_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,33 @@ def side_effect(*args, **kwargs):
assert response.get_encoding().lower() in ('windows-1251', 'maccyrillic')


async def test_get_encoding_body_none(loop, session) -> None:
response = ClientResponse('get', URL('http://def-cl-resp.org'),
request_info=mock.Mock(),
writer=mock.Mock(),
continue100=None,
timer=TimerNoop(),
traces=[],
loop=loop,
session=session)

def side_effect(*args, **kwargs):
fut = loop.create_future()
fut.set_result('{"encoding": "test"}')
return fut

response._headers = {'Content-Type': 'text/html'}
content = response.content = mock.Mock()
content.read.side_effect = side_effect

with pytest.raises(
RuntimeError,
match='^Cannot guess the encoding of a not yet read body$',
):
response.get_encoding()
assert response.closed


async def test_text_after_read(loop, session) -> None:
response = ClientResponse('get', URL('http://def-cl-resp.org'),
request_info=mock.Mock(),
Expand Down

0 comments on commit 63a0d10

Please sign in to comment.