From 94a2fd542ea47abf59d2e3a21f17637a3d9af92f Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Tue, 14 May 2019 11:59:27 +0200 Subject: [PATCH] Fix aiohttp response serialize (#23858) * Fix aiohttp response serialize * Suport bytes * Handle None --- homeassistant/components/cloud/utils.py | 16 ++++++++++-- tests/components/cloud/test_utils.py | 34 +++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/cloud/utils.py b/homeassistant/components/cloud/utils.py index da1d3809989..1d53681cbea 100644 --- a/homeassistant/components/cloud/utils.py +++ b/homeassistant/components/cloud/utils.py @@ -1,13 +1,25 @@ """Helper functions for cloud components.""" from typing import Any, Dict -from aiohttp import web +from aiohttp import web, payload def aiohttp_serialize_response(response: web.Response) -> Dict[str, Any]: """Serialize an aiohttp response to a dictionary.""" + body = response.body + + if body is None: + pass + elif isinstance(body, payload.StringPayload): + # pylint: disable=protected-access + body = body._value.decode(body.encoding) + elif isinstance(body, bytes): + body = body.decode(response.charset or 'utf-8') + else: + raise ValueError("Unknown payload encoding") + return { 'status': response.status, - 'body': response.text, + 'body': body, 'headers': dict(response.headers), } diff --git a/tests/components/cloud/test_utils.py b/tests/components/cloud/test_utils.py index 24de4ce6214..4543f6d5623 100644 --- a/tests/components/cloud/test_utils.py +++ b/tests/components/cloud/test_utils.py @@ -14,6 +14,40 @@ def test_serialize_text(): } +def test_serialize_body_str(): + """Test serializing a response with a str as body.""" + response = web.Response(status=201, body='Hello') + assert utils.aiohttp_serialize_response(response) == { + 'status': 201, + 'body': 'Hello', + 'headers': { + 'Content-Length': '5', + 'Content-Type': 'text/plain; charset=utf-8' + }, + } + + +def test_serialize_body_None(): + """Test serializing a response with a str as body.""" + response = web.Response(status=201, body=None) + assert utils.aiohttp_serialize_response(response) == { + 'status': 201, + 'body': None, + 'headers': { + }, + } + + +def test_serialize_body_bytes(): + """Test serializing a response with a str as body.""" + response = web.Response(status=201, body=b'Hello') + assert utils.aiohttp_serialize_response(response) == { + 'status': 201, + 'body': 'Hello', + 'headers': {}, + } + + def test_serialize_json(): """Test serializing a JSON response.""" response = web.json_response({"how": "what"})