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

Accept an errors parameter for text decoding ClientResponses #1542

Merged
merged 5 commits into from
Jan 21, 2017
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ CHANGES

- Fix typo in FAQ section "How to programmatically close websocket server-side?"

- Allow users to specify what should happen to decoding errors when calling a responses `text()` method #1542

1.2.0 (2016-12-17)
------------------
Expand Down
4 changes: 2 additions & 2 deletions aiohttp/client_reqrep.py
Original file line number Diff line number Diff line change
Expand Up @@ -741,15 +741,15 @@ def _get_encoding(self):
return encoding

@asyncio.coroutine
def text(self, encoding=None):
def text(self, encoding=None, errors='strict'):
"""Read response payload and decode."""
if self._content is None:
yield from self.read()

if encoding is None:
encoding = self._get_encoding()

return self._content.decode(encoding)
return self._content.decode(encoding, errors=errors)

@asyncio.coroutine
def json(self, *, encoding=None, loads=json.loads):
Expand Down
23 changes: 23 additions & 0 deletions tests/test_client_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,29 @@ def side_effect(*args, **kwargs):
assert response._connection is None


@asyncio.coroutine
def test_text_bad_encoding(loop):
response = ClientResponse('get', URL('http://def-cl-resp.org'))
response._post_init(loop)

def side_effect(*args, **kwargs):
fut = helpers.create_future(loop)
fut.set_result('{"тестkey": "пройденvalue"}'.encode('cp1251'))
return fut

# lie about the encoding
response.headers = {
'Content-Type': 'application/json;charset=utf-8'}
content = response.content = mock.Mock()
content.read.side_effect = side_effect
with pytest.raises(UnicodeDecodeError):
yield from response.text()
# only the valid utf-8 characters will be returned
res = yield from response.text(errors='ignore')
assert res == '{"key": "value"}'
assert response._connection is None


@asyncio.coroutine
def test_text_custom_encoding(loop):
response = ClientResponse('get', URL('http://def-cl-resp.org'))
Expand Down