Offload Cloud component (#21937)

* Offload Cloud component & Remote support

* Make hound happy

* Address comments
This commit is contained in:
Pascal Vizeli authored and Paulus Schoutsen committed 2019-03-11 12:21:20 -07:00
1 parent 8bfbe3e085
commit 92ff49212b
21 files changed
+646 -2170

No files matched your search

+2 -3
View File
@@ -11,8 +11,7 @@ from tests.common import mock_coro
def mock_cloud(hass, config={}):
"""Mock cloud."""
with patch('homeassistant.components.cloud.Cloud.async_start',
return_value=mock_coro()):
with patch('hass_nabucasa.Cloud.start', return_value=mock_coro()):
assert hass.loop.run_until_complete(async_setup_component(
hass, cloud.DOMAIN, {
'cloud': config
@@ -30,5 +29,5 @@ def mock_cloud_prefs(hass, prefs={}):
const.PREF_GOOGLE_ALLOW_UNLOCK: True,
}
prefs_to_set.update(prefs)
hass.data[cloud.DOMAIN].prefs._prefs = prefs_to_set
hass.data[cloud.DOMAIN].client._prefs._prefs = prefs_to_set
return prefs_to_set
+9
View File
@@ -1,9 +1,18 @@
"""Fixtures for cloud tests."""
import pytest
from unittest.mock import patch
from . import mock_cloud, mock_cloud_prefs
@pytest.fixture(autouse=True)
def mock_user_data():
"""Mock os module."""
with patch('hass_nabucasa.Cloud.write_user_info') as writer:
yield writer
@pytest.fixture
def mock_cloud_fixture(hass):
"""Fixture for cloud component."""
-196
View File
@@ -1,196 +0,0 @@
"""Tests for the tools to communicate with the cloud."""
import asyncio
from unittest.mock import MagicMock, patch
from botocore.exceptions import ClientError
import pytest
from homeassistant.components.cloud import auth_api
@pytest.fixture
def mock_cognito():
"""Mock warrant."""
with patch('homeassistant.components.cloud.auth_api._cognito') as mock_cog:
yield mock_cog()
def aws_error(code, message='Unknown', operation_name='fake_operation_name'):
"""Generate AWS error response."""
response = {
'Error': {
'Code': code,
'Message': message
}
}
return ClientError(response, operation_name)
def test_login_invalid_auth(mock_cognito):
"""Test trying to login with invalid credentials."""
cloud = MagicMock(is_logged_in=False)
mock_cognito.authenticate.side_effect = aws_error('NotAuthorizedException')
with pytest.raises(auth_api.Unauthenticated):
auth_api.login(cloud, 'user', 'pass')
assert len(cloud.write_user_info.mock_calls) == 0
def test_login_user_not_found(mock_cognito):
"""Test trying to login with invalid credentials."""
cloud = MagicMock(is_logged_in=False)
mock_cognito.authenticate.side_effect = aws_error('UserNotFoundException')
with pytest.raises(auth_api.UserNotFound):
auth_api.login(cloud, 'user', 'pass')
assert len(cloud.write_user_info.mock_calls) == 0
def test_login_user_not_confirmed(mock_cognito):
"""Test trying to login without confirming account."""
cloud = MagicMock(is_logged_in=False)
mock_cognito.authenticate.side_effect = \
aws_error('UserNotConfirmedException')
with pytest.raises(auth_api.UserNotConfirmed):
auth_api.login(cloud, 'user', 'pass')
assert len(cloud.write_user_info.mock_calls) == 0
def test_login(mock_cognito):
"""Test trying to login without confirming account."""
cloud = MagicMock(is_logged_in=False)
mock_cognito.id_token = 'test_id_token'
mock_cognito.access_token = 'test_access_token'
mock_cognito.refresh_token = 'test_refresh_token'
auth_api.login(cloud, 'user', 'pass')
assert len(mock_cognito.authenticate.mock_calls) == 1
assert cloud.id_token == 'test_id_token'
assert cloud.access_token == 'test_access_token'
assert cloud.refresh_token == 'test_refresh_token'
assert len(cloud.write_user_info.mock_calls) == 1
def test_register(mock_cognito):
"""Test registering an account."""
cloud = MagicMock()
cloud = MagicMock()
auth_api.register(cloud, 'email@home-assistant.io', 'password')
assert len(mock_cognito.register.mock_calls) == 1
result_user, result_password = mock_cognito.register.mock_calls[0][1]
assert result_user == 'email@home-assistant.io'
assert result_password == 'password'
def test_register_fails(mock_cognito):
"""Test registering an account."""
cloud = MagicMock()
mock_cognito.register.side_effect = aws_error('SomeError')
with pytest.raises(auth_api.CloudError):
auth_api.register(cloud, 'email@home-assistant.io', 'password')
def test_resend_email_confirm(mock_cognito):
"""Test starting forgot password flow."""
cloud = MagicMock()
auth_api.resend_email_confirm(cloud, 'email@home-assistant.io')
assert len(mock_cognito.client.resend_confirmation_code.mock_calls) == 1
def test_resend_email_confirm_fails(mock_cognito):
"""Test failure when starting forgot password flow."""
cloud = MagicMock()
mock_cognito.client.resend_confirmation_code.side_effect = \
aws_error('SomeError')
with pytest.raises(auth_api.CloudError):
auth_api.resend_email_confirm(cloud, 'email@home-assistant.io')
def test_forgot_password(mock_cognito):
"""Test starting forgot password flow."""
cloud = MagicMock()
auth_api.forgot_password(cloud, 'email@home-assistant.io')
assert len(mock_cognito.initiate_forgot_password.mock_calls) == 1
def test_forgot_password_fails(mock_cognito):
"""Test failure when starting forgot password flow."""
cloud = MagicMock()
mock_cognito.initiate_forgot_password.side_effect = aws_error('SomeError')
with pytest.raises(auth_api.CloudError):
auth_api.forgot_password(cloud, 'email@home-assistant.io')
def test_check_token_writes_new_token_on_refresh(mock_cognito):
"""Test check_token writes new token if refreshed."""
cloud = MagicMock()
mock_cognito.check_token.return_value = True
mock_cognito.id_token = 'new id token'
mock_cognito.access_token = 'new access token'
auth_api.check_token(cloud)
assert len(mock_cognito.check_token.mock_calls) == 1
assert cloud.id_token == 'new id token'
assert cloud.access_token == 'new access token'
assert len(cloud.write_user_info.mock_calls) == 1
def test_check_token_does_not_write_existing_token(mock_cognito):
"""Test check_token won't write new token if still valid."""
cloud = MagicMock()
mock_cognito.check_token.return_value = False
auth_api.check_token(cloud)
assert len(mock_cognito.check_token.mock_calls) == 1
assert cloud.id_token != mock_cognito.id_token
assert cloud.access_token != mock_cognito.access_token
assert len(cloud.write_user_info.mock_calls) == 0
def test_check_token_raises(mock_cognito):
"""Test we raise correct error."""
cloud = MagicMock()
mock_cognito.check_token.side_effect = aws_error('SomeError')
with pytest.raises(auth_api.CloudError):
auth_api.check_token(cloud)
assert len(mock_cognito.check_token.mock_calls) == 1
assert cloud.id_token != mock_cognito.id_token
assert cloud.access_token != mock_cognito.access_token
assert len(cloud.write_user_info.mock_calls) == 0
async def test_async_setup(hass):
"""Test async setup."""
cloud = MagicMock()
await auth_api.async_setup(hass, cloud)
assert len(cloud.iot.mock_calls) == 2
on_connect = cloud.iot.mock_calls[0][1][0]
on_disconnect = cloud.iot.mock_calls[1][1][0]
with patch('random.randint', return_value=0), patch(
'homeassistant.components.cloud.auth_api.renew_access_token'
) as mock_renew:
await on_connect()
# Let handle token sleep once
await asyncio.sleep(0)
# Let handle token refresh token
await asyncio.sleep(0)
assert len(mock_renew.mock_calls) == 1
assert mock_renew.mock_calls[0][1][0] is cloud
await on_disconnect()
# Make sure task is no longer being called
await asyncio.sleep(0)
await asyncio.sleep(0)
assert len(mock_renew.mock_calls) == 1
+199
View File
@@ -0,0 +1,199 @@
"""Test the cloud.iot module."""
from unittest.mock import patch, MagicMock
from aiohttp import web
import pytest
from homeassistant.setup import async_setup_component
from homeassistant.components.cloud.const import (
PREF_ENABLE_ALEXA, PREF_ENABLE_GOOGLE)
from tests.components.alexa import test_smart_home as test_alexa
from tests.common import mock_coro
from . import mock_cloud_prefs
@pytest.fixture
def mock_cloud():
"""Mock cloud class."""
return MagicMock(subscription_expired=False)
async def test_handler_alexa(hass):
"""Test handler Alexa."""
hass.states.async_set(
'switch.test', 'on', {'friendly_name': "Test switch"})
hass.states.async_set(
'switch.test2', 'on', {'friendly_name': "Test switch 2"})
with patch('hass_nabucasa.Cloud.start', return_value=mock_coro()):
setup = await async_setup_component(hass, 'cloud', {
'cloud': {
'alexa': {
'filter': {
'exclude_entities': 'switch.test2'
},
'entity_config': {
'switch.test': {
'name': 'Config name',
'description': 'Config description',
'display_categories': 'LIGHT'
}
}
}
}
})
assert setup
mock_cloud_prefs(hass)
cloud = hass.data['cloud']
resp = await cloud.client.async_alexa_message(
test_alexa.get_new_request('Alexa.Discovery', 'Discover'))
endpoints = resp['event']['payload']['endpoints']
assert len(endpoints) == 1
device = endpoints[0]
assert device['description'] == 'Config description'
assert device['friendlyName'] == 'Config name'
assert device['displayCategories'] == ['LIGHT']
assert device['manufacturerName'] == 'Home Assistant'
async def test_handler_alexa_disabled(hass, mock_cloud_fixture):
"""Test handler Alexa when user has disabled it."""
mock_cloud_fixture[PREF_ENABLE_ALEXA] = False
cloud = hass.data['cloud']
resp = await cloud.client.async_alexa_message(
test_alexa.get_new_request('Alexa.Discovery', 'Discover'))
assert resp['event']['header']['namespace'] == 'Alexa'
assert resp['event']['header']['name'] == 'ErrorResponse'
assert resp['event']['payload']['type'] == 'BRIDGE_UNREACHABLE'
async def test_handler_google_actions(hass):
"""Test handler Google Actions."""
hass.states.async_set(
'switch.test', 'on', {'friendly_name': "Test switch"})
hass.states.async_set(
'switch.test2', 'on', {'friendly_name': "Test switch 2"})
hass.states.async_set(
'group.all_locks', 'on', {'friendly_name': "Evil locks"})
with patch('hass_nabucasa.Cloud.start', return_value=mock_coro()):
setup = await async_setup_component(hass, 'cloud', {
'cloud': {
'google_actions': {
'filter': {
'exclude_entities': 'switch.test2'
},
'entity_config': {
'switch.test': {
'name': 'Config name',
'aliases': 'Config alias',
'room': 'living room'
}
}
}
}
})
assert setup
mock_cloud_prefs(hass)
cloud = hass.data['cloud']
reqid = '5711642932632160983'
data = {'requestId': reqid, 'inputs': [{'intent': 'action.devices.SYNC'}]}
with patch(
'hass_nabucasa.Cloud._decode_claims',
return_value={'cognito:username': 'myUserName'}
):
resp = await cloud.client.async_google_message(data)
assert resp['requestId'] == reqid
payload = resp['payload']
assert payload['agentUserId'] == 'myUserName'
devices = payload['devices']
assert len(devices) == 1
device = devices[0]
assert device['id'] == 'switch.test'
assert device['name']['name'] == 'Config name'
assert device['name']['nicknames'] == ['Config alias']
assert device['type'] == 'action.devices.types.SWITCH'
assert device['roomHint'] == 'living room'
async def test_handler_google_actions_disabled(hass, mock_cloud_fixture):
"""Test handler Google Actions when user has disabled it."""
mock_cloud_fixture[PREF_ENABLE_GOOGLE] = False
with patch('hass_nabucasa.Cloud.start', return_value=mock_coro()):
assert await async_setup_component(hass, 'cloud', {})
reqid = '5711642932632160983'
data = {'requestId': reqid, 'inputs': [{'intent': 'action.devices.SYNC'}]}
cloud = hass.data['cloud']
resp = await cloud.client.async_google_message(data)
assert resp['requestId'] == reqid
assert resp['payload']['errorCode'] == 'deviceTurnedOff'
async def test_webhook_msg(hass):
"""Test webhook msg."""
with patch('hass_nabucasa.Cloud.start', return_value=mock_coro()):
setup = await async_setup_component(hass, 'cloud', {
'cloud': {}
})
assert setup
cloud = hass.data['cloud']
await cloud.client.prefs.async_initialize()
await cloud.client.prefs.async_update(cloudhooks={
'hello': {
'webhook_id': 'mock-webhook-id',
'cloudhook_id': 'mock-cloud-id'
}
})
received = []
async def handler(hass, webhook_id, request):
"""Handle a webhook."""
received.append(request)
return web.json_response({'from': 'handler'})
hass.components.webhook.async_register(
'test', 'Test', 'mock-webhook-id', handler)
response = await cloud.client.async_webhook_message({
'cloudhook_id': 'mock-cloud-id',
'body': '{"hello": "world"}',
'headers': {
'content-type': 'application/json'
},
'method': 'POST',
'query': None,
})
assert response == {
'status': 200,
'body': '{"from": "handler"}',
'headers': {
'Content-Type': 'application/json'
}
}
assert len(received) == 1
assert await received[0].json() == {
'hello': 'world'
}
-33
View File
@@ -1,33 +0,0 @@
"""Test cloud API."""
from unittest.mock import Mock, patch
import pytest
from homeassistant.components.cloud import cloud_api
@pytest.fixture(autouse=True)
def mock_check_token():
"""Mock check token."""
with patch('homeassistant.components.cloud.auth_api.'
'check_token') as mock_check_token:
yield mock_check_token
async def test_create_cloudhook(hass, aioclient_mock):
"""Test creating a cloudhook."""
aioclient_mock.post('https://example.com/bla', json={
'cloudhook_id': 'mock-webhook',
'url': 'https://blabla'
})
cloud = Mock(
hass=hass,
id_token='mock-id-token',
cloudhook_create_url='https://example.com/bla',
)
resp = await cloud_api.async_create_cloudhook(cloud)
assert len(aioclient_mock.mock_calls) == 1
assert await resp.json() == {
'cloudhook_id': 'mock-webhook',
'url': 'https://blabla'
}
-96
View File
@@ -1,96 +0,0 @@
"""Test cloud cloudhooks."""
from unittest.mock import Mock
import pytest
from homeassistant.components.cloud import prefs, cloudhooks
from tests.common import mock_coro
@pytest.fixture
def mock_cloudhooks(hass):
"""Mock cloudhooks class."""
cloud = Mock()
cloud.hass = hass
cloud.hass.async_add_executor_job = Mock(return_value=mock_coro())
cloud.iot = Mock(async_send_message=Mock(return_value=mock_coro()))
cloud.cloudhook_create_url = 'https://webhook-create.url'
cloud.prefs = prefs.CloudPreferences(hass)
hass.loop.run_until_complete(cloud.prefs.async_initialize())
return cloudhooks.Cloudhooks(cloud)
async def test_enable(mock_cloudhooks, aioclient_mock):
"""Test enabling cloudhooks."""
aioclient_mock.post('https://webhook-create.url', json={
'cloudhook_id': 'mock-cloud-id',
'url': 'https://hooks.nabu.casa/ZXCZCXZ',
})
hook = {
'webhook_id': 'mock-webhook-id',
'cloudhook_id': 'mock-cloud-id',
'cloudhook_url': 'https://hooks.nabu.casa/ZXCZCXZ',
}
assert hook == await mock_cloudhooks.async_create('mock-webhook-id')
assert mock_cloudhooks.cloud.prefs.cloudhooks == {
'mock-webhook-id': hook
}
publish_calls = mock_cloudhooks.cloud.iot.async_send_message.mock_calls
assert len(publish_calls) == 1
assert publish_calls[0][1][0] == 'webhook-register'
assert publish_calls[0][1][1] == {
'cloudhook_ids': ['mock-cloud-id']
}
async def test_disable(mock_cloudhooks):
"""Test disabling cloudhooks."""
mock_cloudhooks.cloud.prefs._prefs['cloudhooks'] = {
'mock-webhook-id': {
'webhook_id': 'mock-webhook-id',
'cloudhook_id': 'mock-cloud-id',
'cloudhook_url': 'https://hooks.nabu.casa/ZXCZCXZ',
}
}
await mock_cloudhooks.async_delete('mock-webhook-id')
assert mock_cloudhooks.cloud.prefs.cloudhooks == {}
publish_calls = mock_cloudhooks.cloud.iot.async_send_message.mock_calls
assert len(publish_calls) == 1
assert publish_calls[0][1][0] == 'webhook-register'
assert publish_calls[0][1][1] == {
'cloudhook_ids': []
}
async def test_create_without_connected(mock_cloudhooks, aioclient_mock):
"""Test we don't publish a hook if not connected."""
mock_cloudhooks.cloud.is_connected = False
# Make sure we fail test when we send a message.
mock_cloudhooks.cloud.iot.async_send_message.side_effect = ValueError
aioclient_mock.post('https://webhook-create.url', json={
'cloudhook_id': 'mock-cloud-id',
'url': 'https://hooks.nabu.casa/ZXCZCXZ',
})
hook = {
'webhook_id': 'mock-webhook-id',
'cloudhook_id': 'mock-cloud-id',
'cloudhook_url': 'https://hooks.nabu.casa/ZXCZCXZ',
}
assert hook == await mock_cloudhooks.async_create('mock-webhook-id')
assert mock_cloudhooks.cloud.prefs.cloudhooks == {
'mock-webhook-id': hook
}
assert len(mock_cloudhooks.cloud.iot.async_send_message.mock_calls) == 0
+83 -101
View File
@@ -4,11 +4,11 @@ from unittest.mock import patch, MagicMock
import pytest
from jose import jwt
from hass_nabucasa.auth import Unauthenticated, UnknownError
from hass_nabucasa.const import STATE_CONNECTED
from homeassistant.components.cloud import (
DOMAIN, auth_api, iot)
from homeassistant.components.cloud.const import (
PREF_ENABLE_GOOGLE, PREF_ENABLE_ALEXA, PREF_GOOGLE_ALLOW_UNLOCK)
PREF_ENABLE_GOOGLE, PREF_ENABLE_ALEXA, PREF_GOOGLE_ALLOW_UNLOCK, DOMAIN)
from homeassistant.util import dt as dt_util
from tests.common import mock_coro
@@ -22,12 +22,12 @@ SUBSCRIPTION_INFO_URL = 'https://api-test.hass.io/subscription_info'
@pytest.fixture()
def mock_auth():
"""Mock check token."""
with patch('homeassistant.components.cloud.auth_api.check_token'):
with patch('hass_nabucasa.auth.CognitoAuth.check_token'):
yield
@pytest.fixture(autouse=True)
def setup_api(hass):
def setup_api(hass, aioclient_mock):
"""Initialize HTTP API."""
mock_cloud(hass, {
'mode': 'development',
@@ -54,14 +54,14 @@ def setup_api(hass):
@pytest.fixture
def cloud_client(hass, hass_client):
"""Fixture that can fetch from the cloud client."""
with patch('homeassistant.components.cloud.Cloud.write_user_info'):
with patch('hass_nabucasa.Cloud.write_user_info'):
yield hass.loop.run_until_complete(hass_client())
@pytest.fixture
def mock_cognito():
"""Mock warrant."""
with patch('homeassistant.components.cloud.auth_api._cognito') as mock_cog:
with patch('hass_nabucasa.auth.CognitoAuth._cognito') as mock_cog:
yield mock_cog()
@@ -80,8 +80,7 @@ async def test_google_actions_sync_fails(mock_cognito, cloud_client,
assert req.status == 403
@asyncio.coroutine
def test_login_view(hass, cloud_client, mock_cognito):
async def test_login_view(hass, cloud_client, mock_cognito):
"""Test logging in."""
mock_cognito.id_token = jwt.encode({
'email': 'hello@home-assistant.io',
@@ -90,23 +89,22 @@ def test_login_view(hass, cloud_client, mock_cognito):
mock_cognito.access_token = 'access_token'
mock_cognito.refresh_token = 'refresh_token'
with patch('homeassistant.components.cloud.iot.CloudIoT.'
'connect') as mock_connect, \
patch('homeassistant.components.cloud.auth_api._authenticate',
with patch('hass_nabucasa.iot.CloudIoT.connect') as mock_connect, \
patch('hass_nabucasa.auth.CognitoAuth._authenticate',
return_value=mock_cognito) as mock_auth:
req = yield from cloud_client.post('/api/cloud/login', json={
req = await cloud_client.post('/api/cloud/login', json={
'email': 'my_username',
'password': 'my_password'
})
assert req.status == 200
result = yield from req.json()
result = await req.json()
assert result == {'success': True}
assert len(mock_connect.mock_calls) == 1
assert len(mock_auth.mock_calls) == 1
cloud, result_user, result_pass = mock_auth.mock_calls[0][1]
result_user, result_pass = mock_auth.mock_calls[0][1]
assert result_user == 'my_username'
assert result_pass == 'my_password'
@@ -123,32 +121,29 @@ async def test_login_view_random_exception(cloud_client):
assert resp == {'code': 'valueerror', 'message': 'Unexpected error: Boom'}
@asyncio.coroutine
def test_login_view_invalid_json(cloud_client):
async def test_login_view_invalid_json(cloud_client):
"""Try logging in with invalid JSON."""
with patch('homeassistant.components.cloud.auth_api.login') as mock_login:
req = yield from cloud_client.post('/api/cloud/login', data='Not JSON')
with patch('hass_nabucasa.auth.CognitoAuth.login') as mock_login:
req = await cloud_client.post('/api/cloud/login', data='Not JSON')
assert req.status == 400
assert len(mock_login.mock_calls) == 0
@asyncio.coroutine
def test_login_view_invalid_schema(cloud_client):
async def test_login_view_invalid_schema(cloud_client):
"""Try logging in with invalid schema."""
with patch('homeassistant.components.cloud.auth_api.login') as mock_login:
req = yield from cloud_client.post('/api/cloud/login', json={
with patch('hass_nabucasa.auth.CognitoAuth.login') as mock_login:
req = await cloud_client.post('/api/cloud/login', json={
'invalid': 'schema'
})
assert req.status == 400
assert len(mock_login.mock_calls) == 0
@asyncio.coroutine
def test_login_view_request_timeout(cloud_client):
async def test_login_view_request_timeout(cloud_client):
"""Test request timeout while trying to log in."""
with patch('homeassistant.components.cloud.auth_api.login',
with patch('hass_nabucasa.auth.CognitoAuth.login',
side_effect=asyncio.TimeoutError):
req = yield from cloud_client.post('/api/cloud/login', json={
req = await cloud_client.post('/api/cloud/login', json={
'email': 'my_username',
'password': 'my_password'
})
@@ -156,12 +151,11 @@ def test_login_view_request_timeout(cloud_client):
assert req.status == 502
@asyncio.coroutine
def test_login_view_invalid_credentials(cloud_client):
async def test_login_view_invalid_credentials(cloud_client):
"""Test logging in with invalid credentials."""
with patch('homeassistant.components.cloud.auth_api.login',
side_effect=auth_api.Unauthenticated):
req = yield from cloud_client.post('/api/cloud/login', json={
with patch('hass_nabucasa.auth.CognitoAuth.login',
side_effect=Unauthenticated):
req = await cloud_client.post('/api/cloud/login', json={
'email': 'my_username',
'password': 'my_password'
})
@@ -169,12 +163,11 @@ def test_login_view_invalid_credentials(cloud_client):
assert req.status == 401
@asyncio.coroutine
def test_login_view_unknown_error(cloud_client):
async def test_login_view_unknown_error(cloud_client):
"""Test unknown error while logging in."""
with patch('homeassistant.components.cloud.auth_api.login',
side_effect=auth_api.UnknownError):
req = yield from cloud_client.post('/api/cloud/login', json={
with patch('hass_nabucasa.auth.CognitoAuth.login',
side_effect=UnknownError):
req = await cloud_client.post('/api/cloud/login', json={
'email': 'my_username',
'password': 'my_password'
})
@@ -182,40 +175,36 @@ def test_login_view_unknown_error(cloud_client):
assert req.status == 502
@asyncio.coroutine
def test_logout_view(hass, cloud_client):
async def test_logout_view(hass, cloud_client):
"""Test logging out."""
cloud = hass.data['cloud'] = MagicMock()
cloud.logout.return_value = mock_coro()
req = yield from cloud_client.post('/api/cloud/logout')
req = await cloud_client.post('/api/cloud/logout')
assert req.status == 200
data = yield from req.json()
data = await req.json()
assert data == {'message': 'ok'}
assert len(cloud.logout.mock_calls) == 1
@asyncio.coroutine
def test_logout_view_request_timeout(hass, cloud_client):
async def test_logout_view_request_timeout(hass, cloud_client):
"""Test timeout while logging out."""
cloud = hass.data['cloud'] = MagicMock()
cloud.logout.side_effect = asyncio.TimeoutError
req = yield from cloud_client.post('/api/cloud/logout')
req = await cloud_client.post('/api/cloud/logout')
assert req.status == 502
@asyncio.coroutine
def test_logout_view_unknown_error(hass, cloud_client):
async def test_logout_view_unknown_error(hass, cloud_client):
"""Test unknown error while logging out."""
cloud = hass.data['cloud'] = MagicMock()
cloud.logout.side_effect = auth_api.UnknownError
req = yield from cloud_client.post('/api/cloud/logout')
cloud.logout.side_effect = UnknownError
req = await cloud_client.post('/api/cloud/logout')
assert req.status == 502
@asyncio.coroutine
def test_register_view(mock_cognito, cloud_client):
async def test_register_view(mock_cognito, cloud_client):
"""Test logging out."""
req = yield from cloud_client.post('/api/cloud/register', json={
req = await cloud_client.post('/api/cloud/register', json={
'email': 'hello@bla.com',
'password': 'falcon42'
})
@@ -226,10 +215,9 @@ def test_register_view(mock_cognito, cloud_client):
assert result_pass == 'falcon42'
@asyncio.coroutine
def test_register_view_bad_data(mock_cognito, cloud_client):
async def test_register_view_bad_data(mock_cognito, cloud_client):
"""Test logging out."""
req = yield from cloud_client.post('/api/cloud/register', json={
req = await cloud_client.post('/api/cloud/register', json={
'email': 'hello@bla.com',
'not_password': 'falcon'
})
@@ -237,105 +225,95 @@ def test_register_view_bad_data(mock_cognito, cloud_client):
assert len(mock_cognito.logout.mock_calls) == 0
@asyncio.coroutine
def test_register_view_request_timeout(mock_cognito, cloud_client):
async def test_register_view_request_timeout(mock_cognito, cloud_client):
"""Test timeout while logging out."""
mock_cognito.register.side_effect = asyncio.TimeoutError
req = yield from cloud_client.post('/api/cloud/register', json={
req = await cloud_client.post('/api/cloud/register', json={
'email': 'hello@bla.com',
'password': 'falcon42'
})
assert req.status == 502
@asyncio.coroutine
def test_register_view_unknown_error(mock_cognito, cloud_client):
async def test_register_view_unknown_error(mock_cognito, cloud_client):
"""Test unknown error while logging out."""
mock_cognito.register.side_effect = auth_api.UnknownError
req = yield from cloud_client.post('/api/cloud/register', json={
mock_cognito.register.side_effect = UnknownError
req = await cloud_client.post('/api/cloud/register', json={
'email': 'hello@bla.com',
'password': 'falcon42'
})
assert req.status == 502
@asyncio.coroutine
def test_forgot_password_view(mock_cognito, cloud_client):
async def test_forgot_password_view(mock_cognito, cloud_client):
"""Test logging out."""
req = yield from cloud_client.post('/api/cloud/forgot_password', json={
req = await cloud_client.post('/api/cloud/forgot_password', json={
'email': 'hello@bla.com',
})
assert req.status == 200
assert len(mock_cognito.initiate_forgot_password.mock_calls) == 1
@asyncio.coroutine
def test_forgot_password_view_bad_data(mock_cognito, cloud_client):
async def test_forgot_password_view_bad_data(mock_cognito, cloud_client):
"""Test logging out."""
req = yield from cloud_client.post('/api/cloud/forgot_password', json={
req = await cloud_client.post('/api/cloud/forgot_password', json={
'not_email': 'hello@bla.com',
})
assert req.status == 400
assert len(mock_cognito.initiate_forgot_password.mock_calls) == 0
@asyncio.coroutine
def test_forgot_password_view_request_timeout(mock_cognito, cloud_client):
async def test_forgot_password_view_request_timeout(mock_cognito,
cloud_client):
"""Test timeout while logging out."""
mock_cognito.initiate_forgot_password.side_effect = asyncio.TimeoutError
req = yield from cloud_client.post('/api/cloud/forgot_password', json={
req = await cloud_client.post('/api/cloud/forgot_password', json={
'email': 'hello@bla.com',
})
assert req.status == 502
@asyncio.coroutine
def test_forgot_password_view_unknown_error(mock_cognito, cloud_client):
async def test_forgot_password_view_unknown_error(mock_cognito, cloud_client):
"""Test unknown error while logging out."""
mock_cognito.initiate_forgot_password.side_effect = auth_api.UnknownError
req = yield from cloud_client.post('/api/cloud/forgot_password', json={
mock_cognito.initiate_forgot_password.side_effect = UnknownError
req = await cloud_client.post('/api/cloud/forgot_password', json={
'email': 'hello@bla.com',
})
assert req.status == 502
@asyncio.coroutine
def test_resend_confirm_view(mock_cognito, cloud_client):
async def test_resend_confirm_view(mock_cognito, cloud_client):
"""Test logging out."""
req = yield from cloud_client.post('/api/cloud/resend_confirm', json={
req = await cloud_client.post('/api/cloud/resend_confirm', json={
'email': 'hello@bla.com',
})
assert req.status == 200
assert len(mock_cognito.client.resend_confirmation_code.mock_calls) == 1
@asyncio.coroutine
def test_resend_confirm_view_bad_data(mock_cognito, cloud_client):
async def test_resend_confirm_view_bad_data(mock_cognito, cloud_client):
"""Test logging out."""
req = yield from cloud_client.post('/api/cloud/resend_confirm', json={
req = await cloud_client.post('/api/cloud/resend_confirm', json={
'not_email': 'hello@bla.com',
})
assert req.status == 400
assert len(mock_cognito.client.resend_confirmation_code.mock_calls) == 0
@asyncio.coroutine
def test_resend_confirm_view_request_timeout(mock_cognito, cloud_client):
async def test_resend_confirm_view_request_timeout(mock_cognito, cloud_client):
"""Test timeout while logging out."""
mock_cognito.client.resend_confirmation_code.side_effect = \
asyncio.TimeoutError
req = yield from cloud_client.post('/api/cloud/resend_confirm', json={
req = await cloud_client.post('/api/cloud/resend_confirm', json={
'email': 'hello@bla.com',
})
assert req.status == 502
@asyncio.coroutine
def test_resend_confirm_view_unknown_error(mock_cognito, cloud_client):
async def test_resend_confirm_view_unknown_error(mock_cognito, cloud_client):
"""Test unknown error while logging out."""
mock_cognito.client.resend_confirmation_code.side_effect = \
auth_api.UnknownError
req = yield from cloud_client.post('/api/cloud/resend_confirm', json={
mock_cognito.client.resend_confirmation_code.side_effect = UnknownError
req = await cloud_client.post('/api/cloud/resend_confirm', json={
'email': 'hello@bla.com',
})
assert req.status == 502
@@ -347,7 +325,7 @@ async def test_websocket_status(hass, hass_ws_client, mock_cloud_fixture):
'email': 'hello@home-assistant.io',
'custom:sub-exp': '2018-01-03'
}, 'test')
hass.data[DOMAIN].iot.state = iot.STATE_CONNECTED
hass.data[DOMAIN].iot.state = STATE_CONNECTED
client = await hass_ws_client(hass)
with patch.dict(
@@ -407,9 +385,9 @@ async def test_websocket_subscription_reconnect(
client = await hass_ws_client(hass)
with patch(
'homeassistant.components.cloud.auth_api.renew_access_token'
'hass_nabucasa.auth.CognitoAuth.renew_access_token'
) as mock_renew, patch(
'homeassistant.components.cloud.iot.CloudIoT.connect'
'hass_nabucasa.iot.CloudIoT.connect'
) as mock_connect:
await client.send_json({
'id': 5,
@@ -428,7 +406,7 @@ async def test_websocket_subscription_no_reconnect_if_connected(
hass, hass_ws_client, aioclient_mock, mock_auth):
"""Test querying the status and not reconnecting because still expired."""
aioclient_mock.get(SUBSCRIPTION_INFO_URL, json={'provider': 'stripe'})
hass.data[DOMAIN].iot.state = iot.STATE_CONNECTED
hass.data[DOMAIN].iot.state = STATE_CONNECTED
hass.data[DOMAIN].id_token = jwt.encode({
'email': 'hello@home-assistant.io',
'custom:sub-exp': dt_util.utcnow().date().isoformat()
@@ -436,9 +414,9 @@ async def test_websocket_subscription_no_reconnect_if_connected(
client = await hass_ws_client(hass)
with patch(
'homeassistant.components.cloud.auth_api.renew_access_token'
'hass_nabucasa.auth.CognitoAuth.renew_access_token'
) as mock_renew, patch(
'homeassistant.components.cloud.iot.CloudIoT.connect'
'hass_nabucasa.iot.CloudIoT.connect'
) as mock_connect:
await client.send_json({
'id': 5,
@@ -464,9 +442,9 @@ async def test_websocket_subscription_no_reconnect_if_expired(
client = await hass_ws_client(hass)
with patch(
'homeassistant.components.cloud.auth_api.renew_access_token'
'hass_nabucasa.auth.CognitoAuth.renew_access_token'
) as mock_renew, patch(
'homeassistant.components.cloud.iot.CloudIoT.connect'
'hass_nabucasa.iot.CloudIoT.connect'
) as mock_connect:
await client.send_json({
'id': 5,
@@ -503,7 +481,7 @@ async def test_websocket_subscription_fail(hass, hass_ws_client,
async def test_websocket_subscription_not_logged_in(hass, hass_ws_client):
"""Test querying the status."""
client = await hass_ws_client(hass)
with patch('homeassistant.components.cloud.Cloud.fetch_subscription_info',
with patch('hass_nabucasa.Cloud.fetch_subscription_info',
return_value=mock_coro({'return': 'value'})):
await client.send_json({
'id': 5,
@@ -548,8 +526,10 @@ async def test_enabling_webhook(hass, hass_ws_client, setup_api):
'custom:sub-exp': '2018-01-03'
}, 'test')
client = await hass_ws_client(hass)
with patch('homeassistant.components.cloud.cloudhooks.Cloudhooks'
'.async_create', return_value=mock_coro()) as mock_enable:
with patch(
'hass_nabucasa.cloudhooks.Cloudhooks.async_create',
return_value=mock_coro()
) as mock_enable:
await client.send_json({
'id': 5,
'type': 'cloud/cloudhook/create',
@@ -569,8 +549,10 @@ async def test_disabling_webhook(hass, hass_ws_client, setup_api):
'custom:sub-exp': '2018-01-03'
}, 'test')
client = await hass_ws_client(hass)
with patch('homeassistant.components.cloud.cloudhooks.Cloudhooks'
'.async_delete', return_value=mock_coro()) as mock_disable:
with patch(
'hass_nabucasa.cloudhooks.Cloudhooks.async_delete',
return_value=mock_coro()
) as mock_disable:
await client.send_json({
'id': 5,
'type': 'cloud/cloudhook/delete',
+49 -241
View File
@@ -1,72 +1,34 @@
"""Test the cloud component."""
import asyncio
import json
from unittest.mock import patch, MagicMock, mock_open
from unittest.mock import MagicMock, patch
import pytest
from homeassistant.setup import async_setup_component
from homeassistant.const import (
EVENT_HOMEASSISTANT_STOP, EVENT_HOMEASSISTANT_START)
from homeassistant.components import cloud
from homeassistant.util.dt import utcnow
from homeassistant.components.cloud.const import DOMAIN
from tests.common import mock_coro
@pytest.fixture
def mock_os():
"""Mock os module."""
with patch('homeassistant.components.cloud.os') as os:
os.path.isdir.return_value = True
yield os
@asyncio.coroutine
def test_constructor_loads_info_from_constant():
async def test_constructor_loads_info_from_config():
"""Test non-dev mode loads info from SERVERS constant."""
hass = MagicMock(data={})
with patch.dict(cloud.SERVERS, {
'beer': {
'cognito_client_id': 'test-cognito_client_id',
'user_pool_id': 'test-user_pool_id',
'region': 'test-region',
'relayer': 'test-relayer',
'google_actions_sync_url': 'test-google_actions_sync_url',
'subscription_info_url': 'test-subscription-info-url',
'cloudhook_create_url': 'test-cloudhook_create_url',
}
}):
result = yield from cloud.async_setup(hass, {
'cloud': {cloud.CONF_MODE: 'beer'}
with patch(
"homeassistant.components.cloud.prefs.CloudPreferences."
"async_initialize",
return_value=mock_coro()
):
result = await cloud.async_setup(hass, {
'cloud': {
cloud.CONF_MODE: cloud.MODE_DEV,
'cognito_client_id': 'test-cognito_client_id',
'user_pool_id': 'test-user_pool_id',
'region': 'test-region',
'relayer': 'test-relayer',
}
})
assert result
cl = hass.data['cloud']
assert cl.mode == 'beer'
assert cl.cognito_client_id == 'test-cognito_client_id'
assert cl.user_pool_id == 'test-user_pool_id'
assert cl.region == 'test-region'
assert cl.relayer == 'test-relayer'
assert cl.google_actions_sync_url == 'test-google_actions_sync_url'
assert cl.subscription_info_url == 'test-subscription-info-url'
assert cl.cloudhook_create_url == 'test-cloudhook_create_url'
@asyncio.coroutine
def test_constructor_loads_info_from_config():
"""Test non-dev mode loads info from SERVERS constant."""
hass = MagicMock(data={})
result = yield from cloud.async_setup(hass, {
'cloud': {
cloud.CONF_MODE: cloud.MODE_DEV,
'cognito_client_id': 'test-cognito_client_id',
'user_pool_id': 'test-user_pool_id',
'region': 'test-region',
'relayer': 'test-relayer',
}
})
assert result
cl = hass.data['cloud']
assert cl.mode == cloud.MODE_DEV
assert cl.cognito_client_id == 'test-cognito_client_id'
@@ -75,195 +37,41 @@ def test_constructor_loads_info_from_config():
assert cl.relayer == 'test-relayer'
async def test_initialize_loads_info(mock_os, hass):
"""Test initialize will load info from config file."""
mock_os.path.isfile.return_value = True
mopen = mock_open(read_data=json.dumps({
'id_token': 'test-id-token',
'access_token': 'test-access-token',
'refresh_token': 'test-refresh-token',
}))
async def test_remote_services(hass, mock_cloud_fixture):
"""Setup cloud component and test services."""
assert hass.services.has_service(DOMAIN, 'remote_connect')
assert hass.services.has_service(DOMAIN, 'remote_disconnect')
cl = cloud.Cloud(hass, cloud.MODE_DEV, None, None)
cl.iot = MagicMock()
cl.iot.connect.return_value = mock_coro()
with patch(
"hass_nabucasa.remote.RemoteUI.connect", return_value=mock_coro()
) as mock_connect:
await hass.services.async_call(DOMAIN, "remote_connect", blocking=True)
with patch('homeassistant.components.cloud.open', mopen, create=True), \
patch('homeassistant.components.cloud.Cloud._decode_claims'):
await cl.async_start(None)
assert mock_connect.called
assert cl.id_token == 'test-id-token'
assert cl.access_token == 'test-access-token'
assert cl.refresh_token == 'test-refresh-token'
assert len(cl.iot.connect.mock_calls) == 1
with patch(
"hass_nabucasa.remote.RemoteUI.disconnect", return_value=mock_coro()
) as mock_disconnect:
await hass.services.async_call(
DOMAIN, "remote_disconnect", blocking=True)
assert mock_disconnect.called
@asyncio.coroutine
def test_logout_clears_info(mock_os, hass):
"""Test logging out disconnects and removes info."""
cl = cloud.Cloud(hass, cloud.MODE_DEV, None, None)
cl.iot = MagicMock()
cl.iot.disconnect.return_value = mock_coro()
async def test_startup_shutdown_events(hass, mock_cloud_fixture):
"""Test if the cloud will start on startup event."""
with patch(
"hass_nabucasa.Cloud.start", return_value=mock_coro()
) as mock_start:
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
yield from cl.logout()
assert mock_start.called
assert len(cl.iot.disconnect.mock_calls) == 1
assert cl.id_token is None
assert cl.access_token is None
assert cl.refresh_token is None
assert len(mock_os.remove.mock_calls) == 1
with patch(
"hass_nabucasa.Cloud.stop", return_value=mock_coro()
) as mock_stop:
hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
await hass.async_block_till_done()
@asyncio.coroutine
def test_write_user_info():
"""Test writing user info works."""
mopen = mock_open()
cl = cloud.Cloud(MagicMock(), cloud.MODE_DEV, None, None)
cl.id_token = 'test-id-token'
cl.access_token = 'test-access-token'
cl.refresh_token = 'test-refresh-token'
with patch('homeassistant.components.cloud.open', mopen, create=True):
cl.write_user_info()
handle = mopen()
assert len(handle.write.mock_calls) == 1
data = json.loads(handle.write.mock_calls[0][1][0])
assert data == {
'access_token': 'test-access-token',
'id_token': 'test-id-token',
'refresh_token': 'test-refresh-token',
}
@asyncio.coroutine
def test_subscription_expired(hass):
"""Test subscription being expired after 3 days of expiration."""
cl = cloud.Cloud(hass, cloud.MODE_DEV, None, None)
token_val = {
'custom:sub-exp': '2017-11-13'
}
with patch.object(cl, '_decode_claims', return_value=token_val), \
patch('homeassistant.util.dt.utcnow',
return_value=utcnow().replace(year=2017, month=11, day=13)):
assert not cl.subscription_expired
with patch.object(cl, '_decode_claims', return_value=token_val), \
patch('homeassistant.util.dt.utcnow',
return_value=utcnow().replace(
year=2017, month=11, day=19, hour=23, minute=59,
second=59)):
assert not cl.subscription_expired
with patch.object(cl, '_decode_claims', return_value=token_val), \
patch('homeassistant.util.dt.utcnow',
return_value=utcnow().replace(
year=2017, month=11, day=20, hour=0, minute=0,
second=0)):
assert cl.subscription_expired
@asyncio.coroutine
def test_subscription_not_expired(hass):
"""Test subscription not being expired."""
cl = cloud.Cloud(hass, cloud.MODE_DEV, None, None)
token_val = {
'custom:sub-exp': '2017-11-13'
}
with patch.object(cl, '_decode_claims', return_value=token_val), \
patch('homeassistant.util.dt.utcnow',
return_value=utcnow().replace(year=2017, month=11, day=9)):
assert not cl.subscription_expired
async def test_create_cloudhook_no_login(hass):
"""Test create cloudhook when not logged in."""
assert await async_setup_component(hass, 'cloud', {})
coro = mock_coro({'yo': 'hey'})
with patch('homeassistant.components.cloud.cloudhooks.'
'Cloudhooks.async_create', return_value=coro) as mock_create, \
pytest.raises(cloud.CloudNotAvailable):
await hass.components.cloud.async_create_cloudhook('hello')
assert len(mock_create.mock_calls) == 0
async def test_delete_cloudhook_no_setup(hass):
"""Test delete cloudhook when not logged in."""
coro = mock_coro()
with patch('homeassistant.components.cloud.cloudhooks.'
'Cloudhooks.async_delete', return_value=coro) as mock_delete, \
pytest.raises(cloud.CloudNotAvailable):
await hass.components.cloud.async_delete_cloudhook('hello')
assert len(mock_delete.mock_calls) == 0
async def test_create_cloudhook(hass):
"""Test create cloudhook."""
assert await async_setup_component(hass, 'cloud', {})
coro = mock_coro({'cloudhook_url': 'hello'})
with patch('homeassistant.components.cloud.cloudhooks.'
'Cloudhooks.async_create', return_value=coro) as mock_create, \
patch('homeassistant.components.cloud.async_is_logged_in',
return_value=True):
result = await hass.components.cloud.async_create_cloudhook('hello')
assert result == 'hello'
assert len(mock_create.mock_calls) == 1
async def test_delete_cloudhook(hass):
"""Test delete cloudhook."""
assert await async_setup_component(hass, 'cloud', {})
coro = mock_coro()
with patch('homeassistant.components.cloud.cloudhooks.'
'Cloudhooks.async_delete', return_value=coro) as mock_delete, \
patch('homeassistant.components.cloud.async_is_logged_in',
return_value=True):
await hass.components.cloud.async_delete_cloudhook('hello')
assert len(mock_delete.mock_calls) == 1
async def test_async_logged_in(hass):
"""Test if is_logged_in works."""
# Cloud not loaded
assert hass.components.cloud.async_is_logged_in() is False
assert await async_setup_component(hass, 'cloud', {})
# Cloud loaded, not logged in
assert hass.components.cloud.async_is_logged_in() is False
hass.data['cloud'].id_token = "some token"
# Cloud loaded, logged in
assert hass.components.cloud.async_is_logged_in() is True
async def test_async_active_subscription(hass):
"""Test if is_logged_in works."""
# Cloud not loaded
assert hass.components.cloud.async_active_subscription() is False
assert await async_setup_component(hass, 'cloud', {})
# Cloud loaded, not logged in
assert hass.components.cloud.async_active_subscription() is False
hass.data['cloud'].id_token = "some token"
# Cloud loaded, logged in, invalid sub
with patch('jose.jwt.get_unverified_claims', return_value={
'custom:sub-exp': '{}-12-31'.format(utcnow().year - 1)
}):
assert hass.components.cloud.async_active_subscription() is False
# Cloud loaded, logged in, valid sub
with patch('jose.jwt.get_unverified_claims', return_value={
'custom:sub-exp': '{}-01-01'.format(utcnow().year + 1)
}):
assert hass.components.cloud.async_active_subscription() is True
assert mock_stop.called
-500
View File
@@ -1,500 +0,0 @@
"""Test the cloud.iot module."""
import asyncio
from unittest.mock import patch, MagicMock, PropertyMock
from aiohttp import WSMsgType, client_exceptions, web
import pytest
from homeassistant.setup import async_setup_component
from homeassistant.components.cloud import (
Cloud, iot, auth_api, MODE_DEV)
from homeassistant.components.cloud.const import (
PREF_ENABLE_ALEXA, PREF_ENABLE_GOOGLE)
from tests.components.alexa import test_smart_home as test_alexa
from tests.common import mock_coro
from . import mock_cloud_prefs
@pytest.fixture
def mock_client():
"""Mock the IoT client."""
client = MagicMock()
type(client).closed = PropertyMock(side_effect=[False, True])
# Trigger cancelled error to avoid reconnect.
with patch('asyncio.sleep', side_effect=asyncio.CancelledError), \
patch('homeassistant.components.cloud.iot'
'.async_get_clientsession') as session:
session().ws_connect.return_value = mock_coro(client)
yield client
@pytest.fixture
def mock_handle_message():
"""Mock handle message."""
with patch('homeassistant.components.cloud.iot'
'.async_handle_message') as mock:
yield mock
@pytest.fixture
def mock_cloud():
"""Mock cloud class."""
return MagicMock(subscription_expired=False)
@asyncio.coroutine
def test_cloud_calling_handler(mock_client, mock_handle_message, mock_cloud):
"""Test we call handle message with correct info."""
conn = iot.CloudIoT(mock_cloud)
mock_client.receive.return_value = mock_coro(MagicMock(
type=WSMsgType.text,
json=MagicMock(return_value={
'msgid': 'test-msg-id',
'handler': 'test-handler',
'payload': 'test-payload'
})
))
mock_handle_message.return_value = mock_coro('response')
mock_client.send_json.return_value = mock_coro(None)
yield from conn.connect()
# Check that we sent message to handler correctly
assert len(mock_handle_message.mock_calls) == 1
p_hass, p_cloud, handler_name, payload = \
mock_handle_message.mock_calls[0][1]
assert p_hass is mock_cloud.hass
assert p_cloud is mock_cloud
assert handler_name == 'test-handler'
assert payload == 'test-payload'
# Check that we forwarded response from handler to cloud
assert len(mock_client.send_json.mock_calls) == 1
assert mock_client.send_json.mock_calls[0][1][0] == {
'msgid': 'test-msg-id',
'payload': 'response'
}
@asyncio.coroutine
def test_connection_msg_for_unknown_handler(mock_client, mock_cloud):
"""Test a msg for an unknown handler."""
conn = iot.CloudIoT(mock_cloud)
mock_client.receive.return_value = mock_coro(MagicMock(
type=WSMsgType.text,
json=MagicMock(return_value={
'msgid': 'test-msg-id',
'handler': 'non-existing-handler',
'payload': 'test-payload'
})
))
mock_client.send_json.return_value = mock_coro(None)
yield from conn.connect()
# Check that we sent the correct error
assert len(mock_client.send_json.mock_calls) == 1
assert mock_client.send_json.mock_calls[0][1][0] == {
'msgid': 'test-msg-id',
'error': 'unknown-handler',
}
@asyncio.coroutine
def test_connection_msg_for_handler_raising(mock_client, mock_handle_message,
mock_cloud):
"""Test we sent error when handler raises exception."""
conn = iot.CloudIoT(mock_cloud)
mock_client.receive.return_value = mock_coro(MagicMock(
type=WSMsgType.text,
json=MagicMock(return_value={
'msgid': 'test-msg-id',
'handler': 'test-handler',
'payload': 'test-payload'
})
))
mock_handle_message.side_effect = Exception('Broken')
mock_client.send_json.return_value = mock_coro(None)
yield from conn.connect()
# Check that we sent the correct error
assert len(mock_client.send_json.mock_calls) == 1
assert mock_client.send_json.mock_calls[0][1][0] == {
'msgid': 'test-msg-id',
'error': 'exception',
}
@asyncio.coroutine
def test_handler_forwarding():
"""Test we forward messages to correct handler."""
handler = MagicMock()
handler.return_value = mock_coro()
hass = object()
cloud = object()
with patch.dict(iot.HANDLERS, {'test': handler}):
yield from iot.async_handle_message(
hass, cloud, 'test', 'payload')
assert len(handler.mock_calls) == 1
r_hass, r_cloud, payload = handler.mock_calls[0][1]
assert r_hass is hass
assert r_cloud is cloud
assert payload == 'payload'
async def test_handling_core_messages_logout(hass, mock_cloud):
"""Test handling core messages."""
mock_cloud.logout.return_value = mock_coro()
await iot.async_handle_cloud(hass, mock_cloud, {
'action': 'logout',
'reason': 'Logged in at two places.'
})
assert len(mock_cloud.logout.mock_calls) == 1
@asyncio.coroutine
def test_cloud_getting_disconnected_by_server(mock_client, caplog, mock_cloud):
"""Test server disconnecting instance."""
conn = iot.CloudIoT(mock_cloud)
mock_client.receive.return_value = mock_coro(MagicMock(
type=WSMsgType.CLOSING,
))
with patch('asyncio.sleep', side_effect=[None, asyncio.CancelledError]):
yield from conn.connect()
assert 'Connection closed' in caplog.text
@asyncio.coroutine
def test_cloud_receiving_bytes(mock_client, caplog, mock_cloud):
"""Test server disconnecting instance."""
conn = iot.CloudIoT(mock_cloud)
mock_client.receive.return_value = mock_coro(MagicMock(
type=WSMsgType.BINARY,
))
yield from conn.connect()
assert 'Connection closed: Received non-Text message' in caplog.text
@asyncio.coroutine
def test_cloud_sending_invalid_json(mock_client, caplog, mock_cloud):
"""Test cloud sending invalid JSON."""
conn = iot.CloudIoT(mock_cloud)
mock_client.receive.return_value = mock_coro(MagicMock(
type=WSMsgType.TEXT,
json=MagicMock(side_effect=ValueError)
))
yield from conn.connect()
assert 'Connection closed: Received invalid JSON.' in caplog.text
@asyncio.coroutine
def test_cloud_check_token_raising(mock_client, caplog, mock_cloud):
"""Test cloud unable to check token."""
conn = iot.CloudIoT(mock_cloud)
mock_cloud.hass.async_add_job.side_effect = auth_api.CloudError("BLA")
yield from conn.connect()
assert 'Unable to refresh token: BLA' in caplog.text
@asyncio.coroutine
def test_cloud_connect_invalid_auth(mock_client, caplog, mock_cloud):
"""Test invalid auth detected by server."""
conn = iot.CloudIoT(mock_cloud)
mock_client.receive.side_effect = \
client_exceptions.WSServerHandshakeError(None, None, status=401)
yield from conn.connect()
assert 'Connection closed: Invalid auth.' in caplog.text
@asyncio.coroutine
def test_cloud_unable_to_connect(mock_client, caplog, mock_cloud):
"""Test unable to connect error."""
conn = iot.CloudIoT(mock_cloud)
mock_client.receive.side_effect = client_exceptions.ClientError(None, None)
yield from conn.connect()
assert 'Unable to connect:' in caplog.text
@asyncio.coroutine
def test_cloud_random_exception(mock_client, caplog, mock_cloud):
"""Test random exception."""
conn = iot.CloudIoT(mock_cloud)
mock_client.receive.side_effect = Exception
yield from conn.connect()
assert 'Unexpected error' in caplog.text
@asyncio.coroutine
def test_refresh_token_before_expiration_fails(hass, mock_cloud):
"""Test that we don't connect if token is expired."""
mock_cloud.subscription_expired = True
mock_cloud.hass = hass
conn = iot.CloudIoT(mock_cloud)
with patch('homeassistant.components.cloud.auth_api.check_token',
return_value=mock_coro()) as mock_check_token, \
patch.object(hass.components.persistent_notification,
'async_create') as mock_create:
yield from conn.connect()
assert len(mock_check_token.mock_calls) == 1
assert len(mock_create.mock_calls) == 1
@asyncio.coroutine
def test_handler_alexa(hass):
"""Test handler Alexa."""
hass.states.async_set(
'switch.test', 'on', {'friendly_name': "Test switch"})
hass.states.async_set(
'switch.test2', 'on', {'friendly_name': "Test switch 2"})
with patch('homeassistant.components.cloud.Cloud.async_start',
return_value=mock_coro()):
setup = yield from async_setup_component(hass, 'cloud', {
'cloud': {
'alexa': {
'filter': {
'exclude_entities': 'switch.test2'
},
'entity_config': {
'switch.test': {
'name': 'Config name',
'description': 'Config description',
'display_categories': 'LIGHT'
}
}
}
}
})
assert setup
mock_cloud_prefs(hass)
resp = yield from iot.async_handle_alexa(
hass, hass.data['cloud'],
test_alexa.get_new_request('Alexa.Discovery', 'Discover'))
endpoints = resp['event']['payload']['endpoints']
assert len(endpoints) == 1
device = endpoints[0]
assert device['description'] == 'Config description'
assert device['friendlyName'] == 'Config name'
assert device['displayCategories'] == ['LIGHT']
assert device['manufacturerName'] == 'Home Assistant'
@asyncio.coroutine
def test_handler_alexa_disabled(hass, mock_cloud_fixture):
"""Test handler Alexa when user has disabled it."""
mock_cloud_fixture[PREF_ENABLE_ALEXA] = False
resp = yield from iot.async_handle_alexa(
hass, hass.data['cloud'],
test_alexa.get_new_request('Alexa.Discovery', 'Discover'))
assert resp['event']['header']['namespace'] == 'Alexa'
assert resp['event']['header']['name'] == 'ErrorResponse'
assert resp['event']['payload']['type'] == 'BRIDGE_UNREACHABLE'
@asyncio.coroutine
def test_handler_google_actions(hass):
"""Test handler Google Actions."""
hass.states.async_set(
'switch.test', 'on', {'friendly_name': "Test switch"})
hass.states.async_set(
'switch.test2', 'on', {'friendly_name': "Test switch 2"})
hass.states.async_set(
'group.all_locks', 'on', {'friendly_name': "Evil locks"})
with patch('homeassistant.components.cloud.Cloud.async_start',
return_value=mock_coro()):
setup = yield from async_setup_component(hass, 'cloud', {
'cloud': {
'google_actions': {
'filter': {
'exclude_entities': 'switch.test2'
},
'entity_config': {
'switch.test': {
'name': 'Config name',
'aliases': 'Config alias',
'room': 'living room'
}
}
}
}
})
assert setup
mock_cloud_prefs(hass)
reqid = '5711642932632160983'
data = {'requestId': reqid, 'inputs': [{'intent': 'action.devices.SYNC'}]}
with patch('homeassistant.components.cloud.Cloud._decode_claims',
return_value={'cognito:username': 'myUserName'}):
resp = yield from iot.async_handle_google_actions(
hass, hass.data['cloud'], data)
assert resp['requestId'] == reqid
payload = resp['payload']
assert payload['agentUserId'] == 'myUserName'
devices = payload['devices']
assert len(devices) == 1
device = devices[0]
assert device['id'] == 'switch.test'
assert device['name']['name'] == 'Config name'
assert device['name']['nicknames'] == ['Config alias']
assert device['type'] == 'action.devices.types.SWITCH'
assert device['roomHint'] == 'living room'
async def test_handler_google_actions_disabled(hass, mock_cloud_fixture):
"""Test handler Google Actions when user has disabled it."""
mock_cloud_fixture[PREF_ENABLE_GOOGLE] = False
with patch('homeassistant.components.cloud.Cloud.async_start',
return_value=mock_coro()):
assert await async_setup_component(hass, 'cloud', {})
reqid = '5711642932632160983'
data = {'requestId': reqid, 'inputs': [{'intent': 'action.devices.SYNC'}]}
resp = await iot.async_handle_google_actions(
hass, hass.data['cloud'], data)
assert resp['requestId'] == reqid
assert resp['payload']['errorCode'] == 'deviceTurnedOff'
async def test_refresh_token_expired(hass):
"""Test handling Unauthenticated error raised if refresh token expired."""
cloud = Cloud(hass, MODE_DEV, None, None)
with patch('homeassistant.components.cloud.auth_api.check_token',
side_effect=auth_api.Unauthenticated) as mock_check_token, \
patch.object(hass.components.persistent_notification,
'async_create') as mock_create:
await cloud.iot.connect()
assert len(mock_check_token.mock_calls) == 1
assert len(mock_create.mock_calls) == 1
async def test_webhook_msg(hass):
"""Test webhook msg."""
cloud = Cloud(hass, MODE_DEV, None, None)
await cloud.prefs.async_initialize()
await cloud.prefs.async_update(cloudhooks={
'hello': {
'webhook_id': 'mock-webhook-id',
'cloudhook_id': 'mock-cloud-id'
}
})
received = []
async def handler(hass, webhook_id, request):
"""Handle a webhook."""
received.append(request)
return web.json_response({'from': 'handler'})
hass.components.webhook.async_register(
'test', 'Test', 'mock-webhook-id', handler)
response = await iot.async_handle_webhook(hass, cloud, {
'cloudhook_id': 'mock-cloud-id',
'body': '{"hello": "world"}',
'headers': {
'content-type': 'application/json'
},
'method': 'POST',
'query': None,
})
assert response == {
'status': 200,
'body': '{"from": "handler"}',
'headers': {
'Content-Type': 'application/json'
}
}
assert len(received) == 1
assert await received[0].json() == {
'hello': 'world'
}
async def test_send_message_not_connected(mock_cloud):
"""Test sending a message that expects no answer."""
cloud_iot = iot.CloudIoT(mock_cloud)
with pytest.raises(iot.NotConnected):
await cloud_iot.async_send_message('webhook', {'msg': 'yo'})
async def test_send_message_no_answer(mock_cloud):
"""Test sending a message that expects no answer."""
cloud_iot = iot.CloudIoT(mock_cloud)
cloud_iot.state = iot.STATE_CONNECTED
cloud_iot.client = MagicMock(send_json=MagicMock(return_value=mock_coro()))
await cloud_iot.async_send_message('webhook', {'msg': 'yo'},
expect_answer=False)
assert not cloud_iot._response_handler
assert len(cloud_iot.client.send_json.mock_calls) == 1
msg = cloud_iot.client.send_json.mock_calls[0][1][0]
assert msg['handler'] == 'webhook'
assert msg['payload'] == {'msg': 'yo'}
async def test_send_message_answer(loop, mock_cloud):
"""Test sending a message that expects no answer."""
cloud_iot = iot.CloudIoT(mock_cloud)
cloud_iot.state = iot.STATE_CONNECTED
cloud_iot.client = MagicMock(send_json=MagicMock(return_value=mock_coro()))
uuid = 5
with patch('homeassistant.components.cloud.iot.uuid.uuid4',
return_value=MagicMock(hex=uuid)):
send_task = loop.create_task(cloud_iot.async_send_message(
'webhook', {'msg': 'yo'}))
await asyncio.sleep(0)
assert len(cloud_iot.client.send_json.mock_calls) == 1
assert len(cloud_iot._response_handler) == 1
msg = cloud_iot.client.send_json.mock_calls[0][1][0]
assert msg['handler'] == 'webhook'
assert msg['payload'] == {'msg': 'yo'}
cloud_iot._response_handler[uuid].set_result({'response': True})
response = await send_task
assert response == {'response': True}