Skip to content

Commit

Permalink
Do not strip body before JSON decoding + do not return None on empty …
Browse files Browse the repository at this point in the history
…body (#3482)

This commit actually reverts 6a19364
  • Loading branch information
socketpair committed Jan 4, 2019
1 parent 0715ae7 commit abe6fa7
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 6 deletions.
1 change: 1 addition & 0 deletions CHANGES/3482.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Do not return `None` on `await response.json()` when body is empty. Instead, raise `json.JSONDecodeError` as expected.
8 changes: 2 additions & 6 deletions aiohttp/client_reqrep.py
Original file line number Diff line number Diff line change
Expand Up @@ -692,7 +692,7 @@ def __init__(self, method: str, url: URL, *,

self._real_url = url
self._url = url.with_fragment(None)
self._body = None # type: Any
self._body = None # type: bytes
self._writer = writer # type: Optional[asyncio.Task[None]]
self._continue = continue100 # None by default
self._closed = True
Expand Down Expand Up @@ -1028,14 +1028,10 @@ async def json(self, *, encoding: str=None,
'unexpected mimetype: %s' % ctype),
headers=self.headers)

stripped = self._body.strip() # type: ignore
if not stripped:
return None

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

return loads(stripped.decode(encoding))
return loads(self._body.decode(encoding))

async def __aenter__(self) -> 'ClientResponse':
return self
Expand Down
26 changes: 26 additions & 0 deletions tests/test_client_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import gc
import sys
from json import JSONDecodeError
from unittest import mock

import pytest
Expand Down Expand Up @@ -486,6 +487,31 @@ def side_effect(*args, **kwargs):
assert response._connection is None


async def test_json_empty_body(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(b'')
return fut

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

with pytest.raises(JSONDecodeError):
res = await response.json()

assert response._connection is None


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

0 comments on commit abe6fa7

Please sign in to comment.