Add SmartThings component and switch platform (#20148)

* Added SmartThings component and switch platform

* Corrected comment typos.

* Embedded switch platform.

* Replaced custom view usage with webhook component.

* Replaced urls with tokens in strings.

* Fixed line length.

* Use generated webhook id instead of static one.

* Reuse core constant instead of defining again.

* Optimizations in anticipation of future platforms.

* Use async_generate_path instead of hard-coded path.

* Fixed line length.

* Updates per review feedback.

* Updates per latest review feedback.
This commit is contained in:
Andrew Sayre authored and Paulus Schoutsen committed 2019-01-30 17:31:59 -08:00
1 parent 5a0c707a37
commit 69ec7980ad
18 files changed
+1793

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""Tests for the SmartThings component."""
+279
View File
@@ -0,0 +1,279 @@
"""Test configuration and mocks for the SmartThings component."""
from collections import defaultdict
from unittest.mock import Mock, patch
from uuid import uuid4
from pysmartthings import (
CLASSIFICATION_AUTOMATION, AppEntity, AppSettings, DeviceEntity,
InstalledApp, Location)
from pysmartthings.api import Api
import pytest
from homeassistant.components import webhook
from homeassistant.components.smartthings.const import (
APP_NAME_PREFIX, CONF_APP_ID, CONF_INSTALLED_APP_ID, CONF_INSTANCE_ID,
CONF_LOCATION_ID, DOMAIN, SETTINGS_INSTANCE_ID, STORAGE_KEY,
STORAGE_VERSION)
from homeassistant.config_entries import (
CONN_CLASS_CLOUD_PUSH, SOURCE_USER, ConfigEntry)
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_WEBHOOK_ID
from homeassistant.setup import async_setup_component
from tests.common import mock_coro
@pytest.fixture(autouse=True)
async def setup_component(hass, config_file, hass_storage):
"""Load the SmartThing component."""
hass_storage[STORAGE_KEY] = {'data': config_file,
"version": STORAGE_VERSION}
await async_setup_component(hass, 'smartthings', {})
hass.config.api.base_url = 'https://test.local'
def _create_location():
loc = Location()
loc.apply_data({
'name': 'Test Location',
'locationId': str(uuid4())
})
return loc
@pytest.fixture(name='location')
def location_fixture():
"""Fixture for a single location."""
return _create_location()
@pytest.fixture(name='locations')
def locations_fixture(location):
"""Fixture for 2 locations."""
return [location, _create_location()]
@pytest.fixture(name="app")
def app_fixture(hass, config_file):
"""Fixture for a single app."""
app = AppEntity(Mock())
app.apply_data({
'appName': APP_NAME_PREFIX + str(uuid4()),
'appId': str(uuid4()),
'appType': 'WEBHOOK_SMART_APP',
'classifications': [CLASSIFICATION_AUTOMATION],
'displayName': 'Home Assistant',
'description': "Home Assistant at " + hass.config.api.base_url,
'singleInstance': True,
'webhookSmartApp': {
'targetUrl': webhook.async_generate_url(
hass, hass.data[DOMAIN][CONF_WEBHOOK_ID]),
'publicKey': ''}
})
app.refresh = Mock()
app.refresh.return_value = mock_coro()
app.save = Mock()
app.save.return_value = mock_coro()
settings = AppSettings(app.app_id)
settings.settings[SETTINGS_INSTANCE_ID] = config_file[CONF_INSTANCE_ID]
app.settings = Mock()
app.settings.return_value = mock_coro(return_value=settings)
return app
@pytest.fixture(name='app_settings')
def app_settings_fixture(app, config_file):
"""Fixture for an app settings."""
settings = AppSettings(app.app_id)
settings.settings[SETTINGS_INSTANCE_ID] = config_file[CONF_INSTANCE_ID]
return settings
def _create_installed_app(location_id, app_id):
item = InstalledApp()
item.apply_data(defaultdict(str, {
'installedAppId': str(uuid4()),
'installedAppStatus': 'AUTHORIZED',
'installedAppType': 'UNKNOWN',
'appId': app_id,
'locationId': location_id
}))
return item
@pytest.fixture(name='installed_app')
def installed_app_fixture(location, app):
"""Fixture for a single installed app."""
return _create_installed_app(location.location_id, app.app_id)
@pytest.fixture(name='installed_apps')
def installed_apps_fixture(installed_app, locations, app):
"""Fixture for 2 installed apps."""
return [installed_app,
_create_installed_app(locations[1].location_id, app.app_id)]
@pytest.fixture(name='config_file')
def config_file_fixture():
"""Fixture representing the local config file contents."""
return {
CONF_INSTANCE_ID: str(uuid4()),
CONF_WEBHOOK_ID: webhook.generate_secret()
}
@pytest.fixture(name='smartthings_mock')
def smartthings_mock_fixture(locations):
"""Fixture to mock smartthings API calls."""
def _location(location_id):
return mock_coro(
return_value=next(location for location in locations
if location.location_id == location_id))
with patch("pysmartthings.SmartThings", autospec=True) as mock:
mock.return_value.location.side_effect = _location
yield mock
@pytest.fixture(name='device')
def device_fixture(location):
"""Fixture representing devices loaded."""
item = DeviceEntity(None)
item.status.refresh = Mock()
item.status.refresh.return_value = mock_coro()
item.apply_data({
"deviceId": "743de49f-036f-4e9c-839a-2f89d57607db",
"name": "GE In-Wall Smart Dimmer",
"label": "Front Porch Lights",
"deviceManufacturerCode": "0063-4944-3038",
"locationId": location.location_id,
"deviceTypeId": "8a9d4b1e3b9b1fe3013b9b206a7f000d",
"deviceTypeName": "Dimmer Switch",
"deviceNetworkType": "ZWAVE",
"components": [
{
"id": "main",
"capabilities": [
{
"id": "switch",
"version": 1
},
{
"id": "switchLevel",
"version": 1
},
{
"id": "refresh",
"version": 1
},
{
"id": "indicator",
"version": 1
},
{
"id": "sensor",
"version": 1
},
{
"id": "actuator",
"version": 1
},
{
"id": "healthCheck",
"version": 1
},
{
"id": "light",
"version": 1
}
]
}
],
"dth": {
"deviceTypeId": "8a9d4b1e3b9b1fe3013b9b206a7f000d",
"deviceTypeName": "Dimmer Switch",
"deviceNetworkType": "ZWAVE",
"completedSetup": False
},
"type": "DTH"
})
return item
@pytest.fixture(name='config_entry')
def config_entry_fixture(hass, installed_app, location):
"""Fixture representing a config entry."""
data = {
CONF_ACCESS_TOKEN: str(uuid4()),
CONF_INSTALLED_APP_ID: installed_app.installed_app_id,
CONF_APP_ID: installed_app.app_id,
CONF_LOCATION_ID: location.location_id
}
return ConfigEntry("1", DOMAIN, location.name, data, SOURCE_USER,
CONN_CLASS_CLOUD_PUSH)
@pytest.fixture(name="device_factory")
def device_factory_fixture():
"""Fixture for creating mock devices."""
api = Mock(spec=Api)
api.post_device_command.return_value = mock_coro(return_value={})
def _factory(label, capabilities, status: dict = None):
device_data = {
"deviceId": str(uuid4()),
"name": "Device Type Handler Name",
"label": label,
"deviceManufacturerCode": "9135fc86-0929-4436-bf73-5d75f523d9db",
"locationId": "fcd829e9-82f4-45b9-acfd-62fda029af80",
"components": [
{
"id": "main",
"capabilities": [
{"id": capability, "version": 1}
for capability in capabilities
]
}
],
"dth": {
"deviceTypeId": "b678b29d-2726-4e4f-9c3f-7aa05bd08964",
"deviceTypeName": "Switch",
"deviceNetworkType": "ZWAVE"
},
"type": "DTH"
}
device = DeviceEntity(api, data=device_data)
if status:
for attribute, value in status.items():
device.status.apply_attribute_update(
'main', '', attribute, value)
return device
return _factory
@pytest.fixture(name="event_factory")
def event_factory_fixture():
"""Fixture for creating mock devices."""
def _factory(device_id, event_type="DEVICE_EVENT"):
event = Mock()
event.event_type = event_type
event.device_id = device_id
event.component_id = 'main'
event.capability = ''
event.attribute = 'Updated'
event.value = 'Value'
return event
return _factory
@pytest.fixture(name="event_request_factory")
def event_request_factory_fixture(event_factory):
"""Fixture for creating mock smartapp event requests."""
def _factory(device_ids):
request = Mock()
request.installed_app_id = uuid4()
request.events = [event_factory(id) for id in device_ids]
request.events.append(event_factory(uuid4()))
request.events.append(event_factory(device_ids[0], event_type="OTHER"))
return request
return _factory
@@ -0,0 +1,245 @@
"""Tests for the SmartThings config flow module."""
from unittest.mock import patch
from uuid import uuid4
from aiohttp.client_exceptions import ClientResponseError
from homeassistant import data_entry_flow
from homeassistant.components.smartthings.config_flow import (
SmartThingsFlowHandler)
from homeassistant.config_entries import ConfigEntry
from tests.common import mock_coro
async def test_step_user(hass):
"""Test the access token form is shown for a user initiated flow."""
flow = SmartThingsFlowHandler()
flow.hass = hass
result = await flow.async_step_user()
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['step_id'] == 'user'
async def test_step_init(hass):
"""Test the access token form is shown for an init flow."""
flow = SmartThingsFlowHandler()
flow.hass = hass
result = await flow.async_step_import()
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['step_id'] == 'user'
async def test_base_url_not_https(hass):
"""Test the base_url parameter starts with https://."""
hass.config.api.base_url = 'http://0.0.0.0'
flow = SmartThingsFlowHandler()
flow.hass = hass
result = await flow.async_step_import()
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['step_id'] == 'user'
assert result['errors'] == {'base': 'base_url_not_https'}
async def test_invalid_token_format(hass):
"""Test an error is shown for invalid token formats."""
flow = SmartThingsFlowHandler()
flow.hass = hass
result = await flow.async_step_user({'access_token': '123456789'})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['step_id'] == 'user'
assert result['errors'] == {'access_token': 'token_invalid_format'}
async def test_token_already_setup(hass):
"""Test an error is shown when the token is already setup."""
flow = SmartThingsFlowHandler()
flow.hass = hass
token = str(uuid4())
entries = [ConfigEntry(
version='', domain='', title='', data={'access_token': token},
source='', connection_class='')]
with patch.object(hass.config_entries, 'async_entries',
return_value=entries):
result = await flow.async_step_user({'access_token': token})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['step_id'] == 'user'
assert result['errors'] == {'access_token': 'token_already_setup'}
async def test_token_unauthorized(hass, smartthings_mock):
"""Test an error is shown when the token is not authorized."""
flow = SmartThingsFlowHandler()
flow.hass = hass
smartthings_mock.return_value.apps.return_value = mock_coro(
exception=ClientResponseError(None, None, status=401))
result = await flow.async_step_user({'access_token': str(uuid4())})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['step_id'] == 'user'
assert result['errors'] == {'access_token': 'token_unauthorized'}
async def test_token_forbidden(hass, smartthings_mock):
"""Test an error is shown when the token is forbidden."""
flow = SmartThingsFlowHandler()
flow.hass = hass
smartthings_mock.return_value.apps.return_value = mock_coro(
exception=ClientResponseError(None, None, status=403))
result = await flow.async_step_user({'access_token': str(uuid4())})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['step_id'] == 'user'
assert result['errors'] == {'access_token': 'token_forbidden'}
async def test_unknown_api_error(hass, smartthings_mock):
"""Test an error is shown when there is an unknown API error."""
flow = SmartThingsFlowHandler()
flow.hass = hass
smartthings_mock.return_value.apps.return_value = mock_coro(
exception=ClientResponseError(None, None, status=500))
result = await flow.async_step_user({'access_token': str(uuid4())})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['step_id'] == 'user'
assert result['errors'] == {'base': 'app_setup_error'}
async def test_unknown_error(hass, smartthings_mock):
"""Test an error is shown when there is an unknown API error."""
flow = SmartThingsFlowHandler()
flow.hass = hass
smartthings_mock.return_value.apps.return_value = mock_coro(
exception=Exception('Unknown error'))
result = await flow.async_step_user({'access_token': str(uuid4())})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['step_id'] == 'user'
assert result['errors'] == {'base': 'app_setup_error'}
async def test_app_created_then_show_wait_form(hass, app, smartthings_mock):
"""Test SmartApp is created when one does not exist and shows wait form."""
flow = SmartThingsFlowHandler()
flow.hass = hass
smartthings = smartthings_mock.return_value
smartthings.apps.return_value = mock_coro(return_value=[])
smartthings.create_app.return_value = mock_coro(return_value=(app, None))
smartthings.update_app_settings.return_value = mock_coro()
smartthings.update_app_oauth.return_value = mock_coro()
result = await flow.async_step_user({'access_token': str(uuid4())})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['step_id'] == 'wait_install'
async def test_app_updated_then_show_wait_form(
hass, app, smartthings_mock):
"""Test SmartApp is updated when an existing is already created."""
flow = SmartThingsFlowHandler()
flow.hass = hass
api = smartthings_mock.return_value
api.apps.return_value = mock_coro(return_value=[app])
result = await flow.async_step_user({'access_token': str(uuid4())})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['step_id'] == 'wait_install'
async def test_wait_form_displayed(hass):
"""Test the wait for installation form is displayed."""
flow = SmartThingsFlowHandler()
flow.hass = hass
result = await flow.async_step_wait_install(None)
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['step_id'] == 'wait_install'
async def test_wait_form_displayed_after_checking(hass, smartthings_mock):
"""Test error is shown when the user has not installed the app."""
flow = SmartThingsFlowHandler()
flow.hass = hass
flow.access_token = str(uuid4())
flow.api = smartthings_mock.return_value
flow.api.installed_apps.return_value = mock_coro(return_value=[])
result = await flow.async_step_wait_install({})
assert result['type'] == data_entry_flow.RESULT_TYPE_FORM
assert result['step_id'] == 'wait_install'
assert result['errors'] == {'base': 'app_not_installed'}
async def test_config_entry_created_when_installed(
hass, location, installed_app, smartthings_mock):
"""Test a config entry is created once the app is installed."""
flow = SmartThingsFlowHandler()
flow.hass = hass
flow.access_token = str(uuid4())
flow.api = smartthings_mock.return_value
flow.app_id = installed_app.app_id
flow.api.installed_apps.return_value = \
mock_coro(return_value=[installed_app])
result = await flow.async_step_wait_install({})
assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result['data']['app_id'] == installed_app.app_id
assert result['data']['installed_app_id'] == \
installed_app.installed_app_id
assert result['data']['location_id'] == installed_app.location_id
assert result['data']['access_token'] == flow.access_token
assert result['title'] == location.name
async def test_multiple_config_entry_created_when_installed(
hass, app, locations, installed_apps, smartthings_mock):
"""Test a config entries are created for multiple installs."""
flow = SmartThingsFlowHandler()
flow.hass = hass
flow.access_token = str(uuid4())
flow.app_id = app.app_id
flow.api = smartthings_mock.return_value
flow.api.installed_apps.return_value = \
mock_coro(return_value=installed_apps)
result = await flow.async_step_wait_install({})
assert result['type'] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result['data']['app_id'] == installed_apps[0].app_id
assert result['data']['installed_app_id'] == \
installed_apps[0].installed_app_id
assert result['data']['location_id'] == installed_apps[0].location_id
assert result['data']['access_token'] == flow.access_token
assert result['title'] == locations[0].name
await hass.async_block_till_done()
entries = hass.config_entries.async_entries('smartthings')
assert len(entries) == 1
assert entries[0].data['app_id'] == installed_apps[1].app_id
assert entries[0].data['installed_app_id'] == \
installed_apps[1].installed_app_id
assert entries[0].data['location_id'] == installed_apps[1].location_id
assert entries[0].data['access_token'] == flow.access_token
assert entries[0].title == locations[1].name
+183
View File
@@ -0,0 +1,183 @@
"""Tests for the SmartThings component init module."""
from unittest.mock import Mock, patch
from uuid import uuid4
from aiohttp import ClientConnectionError, ClientResponseError
from pysmartthings import InstalledAppStatus
import pytest
from homeassistant.components import smartthings
from homeassistant.components.smartthings.const import (
DATA_BROKERS, DOMAIN, SIGNAL_SMARTTHINGS_UPDATE, SUPPORTED_PLATFORMS)
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from tests.common import mock_coro
async def test_unrecoverable_api_errors_create_new_flow(
hass, config_entry, smartthings_mock):
"""
Test a new config flow is initiated when there are API errors.
401 (unauthorized): Occurs when the access token is no longer valid.
403 (forbidden/not found): Occurs when the app or installed app could
not be retrieved/found (likely deleted?)
"""
api = smartthings_mock.return_value
for error_status in (401, 403):
setattr(hass.config_entries, '_entries', [config_entry])
api.app.return_value = mock_coro(
exception=ClientResponseError(None, None,
status=error_status))
# Assert setup returns false
result = await smartthings.async_setup_entry(hass, config_entry)
assert not result
# Assert entry was removed and new flow created
await hass.async_block_till_done()
assert not hass.config_entries.async_entries(DOMAIN)
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
assert flows[0]['handler'] == 'smartthings'
assert flows[0]['context'] == {'source': 'import'}
hass.config_entries.flow.async_abort(flows[0]['flow_id'])
async def test_recoverable_api_errors_raise_not_ready(
hass, config_entry, smartthings_mock):
"""Test config entry not ready raised for recoverable API errors."""
setattr(hass.config_entries, '_entries', [config_entry])
api = smartthings_mock.return_value
api.app.return_value = mock_coro(
exception=ClientResponseError(None, None, status=500))
with pytest.raises(ConfigEntryNotReady):
await smartthings.async_setup_entry(hass, config_entry)
async def test_connection_errors_raise_not_ready(
hass, config_entry, smartthings_mock):
"""Test config entry not ready raised for connection errors."""
setattr(hass.config_entries, '_entries', [config_entry])
api = smartthings_mock.return_value
api.app.return_value = mock_coro(
exception=ClientConnectionError())
with pytest.raises(ConfigEntryNotReady):
await smartthings.async_setup_entry(hass, config_entry)
async def test_base_url_no_longer_https_does_not_load(
hass, config_entry, app, smartthings_mock):
"""Test base_url no longer valid creates a new flow."""
hass.config.api.base_url = 'http://0.0.0.0'
setattr(hass.config_entries, '_entries', [config_entry])
api = smartthings_mock.return_value
api.app.return_value = mock_coro(return_value=app)
# Assert setup returns false
result = await smartthings.async_setup_entry(hass, config_entry)
assert not result
async def test_unauthorized_installed_app_raises_not_ready(
hass, config_entry, app, installed_app,
smartthings_mock):
"""Test config entry not ready raised when the app isn't authorized."""
setattr(hass.config_entries, '_entries', [config_entry])
setattr(installed_app, '_installed_app_status',
InstalledAppStatus.PENDING)
api = smartthings_mock.return_value
api.app.return_value = mock_coro(return_value=app)
api.installed_app.return_value = mock_coro(return_value=installed_app)
with pytest.raises(ConfigEntryNotReady):
await smartthings.async_setup_entry(hass, config_entry)
async def test_config_entry_loads_platforms(
hass, config_entry, app, installed_app,
device, smartthings_mock):
"""Test config entry loads properly and proxies to platforms."""
setattr(hass.config_entries, '_entries', [config_entry])
api = smartthings_mock.return_value
api.app.return_value = mock_coro(return_value=app)
api.installed_app.return_value = mock_coro(return_value=installed_app)
api.devices.return_value = mock_coro(return_value=[device])
with patch.object(hass.config_entries, 'async_forward_entry_setup',
return_value=mock_coro()) as forward_mock:
assert await smartthings.async_setup_entry(hass, config_entry)
# Assert platforms loaded
await hass.async_block_till_done()
assert forward_mock.call_count == len(SUPPORTED_PLATFORMS)
async def test_unload_entry(hass, config_entry):
"""Test entries are unloaded correctly."""
broker = Mock()
broker.event_handler_disconnect = Mock()
hass.data[DOMAIN][DATA_BROKERS][config_entry.entry_id] = broker
with patch.object(hass.config_entries, 'async_forward_entry_unload',
return_value=mock_coro(
return_value=True
)) as forward_mock:
assert await smartthings.async_unload_entry(hass, config_entry)
assert broker.event_handler_disconnect.call_count == 1
assert config_entry.entry_id not in hass.data[DOMAIN][DATA_BROKERS]
# Assert platforms unloaded
await hass.async_block_till_done()
assert forward_mock.call_count == len(SUPPORTED_PLATFORMS)
async def test_event_handler_dispatches_updated_devices(
hass, device_factory, event_request_factory):
"""Test the event handler dispatches updated devices."""
devices = [
device_factory('Bedroom 1 Switch', ['switch']),
device_factory('Bathroom 1', ['switch']),
device_factory('Sensor', ['motionSensor']),
]
device_ids = [devices[0].device_id, devices[1].device_id,
devices[2].device_id]
request = event_request_factory(device_ids)
called = False
def signal(ids):
nonlocal called
called = True
assert device_ids == ids
async_dispatcher_connect(hass, SIGNAL_SMARTTHINGS_UPDATE, signal)
broker = smartthings.DeviceBroker(
hass, devices, request.installed_app_id)
await broker.event_handler(request, None, None)
await hass.async_block_till_done()
assert called
for device in devices:
assert device.status.attributes['Updated'] == 'Value'
async def test_event_handler_ignores_other_installed_app(
hass, device_factory, event_request_factory):
"""Test the event handler dispatches updated devices."""
device = device_factory('Bedroom 1 Switch', ['switch'])
request = event_request_factory([device.device_id])
called = False
def signal(ids):
nonlocal called
called = True
async_dispatcher_connect(hass, SIGNAL_SMARTTHINGS_UPDATE, signal)
broker = smartthings.DeviceBroker(hass, [device], str(uuid4()))
await broker.event_handler(request, None, None)
await hass.async_block_till_done()
assert not called
@@ -0,0 +1,112 @@
"""Tests for the smartapp module."""
from unittest.mock import Mock, patch
from uuid import uuid4
from pysmartthings import AppEntity
from homeassistant.components.smartthings import smartapp
from homeassistant.components.smartthings.const import (
DATA_MANAGER, DOMAIN, SUPPORTED_CAPABILITIES)
from tests.common import mock_coro
async def test_update_app(hass, app):
"""Test update_app does not save if app is current."""
await smartapp.update_app(hass, app)
assert app.save.call_count == 0
async def test_update_app_updated_needed(hass, app):
"""Test update_app updates when an app is needed."""
mock_app = Mock(spec=AppEntity)
mock_app.app_name = 'Test'
mock_app.refresh.return_value = mock_coro()
mock_app.save.return_value = mock_coro()
await smartapp.update_app(hass, mock_app)
assert mock_app.save.call_count == 1
assert mock_app.app_name == 'Test'
assert mock_app.display_name == app.display_name
assert mock_app.description == app.description
assert mock_app.webhook_target_url == app.webhook_target_url
assert mock_app.app_type == app.app_type
assert mock_app.single_instance == app.single_instance
assert mock_app.classifications == app.classifications
async def test_smartapp_install_abort_if_no_other(hass, smartthings_mock):
"""Test aborts if no other app was configured already."""
api = smartthings_mock.return_value
api.create_subscription.return_value = mock_coro()
app = Mock()
app.app_id = uuid4()
request = Mock()
request.installed_app_id = uuid4()
request.auth_token = uuid4()
request.location_id = uuid4()
await smartapp.smartapp_install(hass, request, None, app)
entries = hass.config_entries.async_entries('smartthings')
assert not entries
assert api.create_subscription.call_count == \
len(SUPPORTED_CAPABILITIES)
async def test_smartapp_install_creates_flow(
hass, smartthings_mock, config_entry, location):
"""Test installation creates flow."""
# Arrange
setattr(hass.config_entries, '_entries', [config_entry])
api = smartthings_mock.return_value
api.create_subscription.return_value = mock_coro()
app = Mock()
app.app_id = config_entry.data['app_id']
request = Mock()
request.installed_app_id = str(uuid4())
request.auth_token = str(uuid4())
request.location_id = location.location_id
# Act
await smartapp.smartapp_install(hass, request, None, app)
# Assert
await hass.async_block_till_done()
entries = hass.config_entries.async_entries('smartthings')
assert len(entries) == 2
assert api.create_subscription.call_count == \
len(SUPPORTED_CAPABILITIES)
assert entries[1].data['app_id'] == app.app_id
assert entries[1].data['installed_app_id'] == request.installed_app_id
assert entries[1].data['location_id'] == request.location_id
assert entries[1].data['access_token'] == \
config_entry.data['access_token']
assert entries[1].title == location.name
async def test_smartapp_uninstall(hass, config_entry):
"""Test the config entry is unloaded when the app is uninstalled."""
setattr(hass.config_entries, '_entries', [config_entry])
app = Mock()
app.app_id = config_entry.data['app_id']
request = Mock()
request.installed_app_id = config_entry.data['installed_app_id']
with patch.object(hass.config_entries, 'async_remove',
return_value=mock_coro()) as remove:
await smartapp.smartapp_uninstall(hass, request, None, app)
assert remove.call_count == 1
async def test_smartapp_webhook(hass):
"""Test the smartapp webhook calls the manager."""
manager = Mock()
manager.handle_request = Mock()
manager.handle_request.return_value = mock_coro(return_value={})
hass.data[DOMAIN][DATA_MANAGER] = manager
request = Mock()
request.headers = []
request.json.return_value = mock_coro(return_value={})
result = await smartapp.smartapp_webhook(hass, '', request)
assert result.body == b'{}'
+135
View File
@@ -0,0 +1,135 @@
"""
Test for the SmartThings switch platform.
The only mocking required is of the underlying SmartThings API object so
real HTTP calls are not initiated during testing.
"""
from pysmartthings import Attribute, Capability
from homeassistant.components.smartthings import DeviceBroker, switch
from homeassistant.components.smartthings.const import (
DATA_BROKERS, DOMAIN, SIGNAL_SMARTTHINGS_UPDATE)
from homeassistant.config_entries import (
CONN_CLASS_CLOUD_PUSH, SOURCE_USER, ConfigEntry)
from homeassistant.helpers.dispatcher import async_dispatcher_send
async def _setup_platform(hass, *devices):
"""Set up the SmartThings switch platform and prerequisites."""
hass.config.components.add(DOMAIN)
broker = DeviceBroker(hass, devices, '')
config_entry = ConfigEntry("1", DOMAIN, "Test", {},
SOURCE_USER, CONN_CLASS_CLOUD_PUSH)
hass.data[DOMAIN] = {
DATA_BROKERS: {
config_entry.entry_id: broker
}
}
await hass.config_entries.async_forward_entry_setup(config_entry, 'switch')
await hass.async_block_till_done()
return config_entry
async def test_async_setup_platform():
"""Test setup platform does nothing (it uses config entries)."""
await switch.async_setup_platform(None, None, None)
def test_is_switch(device_factory):
"""Test switches are correctly identified."""
switch_device = device_factory('Switch', [Capability.switch])
non_switch_devices = [
device_factory('Light', [Capability.switch, Capability.switch_level]),
device_factory('Fan', [Capability.switch, Capability.fan_speed]),
device_factory('Color Light', [Capability.switch,
Capability.color_control]),
device_factory('Temp Light', [Capability.switch,
Capability.color_temperature]),
device_factory('Unknown', ['Unknown']),
]
assert switch.is_switch(switch_device)
for non_switch_device in non_switch_devices:
assert not switch.is_switch(non_switch_device)
async def test_entity_and_device_attributes(hass, device_factory):
"""Test the attributes of the entity are correct."""
# Arrange
device = device_factory('Switch_1', [Capability.switch],
{Attribute.switch: 'on'})
entity_registry = await hass.helpers.entity_registry.async_get_registry()
device_registry = await hass.helpers.device_registry.async_get_registry()
# Act
await _setup_platform(hass, device)
# Assert
entity = entity_registry.async_get('switch.switch_1')
assert entity
assert entity.unique_id == device.device_id
device_entry = device_registry.async_get_device(
{(DOMAIN, device.device_id)}, [])
assert device_entry
assert device_entry.name == device.label
assert device_entry.model == device.device_type_name
assert device_entry.manufacturer == 'Unavailable'
async def test_turn_off(hass, device_factory):
"""Test the switch turns of successfully."""
# Arrange
device = device_factory('Switch_1', [Capability.switch],
{Attribute.switch: 'on'})
await _setup_platform(hass, device)
# Act
await hass.services.async_call(
'switch', 'turn_off', {'entity_id': 'switch.switch_1'},
blocking=True)
# Assert
state = hass.states.get('switch.switch_1')
assert state is not None
assert state.state == 'off'
async def test_turn_on(hass, device_factory):
"""Test the switch turns of successfully."""
# Arrange
device = device_factory('Switch_1', [Capability.switch],
{Attribute.switch: 'off'})
await _setup_platform(hass, device)
# Act
await hass.services.async_call(
'switch', 'turn_on', {'entity_id': 'switch.switch_1'},
blocking=True)
# Assert
state = hass.states.get('switch.switch_1')
assert state is not None
assert state.state == 'on'
async def test_update_from_signal(hass, device_factory):
"""Test the switch updates when receiving a signal."""
# Arrange
device = device_factory('Switch_1', [Capability.switch],
{Attribute.switch: 'off'})
await _setup_platform(hass, device)
await device.switch_on(True)
# Act
async_dispatcher_send(hass, SIGNAL_SMARTTHINGS_UPDATE,
[device.device_id])
# Assert
await hass.async_block_till_done()
state = hass.states.get('switch.switch_1')
assert state is not None
assert state.state == 'on'
async def test_unload_config_entry(hass, device_factory):
"""Test the switch is removed when the config entry is unloaded."""
# Arrange
device = device_factory('Switch', [Capability.switch],
{Attribute.switch: 'on'})
config_entry = await _setup_platform(hass, device)
# Act
await hass.config_entries.async_forward_entry_unload(
config_entry, 'switch')
# Assert
assert not hass.states.get('switch.switch_1')