From 7c14d81ab1ba9c611ad0bd342ecdf10710b37305 Mon Sep 17 00:00:00 2001 From: Stanislav Evseev Date: Thu, 8 Nov 2018 18:41:07 +0100 Subject: [PATCH] CHANGE: return None from json if body is empty --- tests/integration/aiohttp_utils.py | 8 ++++++++ tests/integration/test_aiohttp.py | 23 +++++++++++++++++++++++ vcr/stubs/aiohttp_stubs/__init__.py | 6 +++++- 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/tests/integration/aiohttp_utils.py b/tests/integration/aiohttp_utils.py index c8c1b0b..851c640 100644 --- a/tests/integration/aiohttp_utils.py +++ b/tests/integration/aiohttp_utils.py @@ -30,6 +30,14 @@ def aiohttp_app(): async def hello(request): return aiohttp.web.Response(text='hello') + async def json(request): + return aiohttp.web.json_response({}) + + async def json_empty_body(request): + return aiohttp.web.json_response() + app = aiohttp.web.Application() app.router.add_get('/', hello) + app.router.add_get('/json', json) + app.router.add_get('/json/empty', json_empty_body) return app diff --git a/tests/integration/test_aiohttp.py b/tests/integration/test_aiohttp.py index a02c982..bbb0913 100644 --- a/tests/integration/test_aiohttp.py +++ b/tests/integration/test_aiohttp.py @@ -191,3 +191,26 @@ def test_aiohttp_test_client(aiohttp_client, tmpdir): response_text = loop.run_until_complete(response.text()) assert response_text == 'hello' assert cassette.play_count == 1 + + +def test_aiohttp_test_client_json(aiohttp_client, tmpdir): + loop = asyncio.get_event_loop() + app = aiohttp_app() + url = '/json/empty' + client = loop.run_until_complete(aiohttp_client(app)) + + with vcr.use_cassette(str(tmpdir.join('get.yaml'))): + response = loop.run_until_complete(client.get(url)) + + assert response.status == 200 + response_json = loop.run_until_complete(response.json()) + assert response_json is None + + with vcr.use_cassette(str(tmpdir.join('get.yaml'))) as cassette: + response = loop.run_until_complete(client.get(url)) + + request = cassette.requests[0] + assert request.url == str(client.make_url(url)) + response_json = loop.run_until_complete(response.json()) + assert response_json is None + assert cassette.play_count == 1 diff --git a/vcr/stubs/aiohttp_stubs/__init__.py b/vcr/stubs/aiohttp_stubs/__init__.py index 8e03907..237ddea 100644 --- a/vcr/stubs/aiohttp_stubs/__init__.py +++ b/vcr/stubs/aiohttp_stubs/__init__.py @@ -30,7 +30,11 @@ class MockClientResponse(ClientResponse): ) async def json(self, *, encoding='utf-8', loads=json.loads, **kwargs): # NOQA: E999 - return loads(self._body.decode(encoding)) + stripped = self._body.strip() + if not stripped: + return None + + return loads(stripped.decode(encoding)) async def text(self, encoding='utf-8', errors='strict'): return self._body.decode(encoding, errors=errors)