diff --git a/CHANGES/3482.bugfix b/CHANGES/3482.bugfix new file mode 100644 index 00000000000..8d193f45efb --- /dev/null +++ b/CHANGES/3482.bugfix @@ -0,0 +1 @@ +Do not return `None` on `await response.json()` when body is empty. Instead, raise `json.JSONDecodeError` as expected. diff --git a/aiohttp/client_reqrep.py b/aiohttp/client_reqrep.py index 5ef133bf325..d7d5b718a72 100644 --- a/aiohttp/client_reqrep.py +++ b/aiohttp/client_reqrep.py @@ -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: Optional[bytes] self._writer = writer # type: Optional[asyncio.Task[None]] self._continue = continue100 # None by default self._closed = True @@ -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)) # type: ignore async def __aenter__(self) -> 'ClientResponse': return self diff --git a/tests/test_client_response.py b/tests/test_client_response.py index c61998de8b7..cf203d844b2 100644 --- a/tests/test_client_response.py +++ b/tests/test_client_response.py @@ -3,6 +3,7 @@ import gc import sys +from json import JSONDecodeError from unittest import mock import pytest @@ -586,11 +587,11 @@ async def test_json_no_content(loop, session) -> None: loop=loop, session=session) response._headers = { - 'Content-Type': 'data/octet-stream'} + 'Content-Type': 'application/json'} response._body = b'' - res = await response.json(content_type=None) - assert res is None + with pytest.raises(JSONDecodeError): + await response.json(content_type=None) async def test_json_override_encoding(loop, session) -> None: