Add sharkiq integration for Shark IQ robot vacuums (#38272)

Co-authored-by: Paulus Schoutsen <paulus@home-assistant.io>
This commit is contained in:
Andrew MarksandPaulus Schoutsen authored and GitHub committed 2020-08-30 15:26:11 +02:00
1 parent ab7b42c022
commit 3d1ff5b8d0
17 files changed
+1183

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""Tests for the Shark IQ integration."""
+73
View File
@@ -0,0 +1,73 @@
"""Constants used in shark iq tests."""
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
# Dummy device dict of the form returned by AylaApi.list_devices()
SHARK_DEVICE_DICT = {
"product_name": "Sharknado",
"model": "AY001MRT1",
"dsn": "AC000Wxxxxxxxxx",
"oem_model": "RV1000A",
"sw_version": "devd 1.7 2020-05-13 11:50:36",
"template_id": 99999,
"mac": "ffffffffffff",
"unique_hardware_id": None,
"lan_ip": "192.168.0.123",
"connected_at": "2020-07-31T08:03:05Z",
"key": 26517570,
"lan_enabled": False,
"has_properties": True,
"product_class": None,
"connection_status": "Online",
"lat": "99.9999",
"lng": "-99.9999",
"locality": "99999",
"device_type": "Wifi",
}
# Dummy response for get_metadata
SHARK_METADATA_DICT = [
{
"datum": {
"created_at": "2019-12-02T02:13:12Z",
"from_template": False,
"key": "sharkDeviceMobileData",
"updated_at": "2019-12-02T02:13:12Z",
"value": '{"vacModelNumber":"RV1001AE","vacSerialNumber":"S26xxxxxxxxx"}',
"dsn": "AC000Wxxxxxxxxx",
}
}
]
# Dummy shark.properties_full for testing. NB: this only includes those properties in the tests
SHARK_PROPERTIES_DICT = {
"Battery_Capacity": {"base_type": "integer", "read_only": True, "value": 50},
"Charging_Status": {"base_type": "boolean", "read_only": True, "value": 0},
"CleanComplete": {"base_type": "boolean", "read_only": True, "value": 0},
"Cleaning_Statistics": {"base_type": "file", "read_only": True, "value": None},
"DockedStatus": {"base_type": "boolean", "read_only": True, "value": 0},
"Error_Code": {"base_type": "integer", "read_only": True, "value": 7},
"Evacuating": {"base_type": "boolean", "read_only": True, "value": 1},
"Find_Device": {"base_type": "boolean", "read_only": False, "value": 0},
"LowLightMission": {"base_type": "boolean", "read_only": True, "value": 0},
"Nav_Module_FW_Version": {
"base_type": "string",
"read_only": True,
"value": "V3.4.11-20191015",
},
"Operating_Mode": {"base_type": "integer", "read_only": False, "value": 2},
"Power_Mode": {"base_type": "integer", "read_only": False, "value": 1},
"RSSI": {"base_type": "integer", "read_only": True, "value": -46},
"Recharge_Resume": {"base_type": "boolean", "read_only": False, "value": 1},
"Recharging_To_Resume": {"base_type": "boolean", "read_only": True, "value": 0},
"Robot_Firmware_Version": {
"base_type": "string",
"read_only": True,
"value": "Dummy Firmware 1.0",
},
}
TEST_USERNAME = "test-username"
TEST_PASSWORD = "test-password"
UNIQUE_ID = "foo@bar.com"
CONFIG = {CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD}
@@ -0,0 +1,138 @@
"""Test the Shark IQ config flow."""
import aiohttp
from sharkiqpy import SharkIqAuthError
from homeassistant import config_entries, setup
from homeassistant.components.sharkiq.const import DOMAIN
from .const import CONFIG, TEST_PASSWORD, TEST_USERNAME, UNIQUE_ID
from tests.async_mock import MagicMock, PropertyMock, patch
from tests.common import MockConfigEntry
def _create_mocked_ayla(connect=None):
"""Create a mocked AylaApi object."""
mocked_ayla = MagicMock()
type(mocked_ayla).sign_in = PropertyMock(side_effect=connect)
type(mocked_ayla).async_sign_in = PropertyMock(side_effect=connect)
return mocked_ayla
async def test_form(hass):
"""Test we get the form."""
await setup.async_setup_component(hass, "persistent_notification", {})
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == "form"
assert result["errors"] == {}
with patch("sharkiqpy.AylaApi.async_sign_in", return_value=True), patch(
"homeassistant.components.sharkiq.async_setup", return_value=True
) as mock_setup, patch(
"homeassistant.components.sharkiq.async_setup_entry", return_value=True,
) as mock_setup_entry:
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], CONFIG,
)
await hass.async_block_till_done()
assert result2["type"] == "create_entry"
assert result2["title"] == f"{TEST_USERNAME:s}"
assert result2["data"] == {
"username": TEST_USERNAME,
"password": TEST_PASSWORD,
}
await hass.async_block_till_done()
assert len(mock_setup.mock_calls) == 1
assert len(mock_setup_entry.mock_calls) == 1
async def test_form_invalid_auth(hass):
"""Test we handle invalid auth."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
mocked_ayla = _create_mocked_ayla(connect=SharkIqAuthError)
with patch(
"homeassistant.components.sharkiq.config_flow.get_ayla_api",
return_value=mocked_ayla,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], CONFIG,
)
assert result2["type"] == "form"
assert result2["errors"] == {"base": "invalid_auth"}
async def test_form_cannot_connect(hass):
"""Test we handle cannot connect error."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
mocked_ayla = _create_mocked_ayla(connect=aiohttp.ClientError)
with patch(
"homeassistant.components.sharkiq.config_flow.get_ayla_api",
return_value=mocked_ayla,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], CONFIG,
)
assert result2["type"] == "form"
assert result2["errors"] == {"base": "cannot_connect"}
async def test_form_other_error(hass):
"""Test we handle other errors."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
mocked_ayla = _create_mocked_ayla(connect=TypeError)
with patch(
"homeassistant.components.sharkiq.config_flow.get_ayla_api",
return_value=mocked_ayla,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], CONFIG
)
assert result2["type"] == "form"
assert result2["errors"] == {"base": "unknown"}
async def test_reauth(hass):
"""Test reauth flow."""
with patch(
"homeassistant.components.sharkiq.vacuum.async_setup_entry", return_value=True,
), patch("sharkiqpy.AylaApi.async_sign_in", return_value=True):
mock_config = MockConfigEntry(domain=DOMAIN, unique_id=UNIQUE_ID, data=CONFIG)
mock_config.add_to_hass(hass)
hass.config_entries.async_update_entry(mock_config, data=CONFIG)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG
)
assert result["type"] == "abort"
assert result["reason"] == "reauth_successful"
with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=SharkIqAuthError):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG,
)
assert result["type"] == "form"
assert result["errors"] == {"base": "invalid_auth"}
with patch("sharkiqpy.AylaApi.async_sign_in", side_effect=RuntimeError):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "reauth", "unique_id": UNIQUE_ID}, data=CONFIG,
)
assert result["type"] == "abort"
assert result["reason"] == "unknown"
+283
View File
@@ -0,0 +1,283 @@
"""Test the Shark IQ vacuum entity."""
from copy import deepcopy
import enum
from typing import Dict, List
from sharkiqpy import AylaApi, Properties, SharkIqAuthError, SharkIqVacuum, get_ayla_api
from homeassistant.components.sharkiq import SharkIqUpdateCoordinator
from homeassistant.components.sharkiq.vacuum import (
ATTR_ERROR_CODE,
ATTR_ERROR_MSG,
ATTR_LOW_LIGHT,
ATTR_RECHARGE_RESUME,
STATE_RECHARGING_TO_RESUME,
SharkVacuumEntity,
)
from homeassistant.components.vacuum import (
STATE_CLEANING,
STATE_DOCKED,
STATE_IDLE,
STATE_PAUSED,
STATE_RETURNING,
SUPPORT_BATTERY,
SUPPORT_FAN_SPEED,
SUPPORT_LOCATE,
SUPPORT_PAUSE,
SUPPORT_RETURN_HOME,
SUPPORT_START,
SUPPORT_STATE,
SUPPORT_STATUS,
SUPPORT_STOP,
)
from homeassistant.config_entries import ConfigEntriesFlowManager, ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import UpdateFailed
from .const import (
SHARK_DEVICE_DICT,
SHARK_METADATA_DICT,
SHARK_PROPERTIES_DICT,
TEST_PASSWORD,
TEST_USERNAME,
)
from tests.async_mock import MagicMock, patch
try:
import ujson as json
except ImportError:
import json
MockAyla = MagicMock(spec=AylaApi) # pylint: disable=invalid-name
def _set_property(self, property_name, value):
"""Set a property locally without hitting the API."""
if isinstance(property_name, enum.Enum):
property_name = property_name.value
if isinstance(value, enum.Enum):
value = value.value
self.properties_full[property_name]["value"] = value
async def _async_set_property(self, property_name, value):
"""Set a property locally without hitting the API."""
_set_property(self, property_name, value)
def _get_mock_shark_vac(ayla_api: AylaApi) -> SharkIqVacuum:
"""Create a crude sharkiq vacuum with mocked properties."""
shark = SharkIqVacuum(ayla_api, SHARK_DEVICE_DICT)
shark.properties_full = deepcopy(SHARK_PROPERTIES_DICT)
return shark
async def _async_list_devices(_) -> List[Dict]:
"""Generate a dummy of async_list_devices output."""
return [SHARK_DEVICE_DICT]
@patch.object(SharkIqVacuum, "set_property_value", new=_set_property)
@patch.object(SharkIqVacuum, "async_set_property_value", new=_async_set_property)
async def test_shark_operation_modes(hass: HomeAssistant) -> None:
"""Test all of the shark vacuum operation modes."""
ayla_api = MockAyla()
shark_vac = _get_mock_shark_vac(ayla_api)
coordinator = SharkIqUpdateCoordinator(hass, None, ayla_api, [shark_vac])
shark = SharkVacuumEntity(shark_vac, coordinator)
# These come from the setup
assert isinstance(shark.is_docked, bool) and not shark.is_docked
assert (
isinstance(shark.recharging_to_resume, bool) and not shark.recharging_to_resume
)
# Go through the operation modes while it's "off the dock"
await shark.async_start()
assert shark.operating_mode == shark.state == STATE_CLEANING
await shark.async_pause()
assert shark.operating_mode == shark.state == STATE_PAUSED
await shark.async_stop()
assert shark.operating_mode == shark.state == STATE_IDLE
await shark.async_return_to_base()
assert shark.operating_mode == shark.state == STATE_RETURNING
# Test the docked modes
await shark.async_stop()
shark.sharkiq.set_property_value(Properties.RECHARGING_TO_RESUME, 1)
shark.sharkiq.set_property_value(Properties.DOCKED_STATUS, 1)
assert isinstance(shark.is_docked, bool) and shark.is_docked
assert isinstance(shark.recharging_to_resume, bool) and shark.recharging_to_resume
assert shark.state == STATE_RECHARGING_TO_RESUME
shark.sharkiq.set_property_value(Properties.RECHARGING_TO_RESUME, 0)
assert shark.state == STATE_DOCKED
await shark.async_set_fan_speed("Eco")
assert shark.fan_speed == "Eco"
await shark.async_set_fan_speed("Max")
assert shark.fan_speed == "Max"
await shark.async_set_fan_speed("Normal")
assert shark.fan_speed == "Normal"
assert set(shark.fan_speed_list) == {"Normal", "Max", "Eco"}
@patch.object(SharkIqVacuum, "set_property_value", new=_set_property)
async def test_shark_vac_properties(hass: HomeAssistant) -> None:
"""Test all of the shark vacuum property accessors."""
ayla_api = MockAyla()
shark_vac = _get_mock_shark_vac(ayla_api)
coordinator = SharkIqUpdateCoordinator(hass, None, ayla_api, [shark_vac])
shark = SharkVacuumEntity(shark_vac, coordinator)
assert shark.name == "Sharknado"
assert shark.serial_number == "AC000Wxxxxxxxxx"
assert shark.model == "RV1000A"
assert shark.battery_level == 50
assert shark.fan_speed == "Eco"
shark.sharkiq.set_property_value(Properties.POWER_MODE, 0)
assert shark.fan_speed == "Normal"
assert isinstance(shark.recharge_resume, bool) and shark.recharge_resume
assert isinstance(shark.low_light, bool) and not shark.low_light
target_state_attributes = {
ATTR_ERROR_CODE: 7,
ATTR_ERROR_MSG: "Cliff sensor is blocked",
ATTR_RECHARGE_RESUME: True,
ATTR_LOW_LIGHT: False,
}
state_json = json.dumps(shark.device_state_attributes, sort_keys=True)
target_json = json.dumps(target_state_attributes, sort_keys=True)
assert state_json == target_json
assert not shark.should_poll
@patch.object(SharkIqVacuum, "set_property_value", new=_set_property)
@patch.object(SharkIqVacuum, "async_set_property_value", new=_async_set_property)
async def test_shark_metadata(hass: HomeAssistant) -> None:
"""Test shark properties coming from metadata."""
ayla_api = MockAyla()
shark_vac = _get_mock_shark_vac(ayla_api)
coordinator = SharkIqUpdateCoordinator(hass, None, ayla_api, [shark_vac])
shark = SharkVacuumEntity(shark_vac, coordinator)
shark.sharkiq._update_metadata( # pylint: disable=protected-access
SHARK_METADATA_DICT
)
target_device_info = {
"identifiers": {("sharkiq", "AC000Wxxxxxxxxx")},
"name": "Sharknado",
"manufacturer": "Shark",
"model": "RV1001AE",
"sw_version": "Dummy Firmware 1.0",
}
state_json = json.dumps(shark.device_info, sort_keys=True)
target_json = json.dumps(target_device_info, sort_keys=True)
assert state_json == target_json
def _get_async_update(err=None):
async def _async_update(_) -> bool:
if err is not None:
raise err
return True
return _async_update
@patch.object(AylaApi, "async_list_devices", new=_async_list_devices)
async def test_updates(hass: HomeAssistant) -> None:
"""Test the update coordinator update functions."""
ayla_api = get_ayla_api(TEST_USERNAME, TEST_PASSWORD)
shark_vac = _get_mock_shark_vac(ayla_api)
mock_config = MagicMock(spec=ConfigEntry)
coordinator = SharkIqUpdateCoordinator(hass, mock_config, ayla_api, [shark_vac])
with patch.object(SharkIqVacuum, "async_update", new=_get_async_update()):
update_called = (
await coordinator._async_update_data() # pylint: disable=protected-access
)
assert update_called
update_failed = False
with patch.object(
SharkIqVacuum, "async_update", new=_get_async_update(SharkIqAuthError)
), patch.object(HomeAssistant, "async_create_task"), patch.object(
ConfigEntriesFlowManager, "async_init"
):
try:
await coordinator._async_update_data() # pylint: disable=protected-access
except UpdateFailed:
update_failed = True
assert update_failed
async def test_coordinator_match(hass: HomeAssistant):
"""Test that sharkiq-coordinator references work."""
ayla_api = get_ayla_api(TEST_PASSWORD, TEST_USERNAME)
shark_vac1 = _get_mock_shark_vac(ayla_api)
shark_vac2 = _get_mock_shark_vac(ayla_api)
shark_vac2._dsn = "FOOBAR!" # pylint: disable=protected-access
coordinator = SharkIqUpdateCoordinator(hass, None, ayla_api, [shark_vac1])
# The first should succeed, the second should fail
api1 = SharkVacuumEntity(shark_vac1, coordinator)
try:
_ = SharkVacuumEntity(shark_vac2, coordinator)
except RuntimeError:
api2_failed = True
else:
api2_failed = False
assert api2_failed
coordinator.last_update_success = True
coordinator._online_dsns = set() # pylint: disable=protected-access
assert not api1.is_online
assert not api1.available
coordinator._online_dsns = { # pylint: disable=protected-access
shark_vac1.serial_number
}
assert api1.is_online
assert api1.available
coordinator.last_update_success = False
assert not api1.available
async def test_simple_properties(hass: HomeAssistant):
"""Test that simple properties work as intended."""
ayla_api = get_ayla_api(TEST_PASSWORD, TEST_USERNAME)
shark_vac1 = _get_mock_shark_vac(ayla_api)
coordinator = SharkIqUpdateCoordinator(hass, None, ayla_api, [shark_vac1])
entity = SharkVacuumEntity(shark_vac1, coordinator)
assert entity.unique_id == "AC000Wxxxxxxxxx"
assert entity.supported_features == (
SUPPORT_BATTERY
| SUPPORT_FAN_SPEED
| SUPPORT_PAUSE
| SUPPORT_RETURN_HOME
| SUPPORT_START
| SUPPORT_STATE
| SUPPORT_STATUS
| SUPPORT_STOP
| SUPPORT_LOCATE
)
assert entity.error_code == 7
assert entity.error_message == "Cliff sensor is blocked"
shark_vac1.properties_full[Properties.ERROR_CODE.value]["value"] = 0
assert entity.error_code == 0
assert entity.error_message is None
assert (
coordinator.online_dsns
is coordinator._online_dsns # pylint: disable=protected-access
)