Skip to content

Commit

Permalink
Merge pull request #112 from NabuCasa/dev
Browse files Browse the repository at this point in the history
0.29
  • Loading branch information
balloob authored Nov 7, 2019
2 parents d9abe76 + 893e955 commit 61b366a
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 4 deletions.
19 changes: 17 additions & 2 deletions hass_nabucasa/thingtalk.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,25 @@
from . import Cloud


class ThingTalkConversionError(Exception):
"""Conversion error occurred."""


async def async_convert(cloud: "Cloud", query: str):
"""Convert sentence."""
resp = await cloud.client.websession.post(
f"{cloud.thingtalk_url}/convert", json={"query": query}
)
resp.raise_for_status()
return await resp.json()
if resp.status == 200:
return await resp.json()

try:
body = await resp.json()
except ValueError:
# Invalid JSON in body
resp.raise_for_status()

if not isinstance(body, dict) or "error" not in body:
resp.raise_for_status()

raise ThingTalkConversionError(body["error"])
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from setuptools import setup

VERSION = "0.28"
VERSION = "0.29"

setup(
name="hass-nabucasa",
Expand Down
2 changes: 1 addition & 1 deletion tests/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def loop(self):
@property
def websession(self):
"""Return client session for aiohttp."""
raise self._websession
return self._websession

@property
def aiohttp_runner(self):
Expand Down
39 changes: 39 additions & 0 deletions tests/test_thingtalk.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"""Tests for ThingTalk."""
import pytest

import aiohttp

from hass_nabucasa import thingtalk

API_URL = "https://example.com"
CONVERT_URL = f"{API_URL}/convert"


@pytest.fixture(autouse=True)
def set_api_url(cloud_mock):
"""Set TT API url."""
cloud_mock.thingtalk_url = API_URL


async def test_async_convert_ok(aioclient_mock, cloud_mock):
"""Test async convert."""
aioclient_mock.post(CONVERT_URL, json={"hello": "yo"})
assert await thingtalk.async_convert(cloud_mock, "Hello") == {"hello": "yo"}


async def test_async_convert_fail(aioclient_mock, cloud_mock):
"""Test async convert."""
aioclient_mock.post(CONVERT_URL, status=400, json={"error": "Convert Error!"})
with pytest.raises(thingtalk.ThingTalkConversionError) as excinfo:
await thingtalk.async_convert(cloud_mock, "Hello")

assert str(excinfo.value) == "Convert Error!"


async def test_async_convert_invalid(aioclient_mock, cloud_mock):
"""Test async convert."""
aioclient_mock.post(CONVERT_URL, status=500, text="")
with pytest.raises(aiohttp.ClientResponseError) as excinfo:
await thingtalk.async_convert(cloud_mock, "Hello")

assert excinfo.value.status == 500

0 comments on commit 61b366a

Please sign in to comment.