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

Fix aiohttp response serialize #23858

Merged
merged 3 commits into from
May 14, 2019
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
16 changes: 14 additions & 2 deletions homeassistant/components/cloud/utils.py
Original file line number Diff line number Diff line change
@@ -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),
}
34 changes: 34 additions & 0 deletions tests/components/cloud/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"})
Expand Down