init home-assistant
This commit is contained in:
1
home-assistant/tests/components/smartthings/__init__.py
Normal file
1
home-assistant/tests/components/smartthings/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
"""Tests for the SmartThings component."""
|
||||
358
home-assistant/tests/components/smartthings/conftest.py
Normal file
358
home-assistant/tests/components/smartthings/conftest.py
Normal file
@@ -0,0 +1,358 @@
|
||||
"""Test configuration and mocks for the SmartThings component."""
|
||||
|
||||
import secrets
|
||||
from typing import Any
|
||||
from unittest.mock import Mock, patch
|
||||
from uuid import uuid4
|
||||
|
||||
from pysmartthings import (
|
||||
CLASSIFICATION_AUTOMATION,
|
||||
AppEntity,
|
||||
AppOAuthClient,
|
||||
AppSettings,
|
||||
DeviceEntity,
|
||||
DeviceStatus,
|
||||
InstalledApp,
|
||||
InstalledAppStatus,
|
||||
InstalledAppType,
|
||||
Location,
|
||||
SceneEntity,
|
||||
SmartThings,
|
||||
Subscription,
|
||||
)
|
||||
from pysmartthings.api import Api
|
||||
import pytest
|
||||
|
||||
from homeassistant.components import webhook
|
||||
from homeassistant.components.smartthings import DeviceBroker
|
||||
from homeassistant.components.smartthings.const import (
|
||||
APP_NAME_PREFIX,
|
||||
CONF_APP_ID,
|
||||
CONF_INSTALLED_APP_ID,
|
||||
CONF_INSTANCE_ID,
|
||||
CONF_LOCATION_ID,
|
||||
CONF_REFRESH_TOKEN,
|
||||
DATA_BROKERS,
|
||||
DOMAIN,
|
||||
SETTINGS_INSTANCE_ID,
|
||||
STORAGE_KEY,
|
||||
STORAGE_VERSION,
|
||||
)
|
||||
from homeassistant.config_entries import SOURCE_USER, ConfigEntryState
|
||||
from homeassistant.const import (
|
||||
CONF_ACCESS_TOKEN,
|
||||
CONF_CLIENT_ID,
|
||||
CONF_CLIENT_SECRET,
|
||||
CONF_WEBHOOK_ID,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.core_config import async_process_ha_core_config
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
from tests.components.light.conftest import mock_light_profiles # noqa: F401
|
||||
|
||||
COMPONENT_PREFIX = "homeassistant.components.smartthings."
|
||||
|
||||
|
||||
async def setup_platform(
|
||||
hass: HomeAssistant, platform: str, *, devices=None, scenes=None
|
||||
):
|
||||
"""Set up the SmartThings platform and prerequisites."""
|
||||
hass.config.components.add(DOMAIN)
|
||||
config_entry = MockConfigEntry(
|
||||
version=2,
|
||||
domain=DOMAIN,
|
||||
title="Test",
|
||||
data={CONF_INSTALLED_APP_ID: str(uuid4())},
|
||||
)
|
||||
config_entry.add_to_hass(hass)
|
||||
broker = DeviceBroker(
|
||||
hass, config_entry, Mock(), Mock(), devices or [], scenes or []
|
||||
)
|
||||
|
||||
hass.data[DOMAIN] = {DATA_BROKERS: {config_entry.entry_id: broker}}
|
||||
config_entry.mock_state(hass, ConfigEntryState.LOADED)
|
||||
await hass.config_entries.async_forward_entry_setups(config_entry, [platform])
|
||||
await hass.async_block_till_done()
|
||||
return config_entry
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
async def setup_component(
|
||||
hass: HomeAssistant, config_file: dict[str, str], hass_storage: dict[str, Any]
|
||||
) -> None:
|
||||
"""Load the SmartThing component."""
|
||||
hass_storage[STORAGE_KEY] = {"data": config_file, "version": STORAGE_VERSION}
|
||||
await async_process_ha_core_config(
|
||||
hass,
|
||||
{"external_url": "https://test.local"},
|
||||
)
|
||||
await async_setup_component(hass, "smartthings", {})
|
||||
|
||||
|
||||
def _create_location() -> Mock:
|
||||
loc = Mock(Location)
|
||||
loc.name = "Test Location"
|
||||
loc.location_id = str(uuid4())
|
||||
return loc
|
||||
|
||||
|
||||
@pytest.fixture(name="location")
|
||||
def location_fixture() -> Mock:
|
||||
"""Fixture for a single location."""
|
||||
return _create_location()
|
||||
|
||||
|
||||
@pytest.fixture(name="locations")
|
||||
def locations_fixture(location: Mock) -> list[Mock]:
|
||||
"""Fixture for 2 locations."""
|
||||
return [location, _create_location()]
|
||||
|
||||
|
||||
@pytest.fixture(name="app")
|
||||
async def app_fixture(hass: HomeAssistant, config_file: dict[str, str]) -> Mock:
|
||||
"""Fixture for a single app."""
|
||||
app = Mock(AppEntity)
|
||||
app.app_name = APP_NAME_PREFIX + str(uuid4())
|
||||
app.app_id = str(uuid4())
|
||||
app.app_type = "WEBHOOK_SMART_APP"
|
||||
app.classifications = [CLASSIFICATION_AUTOMATION]
|
||||
app.display_name = "Home Assistant"
|
||||
app.description = f"{hass.config.location_name} at https://test.local"
|
||||
app.single_instance = True
|
||||
app.webhook_target_url = webhook.async_generate_url(
|
||||
hass, hass.data[DOMAIN][CONF_WEBHOOK_ID]
|
||||
)
|
||||
|
||||
settings = Mock(AppSettings)
|
||||
settings.app_id = app.app_id
|
||||
settings.settings = {SETTINGS_INSTANCE_ID: config_file[CONF_INSTANCE_ID]}
|
||||
app.settings.return_value = settings
|
||||
return app
|
||||
|
||||
|
||||
@pytest.fixture(name="app_oauth_client")
|
||||
def app_oauth_client_fixture() -> Mock:
|
||||
"""Fixture for a single app's oauth."""
|
||||
client = Mock(AppOAuthClient)
|
||||
client.client_id = str(uuid4())
|
||||
client.client_secret = str(uuid4())
|
||||
return client
|
||||
|
||||
|
||||
@pytest.fixture(name="app_settings")
|
||||
def app_settings_fixture(app, config_file):
|
||||
"""Fixture for an app settings."""
|
||||
settings = Mock(AppSettings)
|
||||
settings.app_id = app.app_id
|
||||
settings.settings = {SETTINGS_INSTANCE_ID: config_file[CONF_INSTANCE_ID]}
|
||||
return settings
|
||||
|
||||
|
||||
def _create_installed_app(location_id: str, app_id: str) -> Mock:
|
||||
item = Mock(InstalledApp)
|
||||
item.installed_app_id = str(uuid4())
|
||||
item.installed_app_status = InstalledAppStatus.AUTHORIZED
|
||||
item.installed_app_type = InstalledAppType.WEBHOOK_SMART_APP
|
||||
item.app_id = app_id
|
||||
item.location_id = location_id
|
||||
return item
|
||||
|
||||
|
||||
@pytest.fixture(name="installed_app")
|
||||
def installed_app_fixture(location: Mock, app: Mock) -> Mock:
|
||||
"""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() -> dict[str, str]:
|
||||
"""Fixture representing the local config file contents."""
|
||||
return {CONF_INSTANCE_ID: str(uuid4()), CONF_WEBHOOK_ID: secrets.token_hex()}
|
||||
|
||||
|
||||
@pytest.fixture(name="smartthings_mock")
|
||||
def smartthings_mock_fixture(locations):
|
||||
"""Fixture to mock smartthings API calls."""
|
||||
|
||||
async def _location(location_id):
|
||||
return next(
|
||||
location for location in locations if location.location_id == location_id
|
||||
)
|
||||
|
||||
smartthings_mock = Mock(SmartThings)
|
||||
smartthings_mock.location.side_effect = _location
|
||||
mock = Mock(return_value=smartthings_mock)
|
||||
with (
|
||||
patch(COMPONENT_PREFIX + "SmartThings", new=mock),
|
||||
patch(COMPONENT_PREFIX + "config_flow.SmartThings", new=mock),
|
||||
patch(COMPONENT_PREFIX + "smartapp.SmartThings", new=mock),
|
||||
):
|
||||
yield smartthings_mock
|
||||
|
||||
|
||||
@pytest.fixture(name="device")
|
||||
def device_fixture(location):
|
||||
"""Fixture representing devices loaded."""
|
||||
item = Mock(DeviceEntity)
|
||||
item.device_id = "743de49f-036f-4e9c-839a-2f89d57607db"
|
||||
item.name = "GE In-Wall Smart Dimmer"
|
||||
item.label = "Front Porch Lights"
|
||||
item.location_id = location.location_id
|
||||
item.capabilities = [
|
||||
"switch",
|
||||
"switchLevel",
|
||||
"refresh",
|
||||
"indicator",
|
||||
"sensor",
|
||||
"actuator",
|
||||
"healthCheck",
|
||||
"light",
|
||||
]
|
||||
item.components = {"main": item.capabilities}
|
||||
item.status = Mock(DeviceStatus)
|
||||
return item
|
||||
|
||||
|
||||
@pytest.fixture(name="config_entry")
|
||||
def config_entry_fixture(installed_app: Mock, location: Mock) -> MockConfigEntry:
|
||||
"""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,
|
||||
CONF_REFRESH_TOKEN: str(uuid4()),
|
||||
CONF_CLIENT_ID: str(uuid4()),
|
||||
CONF_CLIENT_SECRET: str(uuid4()),
|
||||
}
|
||||
return MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data=data,
|
||||
title=location.name,
|
||||
version=2,
|
||||
source=SOURCE_USER,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(name="subscription_factory")
|
||||
def subscription_factory_fixture():
|
||||
"""Fixture for creating mock subscriptions."""
|
||||
|
||||
def _factory(capability):
|
||||
sub = Subscription()
|
||||
sub.capability = capability
|
||||
return sub
|
||||
|
||||
return _factory
|
||||
|
||||
|
||||
@pytest.fixture(name="device_factory")
|
||||
def device_factory_fixture():
|
||||
"""Fixture for creating mock devices."""
|
||||
api = Mock(Api)
|
||||
api.post_device_command.return_value = {"results": [{"status": "ACCEPTED"}]}
|
||||
|
||||
def _factory(label, capabilities, status: dict | None = 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="scene_factory")
|
||||
def scene_factory_fixture(location):
|
||||
"""Fixture for creating mock devices."""
|
||||
|
||||
def _factory(name):
|
||||
scene = Mock(SceneEntity)
|
||||
scene.scene_id = str(uuid4())
|
||||
scene.name = name
|
||||
scene.icon = None
|
||||
scene.color = None
|
||||
scene.location_id = location.location_id
|
||||
return scene
|
||||
|
||||
return _factory
|
||||
|
||||
|
||||
@pytest.fixture(name="scene")
|
||||
def scene_fixture(scene_factory):
|
||||
"""Fixture for an individual scene."""
|
||||
return scene_factory("Test Scene")
|
||||
|
||||
|
||||
@pytest.fixture(name="event_factory")
|
||||
def event_factory_fixture():
|
||||
"""Fixture for creating mock devices."""
|
||||
|
||||
def _factory(
|
||||
device_id,
|
||||
event_type="DEVICE_EVENT",
|
||||
capability="",
|
||||
attribute="Updated",
|
||||
value="Value",
|
||||
data=None,
|
||||
):
|
||||
event = Mock()
|
||||
event.event_type = event_type
|
||||
event.device_id = device_id
|
||||
event.component_id = "main"
|
||||
event.capability = capability
|
||||
event.attribute = attribute
|
||||
event.value = value
|
||||
event.data = data
|
||||
event.location_id = str(uuid4())
|
||||
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=None, events=None):
|
||||
request = Mock()
|
||||
request.installed_app_id = uuid4()
|
||||
if events is None:
|
||||
events = []
|
||||
if device_ids:
|
||||
events.extend([event_factory(device_id) for device_id in device_ids])
|
||||
events.append(event_factory(uuid4()))
|
||||
events.append(event_factory(device_ids[0], event_type="OTHER"))
|
||||
request.events = events
|
||||
return request
|
||||
|
||||
return _factory
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Test for the SmartThings binary_sensor platform.
|
||||
|
||||
The only mocking required is of the underlying SmartThings API object so
|
||||
real HTTP calls are not initiated during testing.
|
||||
"""
|
||||
|
||||
from pysmartthings import ATTRIBUTES, CAPABILITIES, Attribute, Capability
|
||||
|
||||
from homeassistant.components.binary_sensor import (
|
||||
DEVICE_CLASSES,
|
||||
DOMAIN as BINARY_SENSOR_DOMAIN,
|
||||
)
|
||||
from homeassistant.components.smartthings import binary_sensor
|
||||
from homeassistant.components.smartthings.const import DOMAIN, SIGNAL_SMARTTHINGS_UPDATE
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.const import ATTR_FRIENDLY_NAME, STATE_UNAVAILABLE, EntityCategory
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
||||
from homeassistant.helpers.dispatcher import async_dispatcher_send
|
||||
|
||||
from .conftest import setup_platform
|
||||
|
||||
|
||||
async def test_mapping_integrity() -> None:
|
||||
"""Test ensures the map dicts have proper integrity."""
|
||||
# Ensure every CAPABILITY_TO_ATTRIB key is in CAPABILITIES
|
||||
# Ensure every CAPABILITY_TO_ATTRIB value is in ATTRIB_TO_CLASS keys
|
||||
for capability, attrib in binary_sensor.CAPABILITY_TO_ATTRIB.items():
|
||||
assert capability in CAPABILITIES, capability
|
||||
assert attrib in ATTRIBUTES, attrib
|
||||
assert attrib in binary_sensor.ATTRIB_TO_CLASS, attrib
|
||||
# Ensure every ATTRIB_TO_CLASS value is in DEVICE_CLASSES
|
||||
for attrib, device_class in binary_sensor.ATTRIB_TO_CLASS.items():
|
||||
assert attrib in ATTRIBUTES, attrib
|
||||
assert device_class in DEVICE_CLASSES, device_class
|
||||
|
||||
|
||||
async def test_entity_state(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Tests the state attributes properly match the light types."""
|
||||
device = device_factory(
|
||||
"Motion Sensor 1", [Capability.motion_sensor], {Attribute.motion: "inactive"}
|
||||
)
|
||||
await setup_platform(hass, BINARY_SENSOR_DOMAIN, devices=[device])
|
||||
state = hass.states.get("binary_sensor.motion_sensor_1_motion")
|
||||
assert state.state == "off"
|
||||
assert state.attributes[ATTR_FRIENDLY_NAME] == f"{device.label} {Attribute.motion}"
|
||||
|
||||
|
||||
async def test_entity_and_device_attributes(
|
||||
hass: HomeAssistant,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
entity_registry: er.EntityRegistry,
|
||||
device_factory,
|
||||
) -> None:
|
||||
"""Test the attributes of the entity are correct."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Motion Sensor 1",
|
||||
[Capability.motion_sensor],
|
||||
{
|
||||
Attribute.motion: "inactive",
|
||||
Attribute.mnmo: "123",
|
||||
Attribute.mnmn: "Generic manufacturer",
|
||||
Attribute.mnhw: "v4.56",
|
||||
Attribute.mnfv: "v7.89",
|
||||
},
|
||||
)
|
||||
# Act
|
||||
await setup_platform(hass, BINARY_SENSOR_DOMAIN, devices=[device])
|
||||
# Assert
|
||||
entry = entity_registry.async_get("binary_sensor.motion_sensor_1_motion")
|
||||
assert entry
|
||||
assert entry.unique_id == f"{device.device_id}.{Attribute.motion}"
|
||||
entry = device_registry.async_get_device(identifiers={(DOMAIN, device.device_id)})
|
||||
assert entry
|
||||
assert entry.configuration_url == "https://account.smartthings.com"
|
||||
assert entry.identifiers == {(DOMAIN, device.device_id)}
|
||||
assert entry.name == device.label
|
||||
assert entry.model == "123"
|
||||
assert entry.manufacturer == "Generic manufacturer"
|
||||
assert entry.hw_version == "v4.56"
|
||||
assert entry.sw_version == "v7.89"
|
||||
|
||||
|
||||
async def test_update_from_signal(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Test the binary_sensor updates when receiving a signal."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Motion Sensor 1", [Capability.motion_sensor], {Attribute.motion: "inactive"}
|
||||
)
|
||||
await setup_platform(hass, BINARY_SENSOR_DOMAIN, devices=[device])
|
||||
device.status.apply_attribute_update(
|
||||
"main", Capability.motion_sensor, Attribute.motion, "active"
|
||||
)
|
||||
# Act
|
||||
async_dispatcher_send(hass, SIGNAL_SMARTTHINGS_UPDATE, [device.device_id])
|
||||
# Assert
|
||||
await hass.async_block_till_done()
|
||||
state = hass.states.get("binary_sensor.motion_sensor_1_motion")
|
||||
assert state is not None
|
||||
assert state.state == "on"
|
||||
|
||||
|
||||
async def test_unload_config_entry(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Test the binary_sensor is removed when the config entry is unloaded."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Motion Sensor 1", [Capability.motion_sensor], {Attribute.motion: "inactive"}
|
||||
)
|
||||
config_entry = await setup_platform(hass, BINARY_SENSOR_DOMAIN, devices=[device])
|
||||
config_entry.mock_state(hass, ConfigEntryState.LOADED)
|
||||
# Act
|
||||
await hass.config_entries.async_forward_entry_unload(config_entry, "binary_sensor")
|
||||
# Assert
|
||||
assert (
|
||||
hass.states.get("binary_sensor.motion_sensor_1_motion").state
|
||||
== STATE_UNAVAILABLE
|
||||
)
|
||||
|
||||
|
||||
async def test_entity_category(
|
||||
hass: HomeAssistant, entity_registry: er.EntityRegistry, device_factory
|
||||
) -> None:
|
||||
"""Tests the state attributes properly match the light types."""
|
||||
device1 = device_factory(
|
||||
"Motion Sensor 1", [Capability.motion_sensor], {Attribute.motion: "inactive"}
|
||||
)
|
||||
device2 = device_factory(
|
||||
"Tamper Sensor 2", [Capability.tamper_alert], {Attribute.tamper: "inactive"}
|
||||
)
|
||||
await setup_platform(hass, BINARY_SENSOR_DOMAIN, devices=[device1, device2])
|
||||
|
||||
entry = entity_registry.async_get("binary_sensor.motion_sensor_1_motion")
|
||||
assert entry
|
||||
assert entry.entity_category is None
|
||||
|
||||
entry = entity_registry.async_get("binary_sensor.tamper_sensor_2_tamper")
|
||||
assert entry
|
||||
assert entry.entity_category is EntityCategory.DIAGNOSTIC
|
||||
773
home-assistant/tests/components/smartthings/test_climate.py
Normal file
773
home-assistant/tests/components/smartthings/test_climate.py
Normal file
@@ -0,0 +1,773 @@
|
||||
"""Test for the SmartThings climate 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 pysmartthings.device import Status
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.climate import (
|
||||
ATTR_CURRENT_HUMIDITY,
|
||||
ATTR_CURRENT_TEMPERATURE,
|
||||
ATTR_FAN_MODE,
|
||||
ATTR_FAN_MODES,
|
||||
ATTR_HVAC_ACTION,
|
||||
ATTR_HVAC_MODE,
|
||||
ATTR_HVAC_MODES,
|
||||
ATTR_PRESET_MODE,
|
||||
ATTR_SWING_MODE,
|
||||
ATTR_TARGET_TEMP_HIGH,
|
||||
ATTR_TARGET_TEMP_LOW,
|
||||
DOMAIN as CLIMATE_DOMAIN,
|
||||
SERVICE_SET_FAN_MODE,
|
||||
SERVICE_SET_HVAC_MODE,
|
||||
SERVICE_SET_PRESET_MODE,
|
||||
SERVICE_SET_SWING_MODE,
|
||||
SERVICE_SET_TEMPERATURE,
|
||||
ClimateEntityFeature,
|
||||
HVACAction,
|
||||
HVACMode,
|
||||
)
|
||||
from homeassistant.components.smartthings import climate
|
||||
from homeassistant.components.smartthings.const import DOMAIN
|
||||
from homeassistant.const import (
|
||||
ATTR_ENTITY_ID,
|
||||
ATTR_SUPPORTED_FEATURES,
|
||||
ATTR_TEMPERATURE,
|
||||
SERVICE_TURN_OFF,
|
||||
SERVICE_TURN_ON,
|
||||
STATE_UNKNOWN,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
||||
|
||||
from .conftest import setup_platform
|
||||
|
||||
|
||||
@pytest.fixture(name="legacy_thermostat")
|
||||
def legacy_thermostat_fixture(device_factory):
|
||||
"""Fixture returns a legacy thermostat."""
|
||||
device = device_factory(
|
||||
"Legacy Thermostat",
|
||||
capabilities=[Capability.thermostat],
|
||||
status={
|
||||
Attribute.cooling_setpoint: 74,
|
||||
Attribute.heating_setpoint: 68,
|
||||
Attribute.thermostat_fan_mode: "auto",
|
||||
Attribute.supported_thermostat_fan_modes: ["auto", "on"],
|
||||
Attribute.thermostat_mode: "auto",
|
||||
Attribute.supported_thermostat_modes: climate.MODE_TO_STATE.keys(),
|
||||
Attribute.thermostat_operating_state: "idle",
|
||||
},
|
||||
)
|
||||
device.status.attributes[Attribute.temperature] = Status(70, "F", None)
|
||||
return device
|
||||
|
||||
|
||||
@pytest.fixture(name="basic_thermostat")
|
||||
def basic_thermostat_fixture(device_factory):
|
||||
"""Fixture returns a basic thermostat."""
|
||||
device = device_factory(
|
||||
"Basic Thermostat",
|
||||
capabilities=[
|
||||
Capability.temperature_measurement,
|
||||
Capability.thermostat_cooling_setpoint,
|
||||
Capability.thermostat_heating_setpoint,
|
||||
Capability.thermostat_mode,
|
||||
],
|
||||
status={
|
||||
Attribute.cooling_setpoint: 74,
|
||||
Attribute.heating_setpoint: 68,
|
||||
Attribute.thermostat_mode: "off",
|
||||
Attribute.supported_thermostat_modes: ["off", "auto", "heat", "cool"],
|
||||
},
|
||||
)
|
||||
device.status.attributes[Attribute.temperature] = Status(70, "F", None)
|
||||
return device
|
||||
|
||||
|
||||
@pytest.fixture(name="minimal_thermostat")
|
||||
def minimal_thermostat_fixture(device_factory):
|
||||
"""Fixture returns a minimal thermostat without cooling."""
|
||||
device = device_factory(
|
||||
"Minimal Thermostat",
|
||||
capabilities=[
|
||||
Capability.temperature_measurement,
|
||||
Capability.thermostat_heating_setpoint,
|
||||
Capability.thermostat_mode,
|
||||
],
|
||||
status={
|
||||
Attribute.heating_setpoint: 68,
|
||||
Attribute.thermostat_mode: "off",
|
||||
Attribute.supported_thermostat_modes: ["off", "heat"],
|
||||
},
|
||||
)
|
||||
device.status.attributes[Attribute.temperature] = Status(70, "F", None)
|
||||
return device
|
||||
|
||||
|
||||
@pytest.fixture(name="thermostat")
|
||||
def thermostat_fixture(device_factory):
|
||||
"""Fixture returns a fully-featured thermostat."""
|
||||
device = device_factory(
|
||||
"Thermostat",
|
||||
capabilities=[
|
||||
Capability.temperature_measurement,
|
||||
Capability.relative_humidity_measurement,
|
||||
Capability.thermostat_cooling_setpoint,
|
||||
Capability.thermostat_heating_setpoint,
|
||||
Capability.thermostat_mode,
|
||||
Capability.thermostat_operating_state,
|
||||
Capability.thermostat_fan_mode,
|
||||
],
|
||||
status={
|
||||
Attribute.cooling_setpoint: 74,
|
||||
Attribute.heating_setpoint: 68,
|
||||
Attribute.thermostat_fan_mode: "on",
|
||||
Attribute.supported_thermostat_fan_modes: ["auto", "on"],
|
||||
Attribute.thermostat_mode: "heat",
|
||||
Attribute.supported_thermostat_modes: [
|
||||
"auto",
|
||||
"heat",
|
||||
"cool",
|
||||
"off",
|
||||
"eco",
|
||||
],
|
||||
Attribute.thermostat_operating_state: "idle",
|
||||
Attribute.humidity: 34,
|
||||
Attribute.mnmo: "123",
|
||||
Attribute.mnmn: "Generic manufacturer",
|
||||
Attribute.mnhw: "v4.56",
|
||||
Attribute.mnfv: "v7.89",
|
||||
},
|
||||
)
|
||||
device.status.attributes[Attribute.temperature] = Status(70, "F", None)
|
||||
return device
|
||||
|
||||
|
||||
@pytest.fixture(name="buggy_thermostat")
|
||||
def buggy_thermostat_fixture(device_factory):
|
||||
"""Fixture returns a buggy thermostat."""
|
||||
device = device_factory(
|
||||
"Buggy Thermostat",
|
||||
capabilities=[
|
||||
Capability.temperature_measurement,
|
||||
Capability.thermostat_cooling_setpoint,
|
||||
Capability.thermostat_heating_setpoint,
|
||||
Capability.thermostat_mode,
|
||||
],
|
||||
status={
|
||||
Attribute.thermostat_mode: "heating",
|
||||
Attribute.cooling_setpoint: 74,
|
||||
Attribute.heating_setpoint: 68,
|
||||
},
|
||||
)
|
||||
device.status.attributes[Attribute.temperature] = Status(70, "F", None)
|
||||
return device
|
||||
|
||||
|
||||
@pytest.fixture(name="air_conditioner")
|
||||
def air_conditioner_fixture(device_factory):
|
||||
"""Fixture returns a air conditioner."""
|
||||
device = device_factory(
|
||||
"Air Conditioner",
|
||||
capabilities=[
|
||||
Capability.air_conditioner_mode,
|
||||
Capability.demand_response_load_control,
|
||||
Capability.air_conditioner_fan_mode,
|
||||
Capability.switch,
|
||||
Capability.temperature_measurement,
|
||||
Capability.thermostat_cooling_setpoint,
|
||||
Capability.fan_oscillation_mode,
|
||||
],
|
||||
status={
|
||||
Attribute.air_conditioner_mode: "auto",
|
||||
Attribute.supported_ac_modes: [
|
||||
"cool",
|
||||
"dry",
|
||||
"wind",
|
||||
"auto",
|
||||
"heat",
|
||||
"fanOnly",
|
||||
],
|
||||
Attribute.drlc_status: {
|
||||
"duration": 0,
|
||||
"drlcLevel": -1,
|
||||
"start": "1970-01-01T00:00:00Z",
|
||||
"override": False,
|
||||
},
|
||||
Attribute.fan_mode: "medium",
|
||||
Attribute.supported_ac_fan_modes: [
|
||||
"auto",
|
||||
"low",
|
||||
"medium",
|
||||
"high",
|
||||
"turbo",
|
||||
],
|
||||
Attribute.switch: "on",
|
||||
Attribute.cooling_setpoint: 23,
|
||||
"supportedAcOptionalMode": ["windFree"],
|
||||
Attribute.supported_fan_oscillation_modes: [
|
||||
"all",
|
||||
"horizontal",
|
||||
"vertical",
|
||||
"fixed",
|
||||
],
|
||||
Attribute.fan_oscillation_mode: "vertical",
|
||||
},
|
||||
)
|
||||
device.status.attributes[Attribute.temperature] = Status(24, "C", None)
|
||||
return device
|
||||
|
||||
|
||||
@pytest.fixture(name="air_conditioner_windfree")
|
||||
def air_conditioner_windfree_fixture(device_factory):
|
||||
"""Fixture returns a air conditioner."""
|
||||
device = device_factory(
|
||||
"Air Conditioner",
|
||||
capabilities=[
|
||||
Capability.air_conditioner_mode,
|
||||
Capability.demand_response_load_control,
|
||||
Capability.air_conditioner_fan_mode,
|
||||
Capability.switch,
|
||||
Capability.temperature_measurement,
|
||||
Capability.thermostat_cooling_setpoint,
|
||||
Capability.fan_oscillation_mode,
|
||||
],
|
||||
status={
|
||||
Attribute.air_conditioner_mode: "auto",
|
||||
Attribute.supported_ac_modes: [
|
||||
"cool",
|
||||
"dry",
|
||||
"wind",
|
||||
"auto",
|
||||
"heat",
|
||||
"wind",
|
||||
],
|
||||
Attribute.drlc_status: {
|
||||
"duration": 0,
|
||||
"drlcLevel": -1,
|
||||
"start": "1970-01-01T00:00:00Z",
|
||||
"override": False,
|
||||
},
|
||||
Attribute.fan_mode: "medium",
|
||||
Attribute.supported_ac_fan_modes: [
|
||||
"auto",
|
||||
"low",
|
||||
"medium",
|
||||
"high",
|
||||
"turbo",
|
||||
],
|
||||
Attribute.switch: "on",
|
||||
Attribute.cooling_setpoint: 23,
|
||||
"supportedAcOptionalMode": ["windFree"],
|
||||
Attribute.supported_fan_oscillation_modes: [
|
||||
"all",
|
||||
"horizontal",
|
||||
"vertical",
|
||||
"fixed",
|
||||
],
|
||||
Attribute.fan_oscillation_mode: "vertical",
|
||||
},
|
||||
)
|
||||
device.status.attributes[Attribute.temperature] = Status(24, "C", None)
|
||||
return device
|
||||
|
||||
|
||||
async def test_legacy_thermostat_entity_state(
|
||||
hass: HomeAssistant, legacy_thermostat
|
||||
) -> None:
|
||||
"""Tests the state attributes properly match the thermostat type."""
|
||||
await setup_platform(hass, CLIMATE_DOMAIN, devices=[legacy_thermostat])
|
||||
state = hass.states.get("climate.legacy_thermostat")
|
||||
assert state.state == HVACMode.HEAT_COOL
|
||||
assert (
|
||||
state.attributes[ATTR_SUPPORTED_FEATURES]
|
||||
== ClimateEntityFeature.FAN_MODE
|
||||
| ClimateEntityFeature.TARGET_TEMPERATURE_RANGE
|
||||
| ClimateEntityFeature.TARGET_TEMPERATURE
|
||||
| ClimateEntityFeature.TURN_OFF
|
||||
| ClimateEntityFeature.TURN_ON
|
||||
)
|
||||
assert state.attributes[ATTR_HVAC_ACTION] == HVACAction.IDLE
|
||||
assert sorted(state.attributes[ATTR_HVAC_MODES]) == [
|
||||
HVACMode.AUTO,
|
||||
HVACMode.COOL,
|
||||
HVACMode.HEAT,
|
||||
HVACMode.HEAT_COOL,
|
||||
HVACMode.OFF,
|
||||
]
|
||||
assert state.attributes[ATTR_FAN_MODE] == "auto"
|
||||
assert state.attributes[ATTR_FAN_MODES] == ["auto", "on"]
|
||||
assert state.attributes[ATTR_TARGET_TEMP_LOW] == 20 # celsius
|
||||
assert state.attributes[ATTR_TARGET_TEMP_HIGH] == 23.3 # celsius
|
||||
assert state.attributes[ATTR_CURRENT_TEMPERATURE] == 21.1 # celsius
|
||||
|
||||
|
||||
async def test_basic_thermostat_entity_state(
|
||||
hass: HomeAssistant, basic_thermostat
|
||||
) -> None:
|
||||
"""Tests the state attributes properly match the thermostat type."""
|
||||
await setup_platform(hass, CLIMATE_DOMAIN, devices=[basic_thermostat])
|
||||
state = hass.states.get("climate.basic_thermostat")
|
||||
assert state.state == HVACMode.OFF
|
||||
assert (
|
||||
state.attributes[ATTR_SUPPORTED_FEATURES]
|
||||
== ClimateEntityFeature.TARGET_TEMPERATURE_RANGE
|
||||
| ClimateEntityFeature.TARGET_TEMPERATURE
|
||||
| ClimateEntityFeature.TURN_OFF
|
||||
| ClimateEntityFeature.TURN_ON
|
||||
)
|
||||
assert ATTR_HVAC_ACTION not in state.attributes
|
||||
assert sorted(state.attributes[ATTR_HVAC_MODES]) == [
|
||||
HVACMode.COOL,
|
||||
HVACMode.HEAT,
|
||||
HVACMode.HEAT_COOL,
|
||||
HVACMode.OFF,
|
||||
]
|
||||
assert state.attributes[ATTR_CURRENT_TEMPERATURE] == 21.1 # celsius
|
||||
|
||||
|
||||
async def test_minimal_thermostat_entity_state(
|
||||
hass: HomeAssistant, minimal_thermostat
|
||||
) -> None:
|
||||
"""Tests the state attributes properly match the thermostat type."""
|
||||
await setup_platform(hass, CLIMATE_DOMAIN, devices=[minimal_thermostat])
|
||||
state = hass.states.get("climate.minimal_thermostat")
|
||||
assert state.state == HVACMode.OFF
|
||||
assert (
|
||||
state.attributes[ATTR_SUPPORTED_FEATURES]
|
||||
== ClimateEntityFeature.TARGET_TEMPERATURE_RANGE
|
||||
| ClimateEntityFeature.TARGET_TEMPERATURE
|
||||
| ClimateEntityFeature.TURN_OFF
|
||||
| ClimateEntityFeature.TURN_ON
|
||||
)
|
||||
assert ATTR_HVAC_ACTION not in state.attributes
|
||||
assert sorted(state.attributes[ATTR_HVAC_MODES]) == [
|
||||
HVACMode.HEAT,
|
||||
HVACMode.OFF,
|
||||
]
|
||||
assert state.attributes[ATTR_CURRENT_TEMPERATURE] == 21.1 # celsius
|
||||
|
||||
|
||||
async def test_thermostat_entity_state(hass: HomeAssistant, thermostat) -> None:
|
||||
"""Tests the state attributes properly match the thermostat type."""
|
||||
await setup_platform(hass, CLIMATE_DOMAIN, devices=[thermostat])
|
||||
state = hass.states.get("climate.thermostat")
|
||||
assert state.state == HVACMode.HEAT
|
||||
assert (
|
||||
state.attributes[ATTR_SUPPORTED_FEATURES]
|
||||
== ClimateEntityFeature.FAN_MODE
|
||||
| ClimateEntityFeature.TARGET_TEMPERATURE_RANGE
|
||||
| ClimateEntityFeature.TARGET_TEMPERATURE
|
||||
| ClimateEntityFeature.TURN_OFF
|
||||
| ClimateEntityFeature.TURN_ON
|
||||
)
|
||||
assert state.attributes[ATTR_HVAC_ACTION] == HVACAction.IDLE
|
||||
assert sorted(state.attributes[ATTR_HVAC_MODES]) == [
|
||||
HVACMode.AUTO,
|
||||
HVACMode.COOL,
|
||||
HVACMode.HEAT,
|
||||
HVACMode.HEAT_COOL,
|
||||
HVACMode.OFF,
|
||||
]
|
||||
assert state.attributes[ATTR_FAN_MODE] == "on"
|
||||
assert state.attributes[ATTR_FAN_MODES] == ["auto", "on"]
|
||||
assert state.attributes[ATTR_TEMPERATURE] == 20 # celsius
|
||||
assert state.attributes[ATTR_CURRENT_TEMPERATURE] == 21.1 # celsius
|
||||
assert state.attributes[ATTR_CURRENT_HUMIDITY] == 34
|
||||
|
||||
|
||||
async def test_buggy_thermostat_entity_state(
|
||||
hass: HomeAssistant, buggy_thermostat
|
||||
) -> None:
|
||||
"""Tests the state attributes properly match the thermostat type."""
|
||||
await setup_platform(hass, CLIMATE_DOMAIN, devices=[buggy_thermostat])
|
||||
state = hass.states.get("climate.buggy_thermostat")
|
||||
assert state.state == STATE_UNKNOWN
|
||||
assert (
|
||||
state.attributes[ATTR_SUPPORTED_FEATURES]
|
||||
== ClimateEntityFeature.TARGET_TEMPERATURE_RANGE
|
||||
| ClimateEntityFeature.TARGET_TEMPERATURE
|
||||
| ClimateEntityFeature.TURN_OFF
|
||||
| ClimateEntityFeature.TURN_ON
|
||||
)
|
||||
assert state.state is STATE_UNKNOWN
|
||||
assert state.attributes[ATTR_TEMPERATURE] is None
|
||||
assert state.attributes[ATTR_CURRENT_TEMPERATURE] == 21.1 # celsius
|
||||
assert state.attributes[ATTR_HVAC_MODES] == []
|
||||
|
||||
|
||||
async def test_buggy_thermostat_invalid_mode(
|
||||
hass: HomeAssistant, buggy_thermostat
|
||||
) -> None:
|
||||
"""Tests when an invalid operation mode is included."""
|
||||
buggy_thermostat.status.update_attribute_value(
|
||||
Attribute.supported_thermostat_modes, ["heat", "emergency heat", "other"]
|
||||
)
|
||||
await setup_platform(hass, CLIMATE_DOMAIN, devices=[buggy_thermostat])
|
||||
state = hass.states.get("climate.buggy_thermostat")
|
||||
assert state.attributes[ATTR_HVAC_MODES] == [HVACMode.HEAT]
|
||||
|
||||
|
||||
async def test_air_conditioner_entity_state(
|
||||
hass: HomeAssistant, air_conditioner
|
||||
) -> None:
|
||||
"""Tests when an invalid operation mode is included."""
|
||||
await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner])
|
||||
state = hass.states.get("climate.air_conditioner")
|
||||
assert state.state == HVACMode.HEAT_COOL
|
||||
assert (
|
||||
state.attributes[ATTR_SUPPORTED_FEATURES]
|
||||
== ClimateEntityFeature.FAN_MODE
|
||||
| ClimateEntityFeature.TARGET_TEMPERATURE
|
||||
| ClimateEntityFeature.PRESET_MODE
|
||||
| ClimateEntityFeature.SWING_MODE
|
||||
| ClimateEntityFeature.TURN_OFF
|
||||
| ClimateEntityFeature.TURN_ON
|
||||
)
|
||||
assert sorted(state.attributes[ATTR_HVAC_MODES]) == [
|
||||
HVACMode.COOL,
|
||||
HVACMode.DRY,
|
||||
HVACMode.FAN_ONLY,
|
||||
HVACMode.HEAT,
|
||||
HVACMode.HEAT_COOL,
|
||||
HVACMode.OFF,
|
||||
]
|
||||
assert state.attributes[ATTR_FAN_MODE] == "medium"
|
||||
assert sorted(state.attributes[ATTR_FAN_MODES]) == [
|
||||
"auto",
|
||||
"high",
|
||||
"low",
|
||||
"medium",
|
||||
"turbo",
|
||||
]
|
||||
assert state.attributes[ATTR_TEMPERATURE] == 23
|
||||
assert state.attributes[ATTR_CURRENT_TEMPERATURE] == 24
|
||||
assert state.attributes["drlc_status_duration"] == 0
|
||||
assert state.attributes["drlc_status_level"] == -1
|
||||
assert state.attributes["drlc_status_start"] == "1970-01-01T00:00:00Z"
|
||||
assert state.attributes["drlc_status_override"] is False
|
||||
|
||||
|
||||
async def test_set_fan_mode(hass: HomeAssistant, thermostat, air_conditioner) -> None:
|
||||
"""Test the fan mode is set successfully."""
|
||||
await setup_platform(hass, CLIMATE_DOMAIN, devices=[thermostat, air_conditioner])
|
||||
entity_ids = ["climate.thermostat", "climate.air_conditioner"]
|
||||
await hass.services.async_call(
|
||||
CLIMATE_DOMAIN,
|
||||
SERVICE_SET_FAN_MODE,
|
||||
{ATTR_ENTITY_ID: entity_ids, ATTR_FAN_MODE: "auto"},
|
||||
blocking=True,
|
||||
)
|
||||
for entity_id in entity_ids:
|
||||
state = hass.states.get(entity_id)
|
||||
assert state.attributes[ATTR_FAN_MODE] == "auto", entity_id
|
||||
|
||||
|
||||
async def test_set_hvac_mode(hass: HomeAssistant, thermostat, air_conditioner) -> None:
|
||||
"""Test the hvac mode is set successfully."""
|
||||
await setup_platform(hass, CLIMATE_DOMAIN, devices=[thermostat, air_conditioner])
|
||||
entity_ids = ["climate.thermostat", "climate.air_conditioner"]
|
||||
await hass.services.async_call(
|
||||
CLIMATE_DOMAIN,
|
||||
SERVICE_SET_HVAC_MODE,
|
||||
{ATTR_ENTITY_ID: entity_ids, ATTR_HVAC_MODE: HVACMode.COOL},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
for entity_id in entity_ids:
|
||||
state = hass.states.get(entity_id)
|
||||
assert state.state == HVACMode.COOL, entity_id
|
||||
|
||||
|
||||
async def test_ac_set_hvac_mode_from_off(hass: HomeAssistant, air_conditioner) -> None:
|
||||
"""Test setting HVAC mode when the unit is off."""
|
||||
air_conditioner.status.update_attribute_value(
|
||||
Attribute.air_conditioner_mode, "heat"
|
||||
)
|
||||
air_conditioner.status.update_attribute_value(Attribute.switch, "off")
|
||||
await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner])
|
||||
state = hass.states.get("climate.air_conditioner")
|
||||
assert state.state == HVACMode.OFF
|
||||
await hass.services.async_call(
|
||||
CLIMATE_DOMAIN,
|
||||
SERVICE_SET_HVAC_MODE,
|
||||
{
|
||||
ATTR_ENTITY_ID: "climate.air_conditioner",
|
||||
ATTR_HVAC_MODE: HVACMode.HEAT_COOL,
|
||||
},
|
||||
blocking=True,
|
||||
)
|
||||
state = hass.states.get("climate.air_conditioner")
|
||||
assert state.state == HVACMode.HEAT_COOL
|
||||
|
||||
|
||||
async def test_ac_set_hvac_mode_off(hass: HomeAssistant, air_conditioner) -> None:
|
||||
"""Test the AC HVAC mode can be turned off set successfully."""
|
||||
await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner])
|
||||
state = hass.states.get("climate.air_conditioner")
|
||||
assert state.state != HVACMode.OFF
|
||||
await hass.services.async_call(
|
||||
CLIMATE_DOMAIN,
|
||||
SERVICE_SET_HVAC_MODE,
|
||||
{ATTR_ENTITY_ID: "climate.air_conditioner", ATTR_HVAC_MODE: HVACMode.OFF},
|
||||
blocking=True,
|
||||
)
|
||||
state = hass.states.get("climate.air_conditioner")
|
||||
assert state.state == HVACMode.OFF
|
||||
|
||||
|
||||
async def test_ac_set_hvac_mode_wind(
|
||||
hass: HomeAssistant, air_conditioner_windfree
|
||||
) -> None:
|
||||
"""Test the AC HVAC mode to fan only as wind mode for supported models."""
|
||||
await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner_windfree])
|
||||
state = hass.states.get("climate.air_conditioner")
|
||||
assert state.state != HVACMode.OFF
|
||||
await hass.services.async_call(
|
||||
CLIMATE_DOMAIN,
|
||||
SERVICE_SET_HVAC_MODE,
|
||||
{ATTR_ENTITY_ID: "climate.air_conditioner", ATTR_HVAC_MODE: HVACMode.FAN_ONLY},
|
||||
blocking=True,
|
||||
)
|
||||
state = hass.states.get("climate.air_conditioner")
|
||||
assert state.state == HVACMode.FAN_ONLY
|
||||
|
||||
|
||||
async def test_set_temperature_heat_mode(hass: HomeAssistant, thermostat) -> None:
|
||||
"""Test the temperature is set successfully when in heat mode."""
|
||||
thermostat.status.thermostat_mode = "heat"
|
||||
await setup_platform(hass, CLIMATE_DOMAIN, devices=[thermostat])
|
||||
await hass.services.async_call(
|
||||
CLIMATE_DOMAIN,
|
||||
SERVICE_SET_TEMPERATURE,
|
||||
{ATTR_ENTITY_ID: "climate.thermostat", ATTR_TEMPERATURE: 21},
|
||||
blocking=True,
|
||||
)
|
||||
state = hass.states.get("climate.thermostat")
|
||||
assert state.state == HVACMode.HEAT
|
||||
assert state.attributes[ATTR_TEMPERATURE] == 21
|
||||
assert thermostat.status.heating_setpoint == 69.8
|
||||
|
||||
|
||||
async def test_set_temperature_cool_mode(hass: HomeAssistant, thermostat) -> None:
|
||||
"""Test the temperature is set successfully when in cool mode."""
|
||||
thermostat.status.thermostat_mode = "cool"
|
||||
await setup_platform(hass, CLIMATE_DOMAIN, devices=[thermostat])
|
||||
await hass.services.async_call(
|
||||
CLIMATE_DOMAIN,
|
||||
SERVICE_SET_TEMPERATURE,
|
||||
{ATTR_ENTITY_ID: "climate.thermostat", ATTR_TEMPERATURE: 21},
|
||||
blocking=True,
|
||||
)
|
||||
state = hass.states.get("climate.thermostat")
|
||||
assert state.attributes[ATTR_TEMPERATURE] == 21
|
||||
|
||||
|
||||
async def test_set_temperature(hass: HomeAssistant, thermostat) -> None:
|
||||
"""Test the temperature is set successfully."""
|
||||
thermostat.status.thermostat_mode = "auto"
|
||||
await setup_platform(hass, CLIMATE_DOMAIN, devices=[thermostat])
|
||||
await hass.services.async_call(
|
||||
CLIMATE_DOMAIN,
|
||||
SERVICE_SET_TEMPERATURE,
|
||||
{
|
||||
ATTR_ENTITY_ID: "climate.thermostat",
|
||||
ATTR_TARGET_TEMP_HIGH: 25.5,
|
||||
ATTR_TARGET_TEMP_LOW: 22.2,
|
||||
},
|
||||
blocking=True,
|
||||
)
|
||||
state = hass.states.get("climate.thermostat")
|
||||
assert state.attributes[ATTR_TARGET_TEMP_HIGH] == 25.5
|
||||
assert state.attributes[ATTR_TARGET_TEMP_LOW] == 22.2
|
||||
|
||||
|
||||
async def test_set_temperature_ac(hass: HomeAssistant, air_conditioner) -> None:
|
||||
"""Test the temperature is set successfully."""
|
||||
await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner])
|
||||
await hass.services.async_call(
|
||||
CLIMATE_DOMAIN,
|
||||
SERVICE_SET_TEMPERATURE,
|
||||
{ATTR_ENTITY_ID: "climate.air_conditioner", ATTR_TEMPERATURE: 27},
|
||||
blocking=True,
|
||||
)
|
||||
state = hass.states.get("climate.air_conditioner")
|
||||
assert state.attributes[ATTR_TEMPERATURE] == 27
|
||||
|
||||
|
||||
async def test_set_temperature_ac_with_mode(
|
||||
hass: HomeAssistant, air_conditioner
|
||||
) -> None:
|
||||
"""Test the temperature is set successfully."""
|
||||
await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner])
|
||||
await hass.services.async_call(
|
||||
CLIMATE_DOMAIN,
|
||||
SERVICE_SET_TEMPERATURE,
|
||||
{
|
||||
ATTR_ENTITY_ID: "climate.air_conditioner",
|
||||
ATTR_TEMPERATURE: 27,
|
||||
ATTR_HVAC_MODE: HVACMode.COOL,
|
||||
},
|
||||
blocking=True,
|
||||
)
|
||||
state = hass.states.get("climate.air_conditioner")
|
||||
assert state.attributes[ATTR_TEMPERATURE] == 27
|
||||
assert state.state == HVACMode.COOL
|
||||
|
||||
|
||||
async def test_set_temperature_ac_with_mode_from_off(
|
||||
hass: HomeAssistant, air_conditioner
|
||||
) -> None:
|
||||
"""Test the temp and mode is set successfully when the unit is off."""
|
||||
air_conditioner.status.update_attribute_value(
|
||||
Attribute.air_conditioner_mode, "heat"
|
||||
)
|
||||
air_conditioner.status.update_attribute_value(Attribute.switch, "off")
|
||||
await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner])
|
||||
assert hass.states.get("climate.air_conditioner").state == HVACMode.OFF
|
||||
await hass.services.async_call(
|
||||
CLIMATE_DOMAIN,
|
||||
SERVICE_SET_TEMPERATURE,
|
||||
{
|
||||
ATTR_ENTITY_ID: "climate.air_conditioner",
|
||||
ATTR_TEMPERATURE: 27,
|
||||
ATTR_HVAC_MODE: HVACMode.COOL,
|
||||
},
|
||||
blocking=True,
|
||||
)
|
||||
state = hass.states.get("climate.air_conditioner")
|
||||
assert state.attributes[ATTR_TEMPERATURE] == 27
|
||||
assert state.state == HVACMode.COOL
|
||||
|
||||
|
||||
async def test_set_temperature_ac_with_mode_to_off(
|
||||
hass: HomeAssistant, air_conditioner
|
||||
) -> None:
|
||||
"""Test the temp and mode is set successfully to turn off the unit."""
|
||||
await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner])
|
||||
assert hass.states.get("climate.air_conditioner").state != HVACMode.OFF
|
||||
await hass.services.async_call(
|
||||
CLIMATE_DOMAIN,
|
||||
SERVICE_SET_TEMPERATURE,
|
||||
{
|
||||
ATTR_ENTITY_ID: "climate.air_conditioner",
|
||||
ATTR_TEMPERATURE: 27,
|
||||
ATTR_HVAC_MODE: HVACMode.OFF,
|
||||
},
|
||||
blocking=True,
|
||||
)
|
||||
state = hass.states.get("climate.air_conditioner")
|
||||
assert state.attributes[ATTR_TEMPERATURE] == 27
|
||||
assert state.state == HVACMode.OFF
|
||||
|
||||
|
||||
async def test_set_temperature_with_mode(hass: HomeAssistant, thermostat) -> None:
|
||||
"""Test the temperature and mode is set successfully."""
|
||||
await setup_platform(hass, CLIMATE_DOMAIN, devices=[thermostat])
|
||||
await hass.services.async_call(
|
||||
CLIMATE_DOMAIN,
|
||||
SERVICE_SET_TEMPERATURE,
|
||||
{
|
||||
ATTR_ENTITY_ID: "climate.thermostat",
|
||||
ATTR_TARGET_TEMP_HIGH: 25.5,
|
||||
ATTR_TARGET_TEMP_LOW: 22.2,
|
||||
ATTR_HVAC_MODE: HVACMode.HEAT_COOL,
|
||||
},
|
||||
blocking=True,
|
||||
)
|
||||
state = hass.states.get("climate.thermostat")
|
||||
assert state.attributes[ATTR_TARGET_TEMP_HIGH] == 25.5
|
||||
assert state.attributes[ATTR_TARGET_TEMP_LOW] == 22.2
|
||||
assert state.state == HVACMode.HEAT_COOL
|
||||
|
||||
|
||||
async def test_set_turn_off(hass: HomeAssistant, air_conditioner) -> None:
|
||||
"""Test the a/c is turned off successfully."""
|
||||
await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner])
|
||||
state = hass.states.get("climate.air_conditioner")
|
||||
assert state.state == HVACMode.HEAT_COOL
|
||||
await hass.services.async_call(
|
||||
CLIMATE_DOMAIN, SERVICE_TURN_OFF, {"entity_id": "all"}, blocking=True
|
||||
)
|
||||
state = hass.states.get("climate.air_conditioner")
|
||||
assert state.state == HVACMode.OFF
|
||||
|
||||
|
||||
async def test_set_turn_on(hass: HomeAssistant, air_conditioner) -> None:
|
||||
"""Test the a/c is turned on successfully."""
|
||||
air_conditioner.status.update_attribute_value(Attribute.switch, "off")
|
||||
await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner])
|
||||
state = hass.states.get("climate.air_conditioner")
|
||||
assert state.state == HVACMode.OFF
|
||||
await hass.services.async_call(
|
||||
CLIMATE_DOMAIN, SERVICE_TURN_ON, {"entity_id": "all"}, blocking=True
|
||||
)
|
||||
state = hass.states.get("climate.air_conditioner")
|
||||
assert state.state == HVACMode.HEAT_COOL
|
||||
|
||||
|
||||
async def test_entity_and_device_attributes(
|
||||
hass: HomeAssistant,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
entity_registry: er.EntityRegistry,
|
||||
thermostat,
|
||||
) -> None:
|
||||
"""Test the attributes of the entries are correct."""
|
||||
await setup_platform(hass, CLIMATE_DOMAIN, devices=[thermostat])
|
||||
|
||||
entry = entity_registry.async_get("climate.thermostat")
|
||||
assert entry
|
||||
assert entry.unique_id == thermostat.device_id
|
||||
|
||||
entry = device_registry.async_get_device(
|
||||
identifiers={(DOMAIN, thermostat.device_id)}
|
||||
)
|
||||
assert entry
|
||||
assert entry.configuration_url == "https://account.smartthings.com"
|
||||
assert entry.identifiers == {(DOMAIN, thermostat.device_id)}
|
||||
assert entry.name == thermostat.label
|
||||
assert entry.model == "123"
|
||||
assert entry.manufacturer == "Generic manufacturer"
|
||||
assert entry.hw_version == "v4.56"
|
||||
assert entry.sw_version == "v7.89"
|
||||
|
||||
|
||||
async def test_set_windfree_off(hass: HomeAssistant, air_conditioner) -> None:
|
||||
"""Test if the windfree preset can be turned on and is turned off when fan mode is set."""
|
||||
entity_ids = ["climate.air_conditioner"]
|
||||
air_conditioner.status.update_attribute_value(Attribute.switch, "on")
|
||||
await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner])
|
||||
await hass.services.async_call(
|
||||
CLIMATE_DOMAIN,
|
||||
SERVICE_SET_PRESET_MODE,
|
||||
{ATTR_ENTITY_ID: entity_ids, ATTR_PRESET_MODE: "windFree"},
|
||||
blocking=True,
|
||||
)
|
||||
state = hass.states.get("climate.air_conditioner")
|
||||
assert state.attributes[ATTR_PRESET_MODE] == "windFree"
|
||||
await hass.services.async_call(
|
||||
CLIMATE_DOMAIN,
|
||||
SERVICE_SET_FAN_MODE,
|
||||
{ATTR_ENTITY_ID: entity_ids, ATTR_FAN_MODE: "low"},
|
||||
blocking=True,
|
||||
)
|
||||
state = hass.states.get("climate.air_conditioner")
|
||||
assert not state.attributes[ATTR_PRESET_MODE]
|
||||
|
||||
|
||||
async def test_set_swing_mode(hass: HomeAssistant, air_conditioner) -> None:
|
||||
"""Test the fan swing is set successfully."""
|
||||
await setup_platform(hass, CLIMATE_DOMAIN, devices=[air_conditioner])
|
||||
entity_ids = ["climate.air_conditioner"]
|
||||
await hass.services.async_call(
|
||||
CLIMATE_DOMAIN,
|
||||
SERVICE_SET_SWING_MODE,
|
||||
{ATTR_ENTITY_ID: entity_ids, ATTR_SWING_MODE: "vertical"},
|
||||
blocking=True,
|
||||
)
|
||||
state = hass.states.get("climate.air_conditioner")
|
||||
assert state.attributes[ATTR_SWING_MODE] == "vertical"
|
||||
813
home-assistant/tests/components/smartthings/test_config_flow.py
Normal file
813
home-assistant/tests/components/smartthings/test_config_flow.py
Normal file
@@ -0,0 +1,813 @@
|
||||
"""Tests for the SmartThings config flow module."""
|
||||
|
||||
from http import HTTPStatus
|
||||
from unittest.mock import AsyncMock, Mock, patch
|
||||
from uuid import uuid4
|
||||
|
||||
from aiohttp import ClientResponseError
|
||||
from pysmartthings import APIResponseError
|
||||
from pysmartthings.installedapp import format_install_url
|
||||
|
||||
from homeassistant import config_entries
|
||||
from homeassistant.components.smartthings import smartapp
|
||||
from homeassistant.components.smartthings.const import (
|
||||
CONF_APP_ID,
|
||||
CONF_INSTALLED_APP_ID,
|
||||
CONF_LOCATION_ID,
|
||||
CONF_REFRESH_TOKEN,
|
||||
DOMAIN,
|
||||
)
|
||||
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_CLIENT_ID, CONF_CLIENT_SECRET
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.core_config import async_process_ha_core_config
|
||||
from homeassistant.data_entry_flow import FlowResultType
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
|
||||
async def test_import_shows_user_step(hass: HomeAssistant) -> None:
|
||||
"""Test import source shows the user form."""
|
||||
# Webhook confirmation shown
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_IMPORT}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "user"
|
||||
assert result["description_placeholders"][
|
||||
"webhook_url"
|
||||
] == smartapp.get_webhook_url(hass)
|
||||
|
||||
|
||||
async def test_entry_created(
|
||||
hass: HomeAssistant, app, app_oauth_client, location, smartthings_mock
|
||||
) -> None:
|
||||
"""Test local webhook, new app, install event creates entry."""
|
||||
token = str(uuid4())
|
||||
installed_app_id = str(uuid4())
|
||||
refresh_token = str(uuid4())
|
||||
smartthings_mock.apps.return_value = []
|
||||
smartthings_mock.create_app.return_value = (app, app_oauth_client)
|
||||
smartthings_mock.locations.return_value = [location]
|
||||
request = Mock()
|
||||
request.installed_app_id = installed_app_id
|
||||
request.auth_token = token
|
||||
request.location_id = location.location_id
|
||||
request.refresh_token = refresh_token
|
||||
|
||||
# Webhook confirmation shown
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "user"
|
||||
assert result["description_placeholders"][
|
||||
"webhook_url"
|
||||
] == smartapp.get_webhook_url(hass)
|
||||
|
||||
# Advance to PAT screen
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "pat"
|
||||
assert "token_url" in result["description_placeholders"]
|
||||
assert "component_url" in result["description_placeholders"]
|
||||
|
||||
# Enter token and advance to location screen
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_ACCESS_TOKEN: token}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "select_location"
|
||||
|
||||
# Select location and advance to external auth
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_LOCATION_ID: location.location_id}
|
||||
)
|
||||
assert result["type"] is FlowResultType.EXTERNAL_STEP
|
||||
assert result["step_id"] == "authorize"
|
||||
assert result["url"] == format_install_url(app.app_id, location.location_id)
|
||||
|
||||
# Complete external auth and advance to install
|
||||
await smartapp.smartapp_install(hass, request, None, app)
|
||||
|
||||
# Finish
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"])
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["data"]["app_id"] == app.app_id
|
||||
assert result["data"]["installed_app_id"] == installed_app_id
|
||||
assert result["data"]["location_id"] == location.location_id
|
||||
assert result["data"]["access_token"] == token
|
||||
assert result["data"]["refresh_token"] == request.refresh_token
|
||||
assert result["data"][CONF_CLIENT_SECRET] == app_oauth_client.client_secret
|
||||
assert result["data"][CONF_CLIENT_ID] == app_oauth_client.client_id
|
||||
assert result["title"] == location.name
|
||||
entry = next(
|
||||
(entry for entry in hass.config_entries.async_entries(DOMAIN)),
|
||||
None,
|
||||
)
|
||||
assert entry.unique_id == smartapp.format_unique_id(
|
||||
app.app_id, location.location_id
|
||||
)
|
||||
|
||||
|
||||
async def test_entry_created_from_update_event(
|
||||
hass: HomeAssistant, app, app_oauth_client, location, smartthings_mock
|
||||
) -> None:
|
||||
"""Test local webhook, new app, update event creates entry."""
|
||||
token = str(uuid4())
|
||||
installed_app_id = str(uuid4())
|
||||
refresh_token = str(uuid4())
|
||||
smartthings_mock.apps.return_value = []
|
||||
smartthings_mock.create_app.return_value = (app, app_oauth_client)
|
||||
smartthings_mock.locations.return_value = [location]
|
||||
request = Mock()
|
||||
request.installed_app_id = installed_app_id
|
||||
request.auth_token = token
|
||||
request.location_id = location.location_id
|
||||
request.refresh_token = refresh_token
|
||||
|
||||
# Webhook confirmation shown
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "user"
|
||||
assert result["description_placeholders"][
|
||||
"webhook_url"
|
||||
] == smartapp.get_webhook_url(hass)
|
||||
|
||||
# Advance to PAT screen
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "pat"
|
||||
assert "token_url" in result["description_placeholders"]
|
||||
assert "component_url" in result["description_placeholders"]
|
||||
|
||||
# Enter token and advance to location screen
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_ACCESS_TOKEN: token}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "select_location"
|
||||
|
||||
# Select location and advance to external auth
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_LOCATION_ID: location.location_id}
|
||||
)
|
||||
assert result["type"] is FlowResultType.EXTERNAL_STEP
|
||||
assert result["step_id"] == "authorize"
|
||||
assert result["url"] == format_install_url(app.app_id, location.location_id)
|
||||
|
||||
# Complete external auth and advance to install
|
||||
await smartapp.smartapp_update(hass, request, None, app)
|
||||
|
||||
# Finish
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"])
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["data"]["app_id"] == app.app_id
|
||||
assert result["data"]["installed_app_id"] == installed_app_id
|
||||
assert result["data"]["location_id"] == location.location_id
|
||||
assert result["data"]["access_token"] == token
|
||||
assert result["data"]["refresh_token"] == request.refresh_token
|
||||
assert result["data"][CONF_CLIENT_SECRET] == app_oauth_client.client_secret
|
||||
assert result["data"][CONF_CLIENT_ID] == app_oauth_client.client_id
|
||||
assert result["title"] == location.name
|
||||
entry = next(
|
||||
(entry for entry in hass.config_entries.async_entries(DOMAIN)),
|
||||
None,
|
||||
)
|
||||
assert entry.unique_id == smartapp.format_unique_id(
|
||||
app.app_id, location.location_id
|
||||
)
|
||||
|
||||
|
||||
async def test_entry_created_existing_app_new_oauth_client(
|
||||
hass: HomeAssistant, app, app_oauth_client, location, smartthings_mock
|
||||
) -> None:
|
||||
"""Test entry is created with an existing app and generation of a new oauth client."""
|
||||
token = str(uuid4())
|
||||
installed_app_id = str(uuid4())
|
||||
refresh_token = str(uuid4())
|
||||
smartthings_mock.apps.return_value = [app]
|
||||
smartthings_mock.generate_app_oauth.return_value = app_oauth_client
|
||||
smartthings_mock.locations.return_value = [location]
|
||||
smartthings_mock.create_app = AsyncMock(return_value=(app, app_oauth_client))
|
||||
request = Mock()
|
||||
request.installed_app_id = installed_app_id
|
||||
request.auth_token = token
|
||||
request.location_id = location.location_id
|
||||
request.refresh_token = refresh_token
|
||||
|
||||
# Webhook confirmation shown
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "user"
|
||||
assert result["description_placeholders"][
|
||||
"webhook_url"
|
||||
] == smartapp.get_webhook_url(hass)
|
||||
|
||||
# Advance to PAT screen
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "pat"
|
||||
assert "token_url" in result["description_placeholders"]
|
||||
assert "component_url" in result["description_placeholders"]
|
||||
|
||||
# Enter token and advance to location screen
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_ACCESS_TOKEN: token}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "select_location"
|
||||
|
||||
# Select location and advance to external auth
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_LOCATION_ID: location.location_id}
|
||||
)
|
||||
assert result["type"] is FlowResultType.EXTERNAL_STEP
|
||||
assert result["step_id"] == "authorize"
|
||||
assert result["url"] == format_install_url(app.app_id, location.location_id)
|
||||
|
||||
# Complete external auth and advance to install
|
||||
await smartapp.smartapp_install(hass, request, None, app)
|
||||
|
||||
# Finish
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"])
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["data"]["app_id"] == app.app_id
|
||||
assert result["data"]["installed_app_id"] == installed_app_id
|
||||
assert result["data"]["location_id"] == location.location_id
|
||||
assert result["data"]["access_token"] == token
|
||||
assert result["data"]["refresh_token"] == request.refresh_token
|
||||
assert result["data"][CONF_CLIENT_SECRET] == app_oauth_client.client_secret
|
||||
assert result["data"][CONF_CLIENT_ID] == app_oauth_client.client_id
|
||||
assert result["title"] == location.name
|
||||
entry = next(
|
||||
(entry for entry in hass.config_entries.async_entries(DOMAIN)),
|
||||
None,
|
||||
)
|
||||
assert entry.unique_id == smartapp.format_unique_id(
|
||||
app.app_id, location.location_id
|
||||
)
|
||||
|
||||
|
||||
async def test_entry_created_existing_app_copies_oauth_client(
|
||||
hass: HomeAssistant, app, location, smartthings_mock
|
||||
) -> None:
|
||||
"""Test entry is created with an existing app and copies the oauth client from another entry."""
|
||||
token = str(uuid4())
|
||||
installed_app_id = str(uuid4())
|
||||
refresh_token = str(uuid4())
|
||||
oauth_client_id = str(uuid4())
|
||||
oauth_client_secret = str(uuid4())
|
||||
smartthings_mock.apps.return_value = [app]
|
||||
smartthings_mock.locations.return_value = [location]
|
||||
request = Mock()
|
||||
request.installed_app_id = installed_app_id
|
||||
request.auth_token = token
|
||||
request.location_id = location.location_id
|
||||
request.refresh_token = refresh_token
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data={
|
||||
CONF_APP_ID: app.app_id,
|
||||
CONF_CLIENT_ID: oauth_client_id,
|
||||
CONF_CLIENT_SECRET: oauth_client_secret,
|
||||
CONF_LOCATION_ID: str(uuid4()),
|
||||
CONF_INSTALLED_APP_ID: str(uuid4()),
|
||||
CONF_ACCESS_TOKEN: token,
|
||||
},
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
# Webhook confirmation shown
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "user"
|
||||
assert result["description_placeholders"][
|
||||
"webhook_url"
|
||||
] == smartapp.get_webhook_url(hass)
|
||||
|
||||
# Advance to PAT screen
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "pat"
|
||||
assert "token_url" in result["description_placeholders"]
|
||||
assert "component_url" in result["description_placeholders"]
|
||||
# Assert access token is defaulted to an existing entry for convenience.
|
||||
assert result["data_schema"]({}) == {CONF_ACCESS_TOKEN: token}
|
||||
|
||||
# Enter token and advance to location screen
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_ACCESS_TOKEN: token}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "select_location"
|
||||
|
||||
# Select location and advance to external auth
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_LOCATION_ID: location.location_id}
|
||||
)
|
||||
assert result["type"] is FlowResultType.EXTERNAL_STEP
|
||||
assert result["step_id"] == "authorize"
|
||||
assert result["url"] == format_install_url(app.app_id, location.location_id)
|
||||
|
||||
# Complete external auth and advance to install
|
||||
await smartapp.smartapp_install(hass, request, None, app)
|
||||
|
||||
# Finish
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"])
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["data"]["app_id"] == app.app_id
|
||||
assert result["data"]["installed_app_id"] == installed_app_id
|
||||
assert result["data"]["location_id"] == location.location_id
|
||||
assert result["data"]["access_token"] == token
|
||||
assert result["data"]["refresh_token"] == request.refresh_token
|
||||
assert result["data"][CONF_CLIENT_SECRET] == oauth_client_secret
|
||||
assert result["data"][CONF_CLIENT_ID] == oauth_client_id
|
||||
assert result["title"] == location.name
|
||||
entry = next(
|
||||
(
|
||||
entry
|
||||
for entry in hass.config_entries.async_entries(DOMAIN)
|
||||
if entry.data[CONF_INSTALLED_APP_ID] == installed_app_id
|
||||
),
|
||||
None,
|
||||
)
|
||||
assert entry.unique_id == smartapp.format_unique_id(
|
||||
app.app_id, location.location_id
|
||||
)
|
||||
|
||||
|
||||
async def test_entry_created_with_cloudhook(
|
||||
hass: HomeAssistant, app, app_oauth_client, location, smartthings_mock
|
||||
) -> None:
|
||||
"""Test cloud, new app, install event creates entry."""
|
||||
hass.config.components.add("cloud")
|
||||
# Unload the endpoint so we can reload it under the cloud.
|
||||
await smartapp.unload_smartapp_endpoint(hass)
|
||||
token = str(uuid4())
|
||||
installed_app_id = str(uuid4())
|
||||
refresh_token = str(uuid4())
|
||||
smartthings_mock.apps.return_value = []
|
||||
smartthings_mock.create_app = AsyncMock(return_value=(app, app_oauth_client))
|
||||
smartthings_mock.locations = AsyncMock(return_value=[location])
|
||||
request = Mock()
|
||||
request.installed_app_id = installed_app_id
|
||||
request.auth_token = token
|
||||
request.location_id = location.location_id
|
||||
request.refresh_token = refresh_token
|
||||
|
||||
with (
|
||||
patch.object(
|
||||
smartapp.cloud,
|
||||
"async_active_subscription",
|
||||
Mock(return_value=True),
|
||||
),
|
||||
patch.object(
|
||||
smartapp.cloud,
|
||||
"async_create_cloudhook",
|
||||
AsyncMock(return_value="http://cloud.test"),
|
||||
) as mock_create_cloudhook,
|
||||
):
|
||||
await smartapp.setup_smartapp_endpoint(hass, True)
|
||||
|
||||
# Webhook confirmation shown
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "user"
|
||||
assert result["description_placeholders"][
|
||||
"webhook_url"
|
||||
] == smartapp.get_webhook_url(hass)
|
||||
# One is done by app fixture, one done by new config entry
|
||||
assert mock_create_cloudhook.call_count == 2
|
||||
|
||||
# Advance to PAT screen
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "pat"
|
||||
assert "token_url" in result["description_placeholders"]
|
||||
assert "component_url" in result["description_placeholders"]
|
||||
|
||||
# Enter token and advance to location screen
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_ACCESS_TOKEN: token}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "select_location"
|
||||
|
||||
# Select location and advance to external auth
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_LOCATION_ID: location.location_id}
|
||||
)
|
||||
assert result["type"] is FlowResultType.EXTERNAL_STEP
|
||||
assert result["step_id"] == "authorize"
|
||||
assert result["url"] == format_install_url(app.app_id, location.location_id)
|
||||
|
||||
# Complete external auth and advance to install
|
||||
await smartapp.smartapp_install(hass, request, None, app)
|
||||
|
||||
# Finish
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"])
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["data"]["app_id"] == app.app_id
|
||||
assert result["data"]["installed_app_id"] == installed_app_id
|
||||
assert result["data"]["location_id"] == location.location_id
|
||||
assert result["data"]["access_token"] == token
|
||||
assert result["data"]["refresh_token"] == request.refresh_token
|
||||
assert result["data"][CONF_CLIENT_SECRET] == app_oauth_client.client_secret
|
||||
assert result["data"][CONF_CLIENT_ID] == app_oauth_client.client_id
|
||||
assert result["title"] == location.name
|
||||
entry = next(
|
||||
(entry for entry in hass.config_entries.async_entries(DOMAIN)),
|
||||
None,
|
||||
)
|
||||
assert entry.unique_id == smartapp.format_unique_id(
|
||||
app.app_id, location.location_id
|
||||
)
|
||||
|
||||
|
||||
async def test_invalid_webhook_aborts(hass: HomeAssistant) -> None:
|
||||
"""Test flow aborts if webhook is invalid."""
|
||||
# Webhook confirmation shown
|
||||
await async_process_ha_core_config(
|
||||
hass,
|
||||
{"external_url": "http://example.local:8123"},
|
||||
)
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "invalid_webhook_url"
|
||||
assert result["description_placeholders"][
|
||||
"webhook_url"
|
||||
] == smartapp.get_webhook_url(hass)
|
||||
assert "component_url" in result["description_placeholders"]
|
||||
|
||||
|
||||
async def test_invalid_token_shows_error(hass: HomeAssistant) -> None:
|
||||
"""Test an error is shown for invalid token formats."""
|
||||
token = "123456789"
|
||||
|
||||
# Webhook confirmation shown
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "user"
|
||||
assert result["description_placeholders"][
|
||||
"webhook_url"
|
||||
] == smartapp.get_webhook_url(hass)
|
||||
|
||||
# Advance to PAT screen
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "pat"
|
||||
assert "token_url" in result["description_placeholders"]
|
||||
assert "component_url" in result["description_placeholders"]
|
||||
|
||||
# Enter token
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_ACCESS_TOKEN: token}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "pat"
|
||||
assert result["data_schema"]({}) == {CONF_ACCESS_TOKEN: token}
|
||||
assert result["errors"] == {CONF_ACCESS_TOKEN: "token_invalid_format"}
|
||||
assert "token_url" in result["description_placeholders"]
|
||||
assert "component_url" in result["description_placeholders"]
|
||||
|
||||
|
||||
async def test_unauthorized_token_shows_error(
|
||||
hass: HomeAssistant, smartthings_mock
|
||||
) -> None:
|
||||
"""Test an error is shown for unauthorized token formats."""
|
||||
token = str(uuid4())
|
||||
request_info = Mock(real_url="http://example.com")
|
||||
smartthings_mock.apps.side_effect = ClientResponseError(
|
||||
request_info=request_info, history=None, status=HTTPStatus.UNAUTHORIZED
|
||||
)
|
||||
|
||||
# Webhook confirmation shown
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "user"
|
||||
assert result["description_placeholders"][
|
||||
"webhook_url"
|
||||
] == smartapp.get_webhook_url(hass)
|
||||
|
||||
# Advance to PAT screen
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "pat"
|
||||
assert "token_url" in result["description_placeholders"]
|
||||
assert "component_url" in result["description_placeholders"]
|
||||
|
||||
# Enter token
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_ACCESS_TOKEN: token}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "pat"
|
||||
assert result["data_schema"]({}) == {CONF_ACCESS_TOKEN: token}
|
||||
assert result["errors"] == {CONF_ACCESS_TOKEN: "token_unauthorized"}
|
||||
assert "token_url" in result["description_placeholders"]
|
||||
assert "component_url" in result["description_placeholders"]
|
||||
|
||||
|
||||
async def test_forbidden_token_shows_error(
|
||||
hass: HomeAssistant, smartthings_mock
|
||||
) -> None:
|
||||
"""Test an error is shown for forbidden token formats."""
|
||||
token = str(uuid4())
|
||||
request_info = Mock(real_url="http://example.com")
|
||||
smartthings_mock.apps.side_effect = ClientResponseError(
|
||||
request_info=request_info, history=None, status=HTTPStatus.FORBIDDEN
|
||||
)
|
||||
|
||||
# Webhook confirmation shown
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "user"
|
||||
assert result["description_placeholders"][
|
||||
"webhook_url"
|
||||
] == smartapp.get_webhook_url(hass)
|
||||
|
||||
# Advance to PAT screen
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "pat"
|
||||
assert "token_url" in result["description_placeholders"]
|
||||
assert "component_url" in result["description_placeholders"]
|
||||
|
||||
# Enter token
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_ACCESS_TOKEN: token}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "pat"
|
||||
assert result["data_schema"]({}) == {CONF_ACCESS_TOKEN: token}
|
||||
assert result["errors"] == {CONF_ACCESS_TOKEN: "token_forbidden"}
|
||||
assert "token_url" in result["description_placeholders"]
|
||||
assert "component_url" in result["description_placeholders"]
|
||||
|
||||
|
||||
async def test_webhook_problem_shows_error(
|
||||
hass: HomeAssistant, smartthings_mock
|
||||
) -> None:
|
||||
"""Test an error is shown when there's an problem with the webhook endpoint."""
|
||||
token = str(uuid4())
|
||||
data = {"error": {}}
|
||||
request_info = Mock(real_url="http://example.com")
|
||||
error = APIResponseError(
|
||||
request_info=request_info,
|
||||
history=None,
|
||||
data=data,
|
||||
status=HTTPStatus.UNPROCESSABLE_ENTITY,
|
||||
)
|
||||
error.is_target_error = Mock(return_value=True)
|
||||
smartthings_mock.apps.side_effect = error
|
||||
|
||||
# Webhook confirmation shown
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "user"
|
||||
assert result["description_placeholders"][
|
||||
"webhook_url"
|
||||
] == smartapp.get_webhook_url(hass)
|
||||
|
||||
# Advance to PAT screen
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "pat"
|
||||
assert "token_url" in result["description_placeholders"]
|
||||
assert "component_url" in result["description_placeholders"]
|
||||
|
||||
# Enter token
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_ACCESS_TOKEN: token}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "pat"
|
||||
assert result["data_schema"]({}) == {CONF_ACCESS_TOKEN: token}
|
||||
assert result["errors"] == {"base": "webhook_error"}
|
||||
assert "token_url" in result["description_placeholders"]
|
||||
assert "component_url" in result["description_placeholders"]
|
||||
|
||||
|
||||
async def test_api_error_shows_error(hass: HomeAssistant, smartthings_mock) -> None:
|
||||
"""Test an error is shown when other API errors occur."""
|
||||
token = str(uuid4())
|
||||
data = {"error": {}}
|
||||
request_info = Mock(real_url="http://example.com")
|
||||
error = APIResponseError(
|
||||
request_info=request_info,
|
||||
history=None,
|
||||
data=data,
|
||||
status=HTTPStatus.BAD_REQUEST,
|
||||
)
|
||||
smartthings_mock.apps.side_effect = error
|
||||
|
||||
# Webhook confirmation shown
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "user"
|
||||
assert result["description_placeholders"][
|
||||
"webhook_url"
|
||||
] == smartapp.get_webhook_url(hass)
|
||||
|
||||
# Advance to PAT screen
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "pat"
|
||||
assert "token_url" in result["description_placeholders"]
|
||||
assert "component_url" in result["description_placeholders"]
|
||||
|
||||
# Enter token
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_ACCESS_TOKEN: token}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "pat"
|
||||
assert result["data_schema"]({}) == {CONF_ACCESS_TOKEN: token}
|
||||
assert result["errors"] == {"base": "app_setup_error"}
|
||||
assert "token_url" in result["description_placeholders"]
|
||||
assert "component_url" in result["description_placeholders"]
|
||||
|
||||
|
||||
async def test_unknown_response_error_shows_error(
|
||||
hass: HomeAssistant, smartthings_mock
|
||||
) -> None:
|
||||
"""Test an error is shown when there is an unknown API error."""
|
||||
token = str(uuid4())
|
||||
request_info = Mock(real_url="http://example.com")
|
||||
error = ClientResponseError(
|
||||
request_info=request_info, history=None, status=HTTPStatus.NOT_FOUND
|
||||
)
|
||||
smartthings_mock.apps.side_effect = error
|
||||
|
||||
# Webhook confirmation shown
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "user"
|
||||
assert result["description_placeholders"][
|
||||
"webhook_url"
|
||||
] == smartapp.get_webhook_url(hass)
|
||||
|
||||
# Advance to PAT screen
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "pat"
|
||||
assert "token_url" in result["description_placeholders"]
|
||||
assert "component_url" in result["description_placeholders"]
|
||||
|
||||
# Enter token
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_ACCESS_TOKEN: token}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "pat"
|
||||
assert result["data_schema"]({}) == {CONF_ACCESS_TOKEN: token}
|
||||
assert result["errors"] == {"base": "app_setup_error"}
|
||||
assert "token_url" in result["description_placeholders"]
|
||||
assert "component_url" in result["description_placeholders"]
|
||||
|
||||
|
||||
async def test_unknown_error_shows_error(hass: HomeAssistant, smartthings_mock) -> None:
|
||||
"""Test an error is shown when there is an unknown API error."""
|
||||
token = str(uuid4())
|
||||
smartthings_mock.apps.side_effect = Exception("Unknown error")
|
||||
|
||||
# Webhook confirmation shown
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "user"
|
||||
assert result["description_placeholders"][
|
||||
"webhook_url"
|
||||
] == smartapp.get_webhook_url(hass)
|
||||
|
||||
# Advance to PAT screen
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "pat"
|
||||
assert "token_url" in result["description_placeholders"]
|
||||
assert "component_url" in result["description_placeholders"]
|
||||
|
||||
# Enter token
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_ACCESS_TOKEN: token}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "pat"
|
||||
assert result["data_schema"]({}) == {CONF_ACCESS_TOKEN: token}
|
||||
assert result["errors"] == {"base": "app_setup_error"}
|
||||
assert "token_url" in result["description_placeholders"]
|
||||
assert "component_url" in result["description_placeholders"]
|
||||
|
||||
|
||||
async def test_no_available_locations_aborts(
|
||||
hass: HomeAssistant, app, app_oauth_client, location, smartthings_mock
|
||||
) -> None:
|
||||
"""Test select location aborts if no available locations."""
|
||||
token = str(uuid4())
|
||||
smartthings_mock.apps.return_value = []
|
||||
smartthings_mock.create_app.return_value = (app, app_oauth_client)
|
||||
smartthings_mock.locations.return_value = [location]
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN, data={CONF_LOCATION_ID: location.location_id}
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
# Webhook confirmation shown
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "user"
|
||||
assert result["description_placeholders"][
|
||||
"webhook_url"
|
||||
] == smartapp.get_webhook_url(hass)
|
||||
|
||||
# Advance to PAT screen
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "pat"
|
||||
assert "token_url" in result["description_placeholders"]
|
||||
assert "component_url" in result["description_placeholders"]
|
||||
|
||||
# Enter token and advance to location screen
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_ACCESS_TOKEN: token}
|
||||
)
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "no_available_locations"
|
||||
|
||||
|
||||
async def test_reauth(
|
||||
hass: HomeAssistant, app, app_oauth_client, location, smartthings_mock
|
||||
) -> None:
|
||||
"""Test reauth flow."""
|
||||
token = str(uuid4())
|
||||
installed_app_id = str(uuid4())
|
||||
refresh_token = str(uuid4())
|
||||
smartthings_mock.apps.return_value = []
|
||||
smartthings_mock.create_app.return_value = (app, app_oauth_client)
|
||||
smartthings_mock.locations.return_value = [location]
|
||||
request = Mock()
|
||||
request.installed_app_id = installed_app_id
|
||||
request.auth_token = token
|
||||
request.location_id = location.location_id
|
||||
request.refresh_token = refresh_token
|
||||
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data={
|
||||
CONF_APP_ID: app.app_id,
|
||||
CONF_CLIENT_ID: app_oauth_client.client_id,
|
||||
CONF_CLIENT_SECRET: app_oauth_client.client_secret,
|
||||
CONF_LOCATION_ID: location.location_id,
|
||||
CONF_INSTALLED_APP_ID: installed_app_id,
|
||||
CONF_ACCESS_TOKEN: token,
|
||||
CONF_REFRESH_TOKEN: "abc",
|
||||
},
|
||||
unique_id=smartapp.format_unique_id(app.app_id, location.location_id),
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
result = await entry.start_reauth_flow(hass)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "reauth_confirm"
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
|
||||
assert result["type"] is FlowResultType.EXTERNAL_STEP
|
||||
assert result["step_id"] == "authorize"
|
||||
assert result["url"] == format_install_url(app.app_id, location.location_id)
|
||||
|
||||
await smartapp.smartapp_update(hass, request, None, app)
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"])
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "update_confirm"
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "reauth_successful"
|
||||
|
||||
assert entry.data[CONF_REFRESH_TOKEN] == refresh_token
|
||||
249
home-assistant/tests/components/smartthings/test_cover.py
Normal file
249
home-assistant/tests/components/smartthings/test_cover.py
Normal file
@@ -0,0 +1,249 @@
|
||||
"""Test for the SmartThings cover 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.cover import (
|
||||
ATTR_CURRENT_POSITION,
|
||||
ATTR_POSITION,
|
||||
DOMAIN as COVER_DOMAIN,
|
||||
SERVICE_CLOSE_COVER,
|
||||
SERVICE_OPEN_COVER,
|
||||
SERVICE_SET_COVER_POSITION,
|
||||
CoverState,
|
||||
)
|
||||
from homeassistant.components.smartthings.const import DOMAIN, SIGNAL_SMARTTHINGS_UPDATE
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.const import ATTR_BATTERY_LEVEL, ATTR_ENTITY_ID, STATE_UNAVAILABLE
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
||||
from homeassistant.helpers.dispatcher import async_dispatcher_send
|
||||
|
||||
from .conftest import setup_platform
|
||||
|
||||
|
||||
async def test_entity_and_device_attributes(
|
||||
hass: HomeAssistant,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
entity_registry: er.EntityRegistry,
|
||||
device_factory,
|
||||
) -> None:
|
||||
"""Test the attributes of the entity are correct."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Garage",
|
||||
[Capability.garage_door_control],
|
||||
{
|
||||
Attribute.door: "open",
|
||||
Attribute.mnmo: "123",
|
||||
Attribute.mnmn: "Generic manufacturer",
|
||||
Attribute.mnhw: "v4.56",
|
||||
Attribute.mnfv: "v7.89",
|
||||
},
|
||||
)
|
||||
# Act
|
||||
await setup_platform(hass, COVER_DOMAIN, devices=[device])
|
||||
# Assert
|
||||
entry = entity_registry.async_get("cover.garage")
|
||||
assert entry
|
||||
assert entry.unique_id == device.device_id
|
||||
|
||||
entry = device_registry.async_get_device(identifiers={(DOMAIN, device.device_id)})
|
||||
assert entry
|
||||
assert entry.configuration_url == "https://account.smartthings.com"
|
||||
assert entry.identifiers == {(DOMAIN, device.device_id)}
|
||||
assert entry.name == device.label
|
||||
assert entry.model == "123"
|
||||
assert entry.manufacturer == "Generic manufacturer"
|
||||
assert entry.hw_version == "v4.56"
|
||||
assert entry.sw_version == "v7.89"
|
||||
|
||||
|
||||
async def test_open(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Test the cover opens doors, garages, and shades successfully."""
|
||||
# Arrange
|
||||
devices = {
|
||||
device_factory("Door", [Capability.door_control], {Attribute.door: "closed"}),
|
||||
device_factory(
|
||||
"Garage", [Capability.garage_door_control], {Attribute.door: "closed"}
|
||||
),
|
||||
device_factory(
|
||||
"Shade", [Capability.window_shade], {Attribute.window_shade: "closed"}
|
||||
),
|
||||
}
|
||||
await setup_platform(hass, COVER_DOMAIN, devices=devices)
|
||||
entity_ids = ["cover.door", "cover.garage", "cover.shade"]
|
||||
# Act
|
||||
await hass.services.async_call(
|
||||
COVER_DOMAIN, SERVICE_OPEN_COVER, {ATTR_ENTITY_ID: entity_ids}, blocking=True
|
||||
)
|
||||
# Assert
|
||||
for entity_id in entity_ids:
|
||||
state = hass.states.get(entity_id)
|
||||
assert state is not None
|
||||
assert state.state == CoverState.OPENING
|
||||
|
||||
|
||||
async def test_close(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Test the cover closes doors, garages, and shades successfully."""
|
||||
# Arrange
|
||||
devices = {
|
||||
device_factory("Door", [Capability.door_control], {Attribute.door: "open"}),
|
||||
device_factory(
|
||||
"Garage", [Capability.garage_door_control], {Attribute.door: "open"}
|
||||
),
|
||||
device_factory(
|
||||
"Shade", [Capability.window_shade], {Attribute.window_shade: "open"}
|
||||
),
|
||||
}
|
||||
await setup_platform(hass, COVER_DOMAIN, devices=devices)
|
||||
entity_ids = ["cover.door", "cover.garage", "cover.shade"]
|
||||
# Act
|
||||
await hass.services.async_call(
|
||||
COVER_DOMAIN, SERVICE_CLOSE_COVER, {ATTR_ENTITY_ID: entity_ids}, blocking=True
|
||||
)
|
||||
# Assert
|
||||
for entity_id in entity_ids:
|
||||
state = hass.states.get(entity_id)
|
||||
assert state is not None
|
||||
assert state.state == CoverState.CLOSING
|
||||
|
||||
|
||||
async def test_set_cover_position_switch_level(
|
||||
hass: HomeAssistant, device_factory
|
||||
) -> None:
|
||||
"""Test the cover sets to the specific position for legacy devices that use Capability.switch_level."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Shade",
|
||||
[Capability.window_shade, Capability.battery, Capability.switch_level],
|
||||
{Attribute.window_shade: "opening", Attribute.battery: 95, Attribute.level: 10},
|
||||
)
|
||||
await setup_platform(hass, COVER_DOMAIN, devices=[device])
|
||||
# Act
|
||||
await hass.services.async_call(
|
||||
COVER_DOMAIN,
|
||||
SERVICE_SET_COVER_POSITION,
|
||||
{ATTR_POSITION: 50, "entity_id": "all"},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
state = hass.states.get("cover.shade")
|
||||
# Result of call does not update state
|
||||
assert state.state == CoverState.OPENING
|
||||
assert state.attributes[ATTR_BATTERY_LEVEL] == 95
|
||||
assert state.attributes[ATTR_CURRENT_POSITION] == 10
|
||||
# Ensure API called
|
||||
|
||||
assert device._api.post_device_command.call_count == 1
|
||||
|
||||
|
||||
async def test_set_cover_position(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Test the cover sets to the specific position."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Shade",
|
||||
[Capability.window_shade, Capability.battery, Capability.window_shade_level],
|
||||
{
|
||||
Attribute.window_shade: "opening",
|
||||
Attribute.battery: 95,
|
||||
Attribute.shade_level: 10,
|
||||
},
|
||||
)
|
||||
await setup_platform(hass, COVER_DOMAIN, devices=[device])
|
||||
# Act
|
||||
await hass.services.async_call(
|
||||
COVER_DOMAIN,
|
||||
SERVICE_SET_COVER_POSITION,
|
||||
{ATTR_POSITION: 50, "entity_id": "all"},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
state = hass.states.get("cover.shade")
|
||||
# Result of call does not update state
|
||||
assert state.state == CoverState.OPENING
|
||||
assert state.attributes[ATTR_BATTERY_LEVEL] == 95
|
||||
assert state.attributes[ATTR_CURRENT_POSITION] == 10
|
||||
# Ensure API called
|
||||
|
||||
assert device._api.post_device_command.call_count == 1
|
||||
|
||||
|
||||
async def test_set_cover_position_unsupported(
|
||||
hass: HomeAssistant, device_factory
|
||||
) -> None:
|
||||
"""Test set position does nothing when not supported by device."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Shade", [Capability.window_shade], {Attribute.window_shade: "opening"}
|
||||
)
|
||||
await setup_platform(hass, COVER_DOMAIN, devices=[device])
|
||||
# Act
|
||||
await hass.services.async_call(
|
||||
COVER_DOMAIN,
|
||||
SERVICE_SET_COVER_POSITION,
|
||||
{"entity_id": "all", ATTR_POSITION: 50},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
state = hass.states.get("cover.shade")
|
||||
assert ATTR_CURRENT_POSITION not in state.attributes
|
||||
|
||||
# Ensure API was not called
|
||||
|
||||
assert device._api.post_device_command.call_count == 0
|
||||
|
||||
|
||||
async def test_update_to_open_from_signal(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Test the cover updates to open when receiving a signal."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Garage", [Capability.garage_door_control], {Attribute.door: "opening"}
|
||||
)
|
||||
await setup_platform(hass, COVER_DOMAIN, devices=[device])
|
||||
device.status.update_attribute_value(Attribute.door, "open")
|
||||
assert hass.states.get("cover.garage").state == CoverState.OPENING
|
||||
# Act
|
||||
async_dispatcher_send(hass, SIGNAL_SMARTTHINGS_UPDATE, [device.device_id])
|
||||
# Assert
|
||||
await hass.async_block_till_done()
|
||||
state = hass.states.get("cover.garage")
|
||||
assert state is not None
|
||||
assert state.state == CoverState.OPEN
|
||||
|
||||
|
||||
async def test_update_to_closed_from_signal(
|
||||
hass: HomeAssistant, device_factory
|
||||
) -> None:
|
||||
"""Test the cover updates to closed when receiving a signal."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Garage", [Capability.garage_door_control], {Attribute.door: "closing"}
|
||||
)
|
||||
await setup_platform(hass, COVER_DOMAIN, devices=[device])
|
||||
device.status.update_attribute_value(Attribute.door, "closed")
|
||||
assert hass.states.get("cover.garage").state == CoverState.CLOSING
|
||||
# Act
|
||||
async_dispatcher_send(hass, SIGNAL_SMARTTHINGS_UPDATE, [device.device_id])
|
||||
# Assert
|
||||
await hass.async_block_till_done()
|
||||
state = hass.states.get("cover.garage")
|
||||
assert state is not None
|
||||
assert state.state == CoverState.CLOSED
|
||||
|
||||
|
||||
async def test_unload_config_entry(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Test the lock is removed when the config entry is unloaded."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Garage", [Capability.garage_door_control], {Attribute.door: "open"}
|
||||
)
|
||||
config_entry = await setup_platform(hass, COVER_DOMAIN, devices=[device])
|
||||
config_entry.mock_state(hass, ConfigEntryState.LOADED)
|
||||
# Act
|
||||
await hass.config_entries.async_forward_entry_unload(config_entry, COVER_DOMAIN)
|
||||
# Assert
|
||||
assert hass.states.get("cover.garage").state == STATE_UNAVAILABLE
|
||||
433
home-assistant/tests/components/smartthings/test_fan.py
Normal file
433
home-assistant/tests/components/smartthings/test_fan.py
Normal file
@@ -0,0 +1,433 @@
|
||||
"""Test for the SmartThings fan 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.fan import (
|
||||
ATTR_PERCENTAGE,
|
||||
ATTR_PRESET_MODE,
|
||||
ATTR_PRESET_MODES,
|
||||
DOMAIN as FAN_DOMAIN,
|
||||
FanEntityFeature,
|
||||
)
|
||||
from homeassistant.components.smartthings.const import DOMAIN, SIGNAL_SMARTTHINGS_UPDATE
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.const import (
|
||||
ATTR_ENTITY_ID,
|
||||
ATTR_SUPPORTED_FEATURES,
|
||||
STATE_UNAVAILABLE,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
||||
from homeassistant.helpers.dispatcher import async_dispatcher_send
|
||||
|
||||
from .conftest import setup_platform
|
||||
|
||||
|
||||
async def test_entity_state(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Tests the state attributes properly match the fan types."""
|
||||
device = device_factory(
|
||||
"Fan 1",
|
||||
capabilities=[Capability.switch, Capability.fan_speed],
|
||||
status={Attribute.switch: "on", Attribute.fan_speed: 2},
|
||||
)
|
||||
await setup_platform(hass, FAN_DOMAIN, devices=[device])
|
||||
|
||||
# Dimmer 1
|
||||
state = hass.states.get("fan.fan_1")
|
||||
assert state.state == "on"
|
||||
assert (
|
||||
state.attributes[ATTR_SUPPORTED_FEATURES]
|
||||
== FanEntityFeature.SET_SPEED
|
||||
| FanEntityFeature.TURN_OFF
|
||||
| FanEntityFeature.TURN_ON
|
||||
)
|
||||
assert state.attributes[ATTR_PERCENTAGE] == 66
|
||||
|
||||
|
||||
async def test_entity_and_device_attributes(
|
||||
hass: HomeAssistant,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
entity_registry: er.EntityRegistry,
|
||||
device_factory,
|
||||
) -> None:
|
||||
"""Test the attributes of the entity are correct."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Fan 1",
|
||||
capabilities=[Capability.switch, Capability.fan_speed],
|
||||
status={
|
||||
Attribute.switch: "on",
|
||||
Attribute.fan_speed: 2,
|
||||
Attribute.mnmo: "123",
|
||||
Attribute.mnmn: "Generic manufacturer",
|
||||
Attribute.mnhw: "v4.56",
|
||||
Attribute.mnfv: "v7.89",
|
||||
},
|
||||
)
|
||||
# Act
|
||||
await setup_platform(hass, FAN_DOMAIN, devices=[device])
|
||||
# Assert
|
||||
entry = entity_registry.async_get("fan.fan_1")
|
||||
assert entry
|
||||
assert entry.unique_id == device.device_id
|
||||
|
||||
entry = device_registry.async_get_device(identifiers={(DOMAIN, device.device_id)})
|
||||
assert entry
|
||||
assert entry.configuration_url == "https://account.smartthings.com"
|
||||
assert entry.identifiers == {(DOMAIN, device.device_id)}
|
||||
assert entry.name == device.label
|
||||
assert entry.model == "123"
|
||||
assert entry.manufacturer == "Generic manufacturer"
|
||||
assert entry.hw_version == "v4.56"
|
||||
assert entry.sw_version == "v7.89"
|
||||
|
||||
|
||||
# Setup platform tests with varying capabilities
|
||||
async def test_setup_mode_capability(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Test setting up a fan with only the mode capability."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Fan 1",
|
||||
capabilities=[Capability.switch, Capability.air_conditioner_fan_mode],
|
||||
status={
|
||||
Attribute.switch: "off",
|
||||
Attribute.fan_mode: "high",
|
||||
Attribute.supported_ac_fan_modes: ["high", "low", "medium"],
|
||||
},
|
||||
)
|
||||
|
||||
await setup_platform(hass, FAN_DOMAIN, devices=[device])
|
||||
|
||||
# Assert
|
||||
state = hass.states.get("fan.fan_1")
|
||||
assert state is not None
|
||||
assert (
|
||||
state.attributes[ATTR_SUPPORTED_FEATURES]
|
||||
== FanEntityFeature.PRESET_MODE
|
||||
| FanEntityFeature.TURN_OFF
|
||||
| FanEntityFeature.TURN_ON
|
||||
)
|
||||
assert state.attributes[ATTR_PRESET_MODE] == "high"
|
||||
assert state.attributes[ATTR_PRESET_MODES] == ["high", "low", "medium"]
|
||||
|
||||
|
||||
async def test_setup_speed_capability(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Test setting up a fan with only the speed capability."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Fan 1",
|
||||
capabilities=[Capability.switch, Capability.fan_speed],
|
||||
status={
|
||||
Attribute.switch: "off",
|
||||
Attribute.fan_speed: 2,
|
||||
},
|
||||
)
|
||||
|
||||
await setup_platform(hass, FAN_DOMAIN, devices=[device])
|
||||
|
||||
# Assert
|
||||
state = hass.states.get("fan.fan_1")
|
||||
assert state is not None
|
||||
assert (
|
||||
state.attributes[ATTR_SUPPORTED_FEATURES]
|
||||
== FanEntityFeature.SET_SPEED
|
||||
| FanEntityFeature.TURN_OFF
|
||||
| FanEntityFeature.TURN_ON
|
||||
)
|
||||
assert state.attributes[ATTR_PERCENTAGE] == 66
|
||||
|
||||
|
||||
async def test_setup_both_capabilities(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Test setting up a fan with both the mode and speed capability."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Fan 1",
|
||||
capabilities=[
|
||||
Capability.switch,
|
||||
Capability.fan_speed,
|
||||
Capability.air_conditioner_fan_mode,
|
||||
],
|
||||
status={
|
||||
Attribute.switch: "off",
|
||||
Attribute.fan_speed: 2,
|
||||
Attribute.fan_mode: "high",
|
||||
Attribute.supported_ac_fan_modes: ["high", "low", "medium"],
|
||||
},
|
||||
)
|
||||
|
||||
await setup_platform(hass, FAN_DOMAIN, devices=[device])
|
||||
|
||||
# Assert
|
||||
state = hass.states.get("fan.fan_1")
|
||||
assert state is not None
|
||||
assert (
|
||||
state.attributes[ATTR_SUPPORTED_FEATURES]
|
||||
== FanEntityFeature.SET_SPEED
|
||||
| FanEntityFeature.PRESET_MODE
|
||||
| FanEntityFeature.TURN_OFF
|
||||
| FanEntityFeature.TURN_ON
|
||||
)
|
||||
assert state.attributes[ATTR_PERCENTAGE] == 66
|
||||
assert state.attributes[ATTR_PRESET_MODE] == "high"
|
||||
assert state.attributes[ATTR_PRESET_MODES] == ["high", "low", "medium"]
|
||||
|
||||
|
||||
# Speed Capability Tests
|
||||
|
||||
|
||||
async def test_turn_off_speed_capability(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Test the fan turns of successfully."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Fan 1",
|
||||
capabilities=[Capability.switch, Capability.fan_speed],
|
||||
status={Attribute.switch: "on", Attribute.fan_speed: 2},
|
||||
)
|
||||
await setup_platform(hass, FAN_DOMAIN, devices=[device])
|
||||
# Act
|
||||
await hass.services.async_call(
|
||||
"fan", "turn_off", {"entity_id": "fan.fan_1"}, blocking=True
|
||||
)
|
||||
# Assert
|
||||
state = hass.states.get("fan.fan_1")
|
||||
assert state is not None
|
||||
assert state.state == "off"
|
||||
|
||||
|
||||
async def test_turn_on_speed_capability(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Test the fan turns of successfully."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Fan 1",
|
||||
capabilities=[Capability.switch, Capability.fan_speed],
|
||||
status={Attribute.switch: "off", Attribute.fan_speed: 0},
|
||||
)
|
||||
await setup_platform(hass, FAN_DOMAIN, devices=[device])
|
||||
# Act
|
||||
await hass.services.async_call(
|
||||
"fan", "turn_on", {ATTR_ENTITY_ID: "fan.fan_1"}, blocking=True
|
||||
)
|
||||
# Assert
|
||||
state = hass.states.get("fan.fan_1")
|
||||
assert state is not None
|
||||
assert state.state == "on"
|
||||
|
||||
|
||||
async def test_turn_on_with_speed_speed_capability(
|
||||
hass: HomeAssistant, device_factory
|
||||
) -> None:
|
||||
"""Test the fan turns on to the specified speed."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Fan 1",
|
||||
capabilities=[Capability.switch, Capability.fan_speed],
|
||||
status={Attribute.switch: "off", Attribute.fan_speed: 0},
|
||||
)
|
||||
await setup_platform(hass, FAN_DOMAIN, devices=[device])
|
||||
# Act
|
||||
await hass.services.async_call(
|
||||
"fan",
|
||||
"turn_on",
|
||||
{ATTR_ENTITY_ID: "fan.fan_1", ATTR_PERCENTAGE: 100},
|
||||
blocking=True,
|
||||
)
|
||||
# Assert
|
||||
state = hass.states.get("fan.fan_1")
|
||||
assert state is not None
|
||||
assert state.state == "on"
|
||||
assert state.attributes[ATTR_PERCENTAGE] == 100
|
||||
|
||||
|
||||
async def test_turn_off_with_speed_speed_capability(
|
||||
hass: HomeAssistant, device_factory
|
||||
) -> None:
|
||||
"""Test the fan turns off with the speed."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Fan 1",
|
||||
capabilities=[Capability.switch, Capability.fan_speed],
|
||||
status={Attribute.switch: "on", Attribute.fan_speed: 100},
|
||||
)
|
||||
await setup_platform(hass, FAN_DOMAIN, devices=[device])
|
||||
# Act
|
||||
await hass.services.async_call(
|
||||
"fan",
|
||||
"set_percentage",
|
||||
{ATTR_ENTITY_ID: "fan.fan_1", ATTR_PERCENTAGE: 0},
|
||||
blocking=True,
|
||||
)
|
||||
# Assert
|
||||
state = hass.states.get("fan.fan_1")
|
||||
assert state is not None
|
||||
assert state.state == "off"
|
||||
|
||||
|
||||
async def test_set_percentage_speed_capability(
|
||||
hass: HomeAssistant, device_factory
|
||||
) -> None:
|
||||
"""Test setting to specific fan speed."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Fan 1",
|
||||
capabilities=[Capability.switch, Capability.fan_speed],
|
||||
status={Attribute.switch: "off", Attribute.fan_speed: 0},
|
||||
)
|
||||
await setup_platform(hass, FAN_DOMAIN, devices=[device])
|
||||
# Act
|
||||
await hass.services.async_call(
|
||||
"fan",
|
||||
"set_percentage",
|
||||
{ATTR_ENTITY_ID: "fan.fan_1", ATTR_PERCENTAGE: 100},
|
||||
blocking=True,
|
||||
)
|
||||
# Assert
|
||||
state = hass.states.get("fan.fan_1")
|
||||
assert state is not None
|
||||
assert state.state == "on"
|
||||
assert state.attributes[ATTR_PERCENTAGE] == 100
|
||||
|
||||
|
||||
async def test_update_from_signal_speed_capability(
|
||||
hass: HomeAssistant, device_factory
|
||||
) -> None:
|
||||
"""Test the fan updates when receiving a signal."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Fan 1",
|
||||
capabilities=[Capability.switch, Capability.fan_speed],
|
||||
status={Attribute.switch: "off", Attribute.fan_speed: 0},
|
||||
)
|
||||
await setup_platform(hass, FAN_DOMAIN, devices=[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("fan.fan_1")
|
||||
assert state is not None
|
||||
assert state.state == "on"
|
||||
|
||||
|
||||
async def test_unload_config_entry(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Test the fan is removed when the config entry is unloaded."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Fan 1",
|
||||
capabilities=[Capability.switch, Capability.fan_speed],
|
||||
status={Attribute.switch: "off", Attribute.fan_speed: 0},
|
||||
)
|
||||
config_entry = await setup_platform(hass, FAN_DOMAIN, devices=[device])
|
||||
config_entry.mock_state(hass, ConfigEntryState.LOADED)
|
||||
# Act
|
||||
await hass.config_entries.async_forward_entry_unload(config_entry, "fan")
|
||||
# Assert
|
||||
assert hass.states.get("fan.fan_1").state == STATE_UNAVAILABLE
|
||||
|
||||
|
||||
# Preset Mode Tests
|
||||
|
||||
|
||||
async def test_turn_off_mode_capability(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Test the fan turns of successfully."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Fan 1",
|
||||
capabilities=[Capability.switch, Capability.air_conditioner_fan_mode],
|
||||
status={
|
||||
Attribute.switch: "on",
|
||||
Attribute.fan_mode: "high",
|
||||
Attribute.supported_ac_fan_modes: ["high", "low", "medium"],
|
||||
},
|
||||
)
|
||||
await setup_platform(hass, FAN_DOMAIN, devices=[device])
|
||||
# Act
|
||||
await hass.services.async_call(
|
||||
"fan", "turn_off", {"entity_id": "fan.fan_1"}, blocking=True
|
||||
)
|
||||
# Assert
|
||||
state = hass.states.get("fan.fan_1")
|
||||
assert state is not None
|
||||
assert state.state == "off"
|
||||
assert state.attributes[ATTR_PRESET_MODE] == "high"
|
||||
|
||||
|
||||
async def test_turn_on_mode_capability(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Test the fan turns of successfully."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Fan 1",
|
||||
capabilities=[Capability.switch, Capability.air_conditioner_fan_mode],
|
||||
status={
|
||||
Attribute.switch: "off",
|
||||
Attribute.fan_mode: "high",
|
||||
Attribute.supported_ac_fan_modes: ["high", "low", "medium"],
|
||||
},
|
||||
)
|
||||
await setup_platform(hass, FAN_DOMAIN, devices=[device])
|
||||
# Act
|
||||
await hass.services.async_call(
|
||||
"fan", "turn_on", {ATTR_ENTITY_ID: "fan.fan_1"}, blocking=True
|
||||
)
|
||||
# Assert
|
||||
state = hass.states.get("fan.fan_1")
|
||||
assert state is not None
|
||||
assert state.state == "on"
|
||||
assert state.attributes[ATTR_PRESET_MODE] == "high"
|
||||
|
||||
|
||||
async def test_update_from_signal_mode_capability(
|
||||
hass: HomeAssistant, device_factory
|
||||
) -> None:
|
||||
"""Test the fan updates when receiving a signal."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Fan 1",
|
||||
capabilities=[Capability.switch, Capability.air_conditioner_fan_mode],
|
||||
status={
|
||||
Attribute.switch: "off",
|
||||
Attribute.fan_mode: "high",
|
||||
Attribute.supported_ac_fan_modes: ["high", "low", "medium"],
|
||||
},
|
||||
)
|
||||
await setup_platform(hass, FAN_DOMAIN, devices=[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("fan.fan_1")
|
||||
assert state is not None
|
||||
assert state.state == "on"
|
||||
|
||||
|
||||
async def test_set_preset_mode_mode_capability(
|
||||
hass: HomeAssistant, device_factory
|
||||
) -> None:
|
||||
"""Test setting to specific fan mode."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Fan 1",
|
||||
capabilities=[Capability.switch, Capability.air_conditioner_fan_mode],
|
||||
status={
|
||||
Attribute.switch: "off",
|
||||
Attribute.fan_mode: "high",
|
||||
Attribute.supported_ac_fan_modes: ["high", "low", "medium"],
|
||||
},
|
||||
)
|
||||
|
||||
await setup_platform(hass, FAN_DOMAIN, devices=[device])
|
||||
# Act
|
||||
await hass.services.async_call(
|
||||
"fan",
|
||||
"set_preset_mode",
|
||||
{ATTR_ENTITY_ID: "fan.fan_1", ATTR_PRESET_MODE: "low"},
|
||||
blocking=True,
|
||||
)
|
||||
# Assert
|
||||
state = hass.states.get("fan.fan_1")
|
||||
assert state is not None
|
||||
assert state.attributes[ATTR_PRESET_MODE] == "low"
|
||||
568
home-assistant/tests/components/smartthings/test_init.py
Normal file
568
home-assistant/tests/components/smartthings/test_init.py
Normal file
@@ -0,0 +1,568 @@
|
||||
"""Tests for the SmartThings component init module."""
|
||||
|
||||
from collections.abc import Callable, Coroutine
|
||||
from datetime import datetime, timedelta
|
||||
from http import HTTPStatus
|
||||
from typing import Any
|
||||
from unittest.mock import Mock, patch
|
||||
from uuid import uuid4
|
||||
|
||||
from aiohttp import ClientConnectionError, ClientResponseError
|
||||
from pysmartthings import InstalledAppStatus, OAuthToken
|
||||
import pytest
|
||||
|
||||
from homeassistant import config_entries
|
||||
from homeassistant.components import cloud, smartthings
|
||||
from homeassistant.components.smartthings.const import (
|
||||
CONF_CLOUDHOOK_URL,
|
||||
CONF_INSTALLED_APP_ID,
|
||||
CONF_REFRESH_TOKEN,
|
||||
DATA_BROKERS,
|
||||
DOMAIN,
|
||||
EVENT_BUTTON,
|
||||
PLATFORMS,
|
||||
SIGNAL_SMARTTHINGS_UPDATE,
|
||||
)
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.core_config import async_process_ha_core_config
|
||||
from homeassistant.exceptions import ConfigEntryNotReady
|
||||
from homeassistant.helpers.dispatcher import async_dispatcher_connect
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
|
||||
async def test_migration_creates_new_flow(
|
||||
hass: HomeAssistant, smartthings_mock, config_entry
|
||||
) -> None:
|
||||
"""Test migration deletes app and creates new flow."""
|
||||
|
||||
config_entry.add_to_hass(hass)
|
||||
hass.config_entries.async_update_entry(config_entry, version=1)
|
||||
|
||||
await smartthings.async_migrate_entry(hass, config_entry)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert smartthings_mock.delete_installed_app.call_count == 1
|
||||
assert smartthings_mock.delete_app.call_count == 1
|
||||
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": config_entries.SOURCE_IMPORT}
|
||||
|
||||
|
||||
async def test_unrecoverable_api_errors_create_new_flow(
|
||||
hass: HomeAssistant, config_entry, smartthings_mock
|
||||
) -> None:
|
||||
"""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?)
|
||||
"""
|
||||
|
||||
config_entry.add_to_hass(hass)
|
||||
request_info = Mock(real_url="http://example.com")
|
||||
smartthings_mock.app.side_effect = ClientResponseError(
|
||||
request_info=request_info, history=None, status=HTTPStatus.UNAUTHORIZED
|
||||
)
|
||||
|
||||
# Assert setup returns false
|
||||
result = await hass.config_entries.async_setup(config_entry.entry_id)
|
||||
assert not result
|
||||
|
||||
assert config_entry.state == ConfigEntryState.SETUP_ERROR
|
||||
|
||||
|
||||
async def test_recoverable_api_errors_raise_not_ready(
|
||||
hass: HomeAssistant, config_entry, smartthings_mock
|
||||
) -> None:
|
||||
"""Test config entry not ready raised for recoverable API errors."""
|
||||
config_entry.add_to_hass(hass)
|
||||
request_info = Mock(real_url="http://example.com")
|
||||
smartthings_mock.app.side_effect = ClientResponseError(
|
||||
request_info=request_info,
|
||||
history=None,
|
||||
status=HTTPStatus.INTERNAL_SERVER_ERROR,
|
||||
)
|
||||
|
||||
with pytest.raises(ConfigEntryNotReady):
|
||||
await smartthings.async_setup_entry(hass, config_entry)
|
||||
|
||||
|
||||
async def test_scenes_api_errors_raise_not_ready(
|
||||
hass: HomeAssistant, config_entry, app, installed_app, smartthings_mock
|
||||
) -> None:
|
||||
"""Test if scenes are unauthorized we continue to load platforms."""
|
||||
config_entry.add_to_hass(hass)
|
||||
request_info = Mock(real_url="http://example.com")
|
||||
smartthings_mock.app.return_value = app
|
||||
smartthings_mock.installed_app.return_value = installed_app
|
||||
smartthings_mock.scenes.side_effect = ClientResponseError(
|
||||
request_info=request_info,
|
||||
history=None,
|
||||
status=HTTPStatus.INTERNAL_SERVER_ERROR,
|
||||
)
|
||||
with pytest.raises(ConfigEntryNotReady):
|
||||
await smartthings.async_setup_entry(hass, config_entry)
|
||||
|
||||
|
||||
async def test_connection_errors_raise_not_ready(
|
||||
hass: HomeAssistant, config_entry, smartthings_mock
|
||||
) -> None:
|
||||
"""Test config entry not ready raised for connection errors."""
|
||||
config_entry.add_to_hass(hass)
|
||||
smartthings_mock.app.side_effect = 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: HomeAssistant, config_entry, app, smartthings_mock
|
||||
) -> None:
|
||||
"""Test base_url no longer valid creates a new flow."""
|
||||
await async_process_ha_core_config(
|
||||
hass,
|
||||
{"external_url": "http://example.local:8123"},
|
||||
)
|
||||
config_entry.add_to_hass(hass)
|
||||
smartthings_mock.app.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: HomeAssistant, config_entry, app, installed_app, smartthings_mock
|
||||
) -> None:
|
||||
"""Test config entry not ready raised when the app isn't authorized."""
|
||||
config_entry.add_to_hass(hass)
|
||||
installed_app.installed_app_status = InstalledAppStatus.PENDING
|
||||
|
||||
smartthings_mock.app.return_value = app
|
||||
smartthings_mock.installed_app.return_value = installed_app
|
||||
|
||||
with pytest.raises(ConfigEntryNotReady):
|
||||
await smartthings.async_setup_entry(hass, config_entry)
|
||||
|
||||
|
||||
async def test_scenes_unauthorized_loads_platforms(
|
||||
hass: HomeAssistant,
|
||||
config_entry,
|
||||
app,
|
||||
installed_app,
|
||||
device,
|
||||
smartthings_mock,
|
||||
subscription_factory,
|
||||
) -> None:
|
||||
"""Test if scenes are unauthorized we continue to load platforms."""
|
||||
config_entry.add_to_hass(hass)
|
||||
request_info = Mock(real_url="http://example.com")
|
||||
smartthings_mock.app.return_value = app
|
||||
smartthings_mock.installed_app.return_value = installed_app
|
||||
smartthings_mock.devices.return_value = [device]
|
||||
smartthings_mock.scenes.side_effect = ClientResponseError(
|
||||
request_info=request_info, history=None, status=HTTPStatus.FORBIDDEN
|
||||
)
|
||||
mock_token = Mock()
|
||||
mock_token.access_token = str(uuid4())
|
||||
mock_token.refresh_token = str(uuid4())
|
||||
smartthings_mock.generate_tokens.return_value = mock_token
|
||||
subscriptions = [
|
||||
subscription_factory(capability) for capability in device.capabilities
|
||||
]
|
||||
smartthings_mock.subscriptions.return_value = subscriptions
|
||||
|
||||
with patch.object(
|
||||
hass.config_entries, "async_forward_entry_setups"
|
||||
) as forward_mock:
|
||||
assert await hass.config_entries.async_setup(config_entry.entry_id)
|
||||
# Assert platforms loaded
|
||||
await hass.async_block_till_done()
|
||||
forward_mock.assert_called_once_with(config_entry, PLATFORMS)
|
||||
|
||||
|
||||
async def test_config_entry_loads_platforms(
|
||||
hass: HomeAssistant,
|
||||
config_entry,
|
||||
app,
|
||||
installed_app,
|
||||
device,
|
||||
smartthings_mock,
|
||||
subscription_factory,
|
||||
scene,
|
||||
) -> None:
|
||||
"""Test config entry loads properly and proxies to platforms."""
|
||||
config_entry.add_to_hass(hass)
|
||||
smartthings_mock.app.return_value = app
|
||||
smartthings_mock.installed_app.return_value = installed_app
|
||||
smartthings_mock.devices.return_value = [device]
|
||||
smartthings_mock.scenes.return_value = [scene]
|
||||
mock_token = Mock()
|
||||
mock_token.access_token = str(uuid4())
|
||||
mock_token.refresh_token = str(uuid4())
|
||||
smartthings_mock.generate_tokens.return_value = mock_token
|
||||
subscriptions = [
|
||||
subscription_factory(capability) for capability in device.capabilities
|
||||
]
|
||||
smartthings_mock.subscriptions.return_value = subscriptions
|
||||
|
||||
with patch.object(
|
||||
hass.config_entries, "async_forward_entry_setups"
|
||||
) as forward_mock:
|
||||
assert await hass.config_entries.async_setup(config_entry.entry_id)
|
||||
# Assert platforms loaded
|
||||
await hass.async_block_till_done()
|
||||
forward_mock.assert_called_once_with(config_entry, PLATFORMS)
|
||||
|
||||
|
||||
async def test_config_entry_loads_unconnected_cloud(
|
||||
hass: HomeAssistant,
|
||||
config_entry,
|
||||
app,
|
||||
installed_app,
|
||||
device,
|
||||
smartthings_mock,
|
||||
subscription_factory,
|
||||
scene,
|
||||
) -> None:
|
||||
"""Test entry loads during startup when cloud isn't connected."""
|
||||
config_entry.add_to_hass(hass)
|
||||
hass.data[DOMAIN][CONF_CLOUDHOOK_URL] = "https://test.cloud"
|
||||
smartthings_mock.app.return_value = app
|
||||
smartthings_mock.installed_app.return_value = installed_app
|
||||
smartthings_mock.devices.return_value = [device]
|
||||
smartthings_mock.scenes.return_value = [scene]
|
||||
mock_token = Mock()
|
||||
mock_token.access_token = str(uuid4())
|
||||
mock_token.refresh_token = str(uuid4())
|
||||
smartthings_mock.generate_tokens.return_value = mock_token
|
||||
subscriptions = [
|
||||
subscription_factory(capability) for capability in device.capabilities
|
||||
]
|
||||
smartthings_mock.subscriptions.return_value = subscriptions
|
||||
with patch.object(
|
||||
hass.config_entries, "async_forward_entry_setups"
|
||||
) as forward_mock:
|
||||
assert await hass.config_entries.async_setup(config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
forward_mock.assert_called_once_with(config_entry, PLATFORMS)
|
||||
|
||||
|
||||
async def test_unload_entry(hass: HomeAssistant, config_entry) -> None:
|
||||
"""Test entries are unloaded correctly."""
|
||||
connect_disconnect = Mock()
|
||||
smart_app = Mock()
|
||||
smart_app.connect_event.return_value = connect_disconnect
|
||||
broker = smartthings.DeviceBroker(hass, config_entry, Mock(), smart_app, [], [])
|
||||
broker.connect()
|
||||
hass.data[DOMAIN][DATA_BROKERS][config_entry.entry_id] = broker
|
||||
|
||||
with patch.object(
|
||||
hass.config_entries, "async_forward_entry_unload", return_value=True
|
||||
) as forward_mock:
|
||||
assert await smartthings.async_unload_entry(hass, config_entry)
|
||||
|
||||
assert connect_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(PLATFORMS)
|
||||
|
||||
|
||||
async def test_remove_entry(
|
||||
hass: HomeAssistant, config_entry, smartthings_mock
|
||||
) -> None:
|
||||
"""Test that the installed app and app are removed up."""
|
||||
# Act
|
||||
await smartthings.async_remove_entry(hass, config_entry)
|
||||
# Assert
|
||||
assert smartthings_mock.delete_installed_app.call_count == 1
|
||||
assert smartthings_mock.delete_app.call_count == 1
|
||||
|
||||
|
||||
async def test_remove_entry_cloudhook(
|
||||
hass: HomeAssistant, config_entry, smartthings_mock
|
||||
) -> None:
|
||||
"""Test that the installed app, app, and cloudhook are removed up."""
|
||||
hass.config.components.add("cloud")
|
||||
# Arrange
|
||||
config_entry.add_to_hass(hass)
|
||||
hass.data[DOMAIN][CONF_CLOUDHOOK_URL] = "https://test.cloud"
|
||||
# Act
|
||||
with (
|
||||
patch.object(
|
||||
cloud, "async_is_logged_in", return_value=True
|
||||
) as mock_async_is_logged_in,
|
||||
patch.object(cloud, "async_delete_cloudhook") as mock_async_delete_cloudhook,
|
||||
):
|
||||
await smartthings.async_remove_entry(hass, config_entry)
|
||||
# Assert
|
||||
assert smartthings_mock.delete_installed_app.call_count == 1
|
||||
assert smartthings_mock.delete_app.call_count == 1
|
||||
assert mock_async_is_logged_in.call_count == 1
|
||||
assert mock_async_delete_cloudhook.call_count == 1
|
||||
|
||||
|
||||
async def test_remove_entry_app_in_use(
|
||||
hass: HomeAssistant, config_entry, smartthings_mock
|
||||
) -> None:
|
||||
"""Test app is not removed if in use by another config entry."""
|
||||
# Arrange
|
||||
config_entry.add_to_hass(hass)
|
||||
data = config_entry.data.copy()
|
||||
data[CONF_INSTALLED_APP_ID] = str(uuid4())
|
||||
entry2 = MockConfigEntry(version=2, domain=DOMAIN, data=data)
|
||||
entry2.add_to_hass(hass)
|
||||
# Act
|
||||
await smartthings.async_remove_entry(hass, config_entry)
|
||||
# Assert
|
||||
assert smartthings_mock.delete_installed_app.call_count == 1
|
||||
assert smartthings_mock.delete_app.call_count == 0
|
||||
|
||||
|
||||
async def test_remove_entry_already_deleted(
|
||||
hass: HomeAssistant, config_entry, smartthings_mock
|
||||
) -> None:
|
||||
"""Test handles when the apps have already been removed."""
|
||||
request_info = Mock(real_url="http://example.com")
|
||||
# Arrange
|
||||
smartthings_mock.delete_installed_app.side_effect = ClientResponseError(
|
||||
request_info=request_info, history=None, status=HTTPStatus.FORBIDDEN
|
||||
)
|
||||
smartthings_mock.delete_app.side_effect = ClientResponseError(
|
||||
request_info=request_info, history=None, status=HTTPStatus.FORBIDDEN
|
||||
)
|
||||
# Act
|
||||
await smartthings.async_remove_entry(hass, config_entry)
|
||||
# Assert
|
||||
assert smartthings_mock.delete_installed_app.call_count == 1
|
||||
assert smartthings_mock.delete_app.call_count == 1
|
||||
|
||||
|
||||
async def test_remove_entry_installedapp_api_error(
|
||||
hass: HomeAssistant, config_entry, smartthings_mock
|
||||
) -> None:
|
||||
"""Test raises exceptions removing the installed app."""
|
||||
request_info = Mock(real_url="http://example.com")
|
||||
# Arrange
|
||||
smartthings_mock.delete_installed_app.side_effect = ClientResponseError(
|
||||
request_info=request_info,
|
||||
history=None,
|
||||
status=HTTPStatus.INTERNAL_SERVER_ERROR,
|
||||
)
|
||||
# Act
|
||||
with pytest.raises(ClientResponseError):
|
||||
await smartthings.async_remove_entry(hass, config_entry)
|
||||
# Assert
|
||||
assert smartthings_mock.delete_installed_app.call_count == 1
|
||||
assert smartthings_mock.delete_app.call_count == 0
|
||||
|
||||
|
||||
async def test_remove_entry_installedapp_unknown_error(
|
||||
hass: HomeAssistant, config_entry, smartthings_mock
|
||||
) -> None:
|
||||
"""Test raises exceptions removing the installed app."""
|
||||
# Arrange
|
||||
smartthings_mock.delete_installed_app.side_effect = ValueError
|
||||
# Act
|
||||
with pytest.raises(ValueError):
|
||||
await smartthings.async_remove_entry(hass, config_entry)
|
||||
# Assert
|
||||
assert smartthings_mock.delete_installed_app.call_count == 1
|
||||
assert smartthings_mock.delete_app.call_count == 0
|
||||
|
||||
|
||||
async def test_remove_entry_app_api_error(
|
||||
hass: HomeAssistant, config_entry, smartthings_mock
|
||||
) -> None:
|
||||
"""Test raises exceptions removing the app."""
|
||||
# Arrange
|
||||
request_info = Mock(real_url="http://example.com")
|
||||
smartthings_mock.delete_app.side_effect = ClientResponseError(
|
||||
request_info=request_info,
|
||||
history=None,
|
||||
status=HTTPStatus.INTERNAL_SERVER_ERROR,
|
||||
)
|
||||
# Act
|
||||
with pytest.raises(ClientResponseError):
|
||||
await smartthings.async_remove_entry(hass, config_entry)
|
||||
# Assert
|
||||
assert smartthings_mock.delete_installed_app.call_count == 1
|
||||
assert smartthings_mock.delete_app.call_count == 1
|
||||
|
||||
|
||||
async def test_remove_entry_app_unknown_error(
|
||||
hass: HomeAssistant, config_entry, smartthings_mock
|
||||
) -> None:
|
||||
"""Test raises exceptions removing the app."""
|
||||
# Arrange
|
||||
smartthings_mock.delete_app.side_effect = ValueError
|
||||
# Act
|
||||
with pytest.raises(ValueError):
|
||||
await smartthings.async_remove_entry(hass, config_entry)
|
||||
# Assert
|
||||
assert smartthings_mock.delete_installed_app.call_count == 1
|
||||
assert smartthings_mock.delete_app.call_count == 1
|
||||
|
||||
|
||||
async def test_broker_regenerates_token(hass: HomeAssistant, config_entry) -> None:
|
||||
"""Test the device broker regenerates the refresh token."""
|
||||
token = Mock(OAuthToken)
|
||||
token.refresh_token = str(uuid4())
|
||||
stored_action = None
|
||||
config_entry.add_to_hass(hass)
|
||||
|
||||
def async_track_time_interval(
|
||||
hass: HomeAssistant,
|
||||
action: Callable[[datetime], Coroutine[Any, Any, None] | None],
|
||||
interval: timedelta,
|
||||
) -> None:
|
||||
nonlocal stored_action
|
||||
stored_action = action
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.smartthings.async_track_time_interval",
|
||||
new=async_track_time_interval,
|
||||
):
|
||||
broker = smartthings.DeviceBroker(hass, config_entry, token, Mock(), [], [])
|
||||
broker.connect()
|
||||
|
||||
assert stored_action
|
||||
await stored_action(None)
|
||||
assert token.refresh.call_count == 1
|
||||
assert config_entry.data[CONF_REFRESH_TOKEN] == token.refresh_token
|
||||
|
||||
|
||||
async def test_event_handler_dispatches_updated_devices(
|
||||
hass: HomeAssistant,
|
||||
config_entry,
|
||||
device_factory,
|
||||
event_request_factory,
|
||||
event_factory,
|
||||
) -> None:
|
||||
"""Test the event handler dispatches updated devices."""
|
||||
devices = [
|
||||
device_factory("Bedroom 1 Switch", ["switch"]),
|
||||
device_factory("Bathroom 1", ["switch"]),
|
||||
device_factory("Sensor", ["motionSensor"]),
|
||||
device_factory("Lock", ["lock"]),
|
||||
]
|
||||
device_ids = [
|
||||
devices[0].device_id,
|
||||
devices[1].device_id,
|
||||
devices[2].device_id,
|
||||
devices[3].device_id,
|
||||
]
|
||||
event = event_factory(
|
||||
devices[3].device_id,
|
||||
capability="lock",
|
||||
attribute="lock",
|
||||
value="locked",
|
||||
data={"codeId": "1"},
|
||||
)
|
||||
request = event_request_factory(device_ids=device_ids, events=[event])
|
||||
config_entry.add_to_hass(hass)
|
||||
hass.config_entries.async_update_entry(
|
||||
config_entry,
|
||||
data={
|
||||
**config_entry.data,
|
||||
CONF_INSTALLED_APP_ID: request.installed_app_id,
|
||||
},
|
||||
)
|
||||
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, config_entry, Mock(), Mock(), devices, [])
|
||||
broker.connect()
|
||||
|
||||
await broker._event_handler(request, None, None)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert called
|
||||
for device in devices:
|
||||
assert device.status.values["Updated"] == "Value"
|
||||
assert devices[3].status.attributes["lock"].value == "locked"
|
||||
assert devices[3].status.attributes["lock"].data == {"codeId": "1"}
|
||||
|
||||
broker.disconnect()
|
||||
|
||||
|
||||
async def test_event_handler_ignores_other_installed_app(
|
||||
hass: HomeAssistant, config_entry, device_factory, event_request_factory
|
||||
) -> None:
|
||||
"""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, config_entry, Mock(), Mock(), [device], [])
|
||||
broker.connect()
|
||||
|
||||
await broker._event_handler(request, None, None)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert not called
|
||||
|
||||
broker.disconnect()
|
||||
|
||||
|
||||
async def test_event_handler_fires_button_events(
|
||||
hass: HomeAssistant,
|
||||
config_entry,
|
||||
device_factory,
|
||||
event_factory,
|
||||
event_request_factory,
|
||||
) -> None:
|
||||
"""Test the event handler fires button events."""
|
||||
device = device_factory("Button 1", ["button"])
|
||||
event = event_factory(
|
||||
device.device_id, capability="button", attribute="button", value="pushed"
|
||||
)
|
||||
request = event_request_factory(events=[event])
|
||||
config_entry.add_to_hass(hass)
|
||||
hass.config_entries.async_update_entry(
|
||||
config_entry,
|
||||
data={
|
||||
**config_entry.data,
|
||||
CONF_INSTALLED_APP_ID: request.installed_app_id,
|
||||
},
|
||||
)
|
||||
called = False
|
||||
|
||||
def handler(evt):
|
||||
nonlocal called
|
||||
called = True
|
||||
assert evt.data == {
|
||||
"component_id": "main",
|
||||
"device_id": device.device_id,
|
||||
"location_id": event.location_id,
|
||||
"value": "pushed",
|
||||
"name": device.label,
|
||||
"data": None,
|
||||
}
|
||||
|
||||
hass.bus.async_listen(EVENT_BUTTON, handler)
|
||||
broker = smartthings.DeviceBroker(hass, config_entry, Mock(), Mock(), [device], [])
|
||||
broker.connect()
|
||||
|
||||
await broker._event_handler(request, None, None)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert called
|
||||
|
||||
broker.disconnect()
|
||||
342
home-assistant/tests/components/smartthings/test_light.py
Normal file
342
home-assistant/tests/components/smartthings/test_light.py
Normal file
@@ -0,0 +1,342 @@
|
||||
"""Test for the SmartThings light 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
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.light import (
|
||||
ATTR_BRIGHTNESS,
|
||||
ATTR_COLOR_TEMP_KELVIN,
|
||||
ATTR_HS_COLOR,
|
||||
ATTR_SUPPORTED_COLOR_MODES,
|
||||
ATTR_TRANSITION,
|
||||
DOMAIN as LIGHT_DOMAIN,
|
||||
ColorMode,
|
||||
LightEntityFeature,
|
||||
)
|
||||
from homeassistant.components.smartthings.const import DOMAIN, SIGNAL_SMARTTHINGS_UPDATE
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.const import (
|
||||
ATTR_ENTITY_ID,
|
||||
ATTR_SUPPORTED_FEATURES,
|
||||
STATE_UNAVAILABLE,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
||||
from homeassistant.helpers.dispatcher import async_dispatcher_send
|
||||
|
||||
from .conftest import setup_platform
|
||||
|
||||
|
||||
@pytest.fixture(name="light_devices")
|
||||
def light_devices_fixture(device_factory):
|
||||
"""Fixture returns a set of mock light devices."""
|
||||
return [
|
||||
device_factory(
|
||||
"Dimmer 1",
|
||||
capabilities=[Capability.switch, Capability.switch_level],
|
||||
status={Attribute.switch: "on", Attribute.level: 100},
|
||||
),
|
||||
device_factory(
|
||||
"Color Dimmer 1",
|
||||
capabilities=[
|
||||
Capability.switch,
|
||||
Capability.switch_level,
|
||||
Capability.color_control,
|
||||
],
|
||||
status={
|
||||
Attribute.switch: "off",
|
||||
Attribute.level: 0,
|
||||
Attribute.hue: 76.0,
|
||||
Attribute.saturation: 55.0,
|
||||
},
|
||||
),
|
||||
device_factory(
|
||||
"Color Dimmer 2",
|
||||
capabilities=[
|
||||
Capability.switch,
|
||||
Capability.switch_level,
|
||||
Capability.color_control,
|
||||
Capability.color_temperature,
|
||||
],
|
||||
status={
|
||||
Attribute.switch: "on",
|
||||
Attribute.level: 100,
|
||||
Attribute.hue: 76.0,
|
||||
Attribute.saturation: 0.0,
|
||||
Attribute.color_temperature: 4500,
|
||||
},
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
async def test_entity_state(hass: HomeAssistant, light_devices) -> None:
|
||||
"""Tests the state attributes properly match the light types."""
|
||||
await setup_platform(hass, LIGHT_DOMAIN, devices=light_devices)
|
||||
|
||||
# Dimmer 1
|
||||
state = hass.states.get("light.dimmer_1")
|
||||
assert state.state == "on"
|
||||
assert state.attributes[ATTR_SUPPORTED_COLOR_MODES] == [ColorMode.BRIGHTNESS]
|
||||
assert state.attributes[ATTR_SUPPORTED_FEATURES] == LightEntityFeature.TRANSITION
|
||||
assert isinstance(state.attributes[ATTR_BRIGHTNESS], int)
|
||||
assert state.attributes[ATTR_BRIGHTNESS] == 255
|
||||
|
||||
# Color Dimmer 1
|
||||
state = hass.states.get("light.color_dimmer_1")
|
||||
assert state.state == "off"
|
||||
assert state.attributes[ATTR_SUPPORTED_COLOR_MODES] == [ColorMode.HS]
|
||||
assert state.attributes[ATTR_SUPPORTED_FEATURES] == LightEntityFeature.TRANSITION
|
||||
|
||||
# Color Dimmer 2
|
||||
state = hass.states.get("light.color_dimmer_2")
|
||||
assert state.state == "on"
|
||||
assert state.attributes[ATTR_SUPPORTED_COLOR_MODES] == [
|
||||
ColorMode.COLOR_TEMP,
|
||||
ColorMode.HS,
|
||||
]
|
||||
assert state.attributes[ATTR_SUPPORTED_FEATURES] == LightEntityFeature.TRANSITION
|
||||
assert state.attributes[ATTR_BRIGHTNESS] == 255
|
||||
assert ATTR_HS_COLOR not in state.attributes[ATTR_HS_COLOR]
|
||||
assert isinstance(state.attributes[ATTR_COLOR_TEMP_KELVIN], int)
|
||||
assert state.attributes[ATTR_COLOR_TEMP_KELVIN] == 4500
|
||||
|
||||
|
||||
async def test_entity_and_device_attributes(
|
||||
hass: HomeAssistant,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
entity_registry: er.EntityRegistry,
|
||||
device_factory,
|
||||
) -> None:
|
||||
"""Test the attributes of the entity are correct."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Light 1",
|
||||
[Capability.switch, Capability.switch_level],
|
||||
{
|
||||
Attribute.mnmo: "123",
|
||||
Attribute.mnmn: "Generic manufacturer",
|
||||
Attribute.mnhw: "v4.56",
|
||||
Attribute.mnfv: "v7.89",
|
||||
},
|
||||
)
|
||||
# Act
|
||||
await setup_platform(hass, LIGHT_DOMAIN, devices=[device])
|
||||
# Assert
|
||||
entry = entity_registry.async_get("light.light_1")
|
||||
assert entry
|
||||
assert entry.unique_id == device.device_id
|
||||
|
||||
entry = device_registry.async_get_device(identifiers={(DOMAIN, device.device_id)})
|
||||
assert entry
|
||||
assert entry.configuration_url == "https://account.smartthings.com"
|
||||
assert entry.identifiers == {(DOMAIN, device.device_id)}
|
||||
assert entry.name == device.label
|
||||
assert entry.model == "123"
|
||||
assert entry.manufacturer == "Generic manufacturer"
|
||||
assert entry.hw_version == "v4.56"
|
||||
assert entry.sw_version == "v7.89"
|
||||
|
||||
|
||||
async def test_turn_off(hass: HomeAssistant, light_devices) -> None:
|
||||
"""Test the light turns of successfully."""
|
||||
# Arrange
|
||||
await setup_platform(hass, LIGHT_DOMAIN, devices=light_devices)
|
||||
# Act
|
||||
await hass.services.async_call(
|
||||
"light", "turn_off", {"entity_id": "light.color_dimmer_2"}, blocking=True
|
||||
)
|
||||
# This test schedules and update right after the call
|
||||
await hass.async_block_till_done()
|
||||
# Assert
|
||||
state = hass.states.get("light.color_dimmer_2")
|
||||
assert state is not None
|
||||
assert state.state == "off"
|
||||
|
||||
|
||||
async def test_turn_off_with_transition(hass: HomeAssistant, light_devices) -> None:
|
||||
"""Test the light turns of successfully with transition."""
|
||||
# Arrange
|
||||
await setup_platform(hass, LIGHT_DOMAIN, devices=light_devices)
|
||||
# Act
|
||||
await hass.services.async_call(
|
||||
"light",
|
||||
"turn_off",
|
||||
{ATTR_ENTITY_ID: "light.color_dimmer_2", ATTR_TRANSITION: 2},
|
||||
blocking=True,
|
||||
)
|
||||
# This test schedules and update right after the call
|
||||
await hass.async_block_till_done()
|
||||
# Assert
|
||||
state = hass.states.get("light.color_dimmer_2")
|
||||
assert state is not None
|
||||
assert state.state == "off"
|
||||
|
||||
|
||||
async def test_turn_on(hass: HomeAssistant, light_devices) -> None:
|
||||
"""Test the light turns of successfully."""
|
||||
# Arrange
|
||||
await setup_platform(hass, LIGHT_DOMAIN, devices=light_devices)
|
||||
# Act
|
||||
await hass.services.async_call(
|
||||
"light", "turn_on", {ATTR_ENTITY_ID: "light.color_dimmer_1"}, blocking=True
|
||||
)
|
||||
# This test schedules and update right after the call
|
||||
await hass.async_block_till_done()
|
||||
# Assert
|
||||
state = hass.states.get("light.color_dimmer_1")
|
||||
assert state is not None
|
||||
assert state.state == "on"
|
||||
|
||||
|
||||
async def test_turn_on_with_brightness(hass: HomeAssistant, light_devices) -> None:
|
||||
"""Test the light turns on to the specified brightness."""
|
||||
# Arrange
|
||||
await setup_platform(hass, LIGHT_DOMAIN, devices=light_devices)
|
||||
# Act
|
||||
await hass.services.async_call(
|
||||
"light",
|
||||
"turn_on",
|
||||
{
|
||||
ATTR_ENTITY_ID: "light.color_dimmer_1",
|
||||
ATTR_BRIGHTNESS: 75,
|
||||
ATTR_TRANSITION: 2,
|
||||
},
|
||||
blocking=True,
|
||||
)
|
||||
# This test schedules and update right after the call
|
||||
await hass.async_block_till_done()
|
||||
# Assert
|
||||
state = hass.states.get("light.color_dimmer_1")
|
||||
assert state is not None
|
||||
assert state.state == "on"
|
||||
# round-trip rounding error (expected)
|
||||
assert state.attributes[ATTR_BRIGHTNESS] == 74
|
||||
|
||||
|
||||
async def test_turn_on_with_minimal_brightness(
|
||||
hass: HomeAssistant, light_devices
|
||||
) -> None:
|
||||
"""Test lights set to lowest brightness when converted scale would be zero.
|
||||
|
||||
SmartThings light brightness is a percentage (0-100), but Home Assistant uses a
|
||||
0-255 scale. This tests if a really low value (1-2) is passed, we don't
|
||||
set the level to zero, which turns off the lights in SmartThings.
|
||||
"""
|
||||
# Arrange
|
||||
await setup_platform(hass, LIGHT_DOMAIN, devices=light_devices)
|
||||
# Act
|
||||
await hass.services.async_call(
|
||||
"light",
|
||||
"turn_on",
|
||||
{ATTR_ENTITY_ID: "light.color_dimmer_1", ATTR_BRIGHTNESS: 2},
|
||||
blocking=True,
|
||||
)
|
||||
# This test schedules and update right after the call
|
||||
await hass.async_block_till_done()
|
||||
# Assert
|
||||
state = hass.states.get("light.color_dimmer_1")
|
||||
assert state is not None
|
||||
assert state.state == "on"
|
||||
# round-trip rounding error (expected)
|
||||
assert state.attributes[ATTR_BRIGHTNESS] == 3
|
||||
|
||||
|
||||
async def test_turn_on_with_color(hass: HomeAssistant, light_devices) -> None:
|
||||
"""Test the light turns on with color."""
|
||||
# Arrange
|
||||
await setup_platform(hass, LIGHT_DOMAIN, devices=light_devices)
|
||||
# Act
|
||||
await hass.services.async_call(
|
||||
"light",
|
||||
"turn_on",
|
||||
{ATTR_ENTITY_ID: "light.color_dimmer_2", ATTR_HS_COLOR: (180, 50)},
|
||||
blocking=True,
|
||||
)
|
||||
# This test schedules and update right after the call
|
||||
await hass.async_block_till_done()
|
||||
# Assert
|
||||
state = hass.states.get("light.color_dimmer_2")
|
||||
assert state is not None
|
||||
assert state.state == "on"
|
||||
assert state.attributes[ATTR_HS_COLOR] == (180, 50)
|
||||
|
||||
|
||||
async def test_turn_on_with_color_temp(hass: HomeAssistant, light_devices) -> None:
|
||||
"""Test the light turns on with color temp."""
|
||||
# Arrange
|
||||
await setup_platform(hass, LIGHT_DOMAIN, devices=light_devices)
|
||||
# Act
|
||||
await hass.services.async_call(
|
||||
"light",
|
||||
"turn_on",
|
||||
{ATTR_ENTITY_ID: "light.color_dimmer_2", ATTR_COLOR_TEMP_KELVIN: 3333},
|
||||
blocking=True,
|
||||
)
|
||||
# This test schedules and update right after the call
|
||||
await hass.async_block_till_done()
|
||||
# Assert
|
||||
state = hass.states.get("light.color_dimmer_2")
|
||||
assert state is not None
|
||||
assert state.state == "on"
|
||||
assert state.attributes[ATTR_COLOR_TEMP_KELVIN] == 3333
|
||||
|
||||
|
||||
async def test_update_from_signal(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Test the light updates when receiving a signal."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Color Dimmer 2",
|
||||
capabilities=[
|
||||
Capability.switch,
|
||||
Capability.switch_level,
|
||||
Capability.color_control,
|
||||
Capability.color_temperature,
|
||||
],
|
||||
status={
|
||||
Attribute.switch: "off",
|
||||
Attribute.level: 100,
|
||||
Attribute.hue: 76.0,
|
||||
Attribute.saturation: 55.0,
|
||||
Attribute.color_temperature: 4500,
|
||||
},
|
||||
)
|
||||
await setup_platform(hass, LIGHT_DOMAIN, devices=[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("light.color_dimmer_2")
|
||||
assert state is not None
|
||||
assert state.state == "on"
|
||||
|
||||
|
||||
async def test_unload_config_entry(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Test the light is removed when the config entry is unloaded."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Color Dimmer 2",
|
||||
capabilities=[
|
||||
Capability.switch,
|
||||
Capability.switch_level,
|
||||
Capability.color_control,
|
||||
Capability.color_temperature,
|
||||
],
|
||||
status={
|
||||
Attribute.switch: "off",
|
||||
Attribute.level: 100,
|
||||
Attribute.hue: 76.0,
|
||||
Attribute.saturation: 55.0,
|
||||
Attribute.color_temperature: 4500,
|
||||
},
|
||||
)
|
||||
config_entry = await setup_platform(hass, LIGHT_DOMAIN, devices=[device])
|
||||
config_entry.mock_state(hass, ConfigEntryState.LOADED)
|
||||
# Act
|
||||
await hass.config_entries.async_forward_entry_unload(config_entry, "light")
|
||||
# Assert
|
||||
assert hass.states.get("light.color_dimmer_2").state == STATE_UNAVAILABLE
|
||||
129
home-assistant/tests/components/smartthings/test_lock.py
Normal file
129
home-assistant/tests/components/smartthings/test_lock.py
Normal file
@@ -0,0 +1,129 @@
|
||||
"""Test for the SmartThings lock 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 pysmartthings.device import Status
|
||||
|
||||
from homeassistant.components.lock import DOMAIN as LOCK_DOMAIN
|
||||
from homeassistant.components.smartthings.const import DOMAIN, SIGNAL_SMARTTHINGS_UPDATE
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.const import STATE_UNAVAILABLE
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
||||
from homeassistant.helpers.dispatcher import async_dispatcher_send
|
||||
|
||||
from .conftest import setup_platform
|
||||
|
||||
|
||||
async def test_entity_and_device_attributes(
|
||||
hass: HomeAssistant,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
entity_registry: er.EntityRegistry,
|
||||
device_factory,
|
||||
) -> None:
|
||||
"""Test the attributes of the entity are correct."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Lock_1",
|
||||
[Capability.lock],
|
||||
{
|
||||
Attribute.lock: "unlocked",
|
||||
Attribute.mnmo: "123",
|
||||
Attribute.mnmn: "Generic manufacturer",
|
||||
Attribute.mnhw: "v4.56",
|
||||
Attribute.mnfv: "v7.89",
|
||||
},
|
||||
)
|
||||
# Act
|
||||
await setup_platform(hass, LOCK_DOMAIN, devices=[device])
|
||||
# Assert
|
||||
entry = entity_registry.async_get("lock.lock_1")
|
||||
assert entry
|
||||
assert entry.unique_id == device.device_id
|
||||
|
||||
entry = device_registry.async_get_device(identifiers={(DOMAIN, device.device_id)})
|
||||
assert entry
|
||||
assert entry.configuration_url == "https://account.smartthings.com"
|
||||
assert entry.identifiers == {(DOMAIN, device.device_id)}
|
||||
assert entry.name == device.label
|
||||
assert entry.model == "123"
|
||||
assert entry.manufacturer == "Generic manufacturer"
|
||||
assert entry.hw_version == "v4.56"
|
||||
assert entry.sw_version == "v7.89"
|
||||
|
||||
|
||||
async def test_lock(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Test the lock locks successfully."""
|
||||
# Arrange
|
||||
device = device_factory("Lock_1", [Capability.lock])
|
||||
device.status.attributes[Attribute.lock] = Status(
|
||||
"unlocked",
|
||||
None,
|
||||
{
|
||||
"method": "Manual",
|
||||
"codeId": None,
|
||||
"codeName": "Code 1",
|
||||
"lockName": "Front Door",
|
||||
"usedCode": "Code 2",
|
||||
},
|
||||
)
|
||||
await setup_platform(hass, LOCK_DOMAIN, devices=[device])
|
||||
# Act
|
||||
await hass.services.async_call(
|
||||
LOCK_DOMAIN, "lock", {"entity_id": "lock.lock_1"}, blocking=True
|
||||
)
|
||||
# Assert
|
||||
state = hass.states.get("lock.lock_1")
|
||||
assert state is not None
|
||||
assert state.state == "locked"
|
||||
assert state.attributes["method"] == "Manual"
|
||||
assert state.attributes["lock_state"] == "locked"
|
||||
assert state.attributes["code_name"] == "Code 1"
|
||||
assert state.attributes["used_code"] == "Code 2"
|
||||
assert state.attributes["lock_name"] == "Front Door"
|
||||
assert "code_id" not in state.attributes
|
||||
|
||||
|
||||
async def test_unlock(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Test the lock unlocks successfully."""
|
||||
# Arrange
|
||||
device = device_factory("Lock_1", [Capability.lock], {Attribute.lock: "locked"})
|
||||
await setup_platform(hass, LOCK_DOMAIN, devices=[device])
|
||||
# Act
|
||||
await hass.services.async_call(
|
||||
LOCK_DOMAIN, "unlock", {"entity_id": "lock.lock_1"}, blocking=True
|
||||
)
|
||||
# Assert
|
||||
state = hass.states.get("lock.lock_1")
|
||||
assert state is not None
|
||||
assert state.state == "unlocked"
|
||||
|
||||
|
||||
async def test_update_from_signal(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Test the lock updates when receiving a signal."""
|
||||
# Arrange
|
||||
device = device_factory("Lock_1", [Capability.lock], {Attribute.lock: "unlocked"})
|
||||
await setup_platform(hass, LOCK_DOMAIN, devices=[device])
|
||||
await device.lock(True)
|
||||
# Act
|
||||
async_dispatcher_send(hass, SIGNAL_SMARTTHINGS_UPDATE, [device.device_id])
|
||||
# Assert
|
||||
await hass.async_block_till_done()
|
||||
state = hass.states.get("lock.lock_1")
|
||||
assert state is not None
|
||||
assert state.state == "locked"
|
||||
|
||||
|
||||
async def test_unload_config_entry(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Test the lock is removed when the config entry is unloaded."""
|
||||
# Arrange
|
||||
device = device_factory("Lock_1", [Capability.lock], {Attribute.lock: "locked"})
|
||||
config_entry = await setup_platform(hass, LOCK_DOMAIN, devices=[device])
|
||||
config_entry.mock_state(hass, ConfigEntryState.LOADED)
|
||||
# Act
|
||||
await hass.config_entries.async_forward_entry_unload(config_entry, "lock")
|
||||
# Assert
|
||||
assert hass.states.get("lock.lock_1").state == STATE_UNAVAILABLE
|
||||
52
home-assistant/tests/components/smartthings/test_scene.py
Normal file
52
home-assistant/tests/components/smartthings/test_scene.py
Normal file
@@ -0,0 +1,52 @@
|
||||
"""Test for the SmartThings scene platform.
|
||||
|
||||
The only mocking required is of the underlying SmartThings API object so
|
||||
real HTTP calls are not initiated during testing.
|
||||
"""
|
||||
|
||||
from homeassistant.components.scene import DOMAIN as SCENE_DOMAIN
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TURN_ON, STATE_UNAVAILABLE
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
|
||||
from .conftest import setup_platform
|
||||
|
||||
|
||||
async def test_entity_and_device_attributes(
|
||||
hass: HomeAssistant, entity_registry: er.EntityRegistry, scene
|
||||
) -> None:
|
||||
"""Test the attributes of the entity are correct."""
|
||||
# Act
|
||||
await setup_platform(hass, SCENE_DOMAIN, scenes=[scene])
|
||||
# Assert
|
||||
entry = entity_registry.async_get("scene.test_scene")
|
||||
assert entry
|
||||
assert entry.unique_id == scene.scene_id
|
||||
|
||||
|
||||
async def test_scene_activate(hass: HomeAssistant, scene) -> None:
|
||||
"""Test the scene is activated."""
|
||||
await setup_platform(hass, SCENE_DOMAIN, scenes=[scene])
|
||||
await hass.services.async_call(
|
||||
SCENE_DOMAIN,
|
||||
SERVICE_TURN_ON,
|
||||
{ATTR_ENTITY_ID: "scene.test_scene"},
|
||||
blocking=True,
|
||||
)
|
||||
state = hass.states.get("scene.test_scene")
|
||||
assert state.attributes["icon"] == scene.icon
|
||||
assert state.attributes["color"] == scene.color
|
||||
assert state.attributes["location_id"] == scene.location_id
|
||||
assert scene.execute.call_count == 1
|
||||
|
||||
|
||||
async def test_unload_config_entry(hass: HomeAssistant, scene) -> None:
|
||||
"""Test the scene is removed when the config entry is unloaded."""
|
||||
# Arrange
|
||||
config_entry = await setup_platform(hass, SCENE_DOMAIN, scenes=[scene])
|
||||
config_entry.mock_state(hass, ConfigEntryState.LOADED)
|
||||
# Act
|
||||
await hass.config_entries.async_forward_entry_unload(config_entry, SCENE_DOMAIN)
|
||||
# Assert
|
||||
assert hass.states.get("scene.test_scene").state == STATE_UNAVAILABLE
|
||||
307
home-assistant/tests/components/smartthings/test_sensor.py
Normal file
307
home-assistant/tests/components/smartthings/test_sensor.py
Normal file
@@ -0,0 +1,307 @@
|
||||
"""Test for the SmartThings sensors platform.
|
||||
|
||||
The only mocking required is of the underlying SmartThings API object so
|
||||
real HTTP calls are not initiated during testing.
|
||||
"""
|
||||
|
||||
from pysmartthings import ATTRIBUTES, CAPABILITIES, Attribute, Capability
|
||||
|
||||
from homeassistant.components.sensor import (
|
||||
DEVICE_CLASSES,
|
||||
DOMAIN as SENSOR_DOMAIN,
|
||||
STATE_CLASSES,
|
||||
)
|
||||
from homeassistant.components.smartthings import sensor
|
||||
from homeassistant.components.smartthings.const import DOMAIN, SIGNAL_SMARTTHINGS_UPDATE
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.const import (
|
||||
ATTR_FRIENDLY_NAME,
|
||||
ATTR_UNIT_OF_MEASUREMENT,
|
||||
PERCENTAGE,
|
||||
STATE_UNAVAILABLE,
|
||||
STATE_UNKNOWN,
|
||||
EntityCategory,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
||||
from homeassistant.helpers.dispatcher import async_dispatcher_send
|
||||
|
||||
from .conftest import setup_platform
|
||||
|
||||
|
||||
async def test_mapping_integrity() -> None:
|
||||
"""Test ensures the map dicts have proper integrity."""
|
||||
for capability, maps in sensor.CAPABILITY_TO_SENSORS.items():
|
||||
assert capability in CAPABILITIES, capability
|
||||
for sensor_map in maps:
|
||||
assert sensor_map.attribute in ATTRIBUTES, sensor_map.attribute
|
||||
if sensor_map.device_class:
|
||||
assert (
|
||||
sensor_map.device_class in DEVICE_CLASSES
|
||||
), sensor_map.device_class
|
||||
if sensor_map.state_class:
|
||||
assert sensor_map.state_class in STATE_CLASSES, sensor_map.state_class
|
||||
|
||||
|
||||
async def test_entity_state(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Tests the state attributes properly match the sensor types."""
|
||||
device = device_factory("Sensor 1", [Capability.battery], {Attribute.battery: 100})
|
||||
await setup_platform(hass, SENSOR_DOMAIN, devices=[device])
|
||||
state = hass.states.get("sensor.sensor_1_battery")
|
||||
assert state.state == "100"
|
||||
assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == PERCENTAGE
|
||||
assert state.attributes[ATTR_FRIENDLY_NAME] == f"{device.label} Battery"
|
||||
|
||||
|
||||
async def test_entity_three_axis_state(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Tests the state attributes properly match the three axis types."""
|
||||
device = device_factory(
|
||||
"Three Axis", [Capability.three_axis], {Attribute.three_axis: [100, 75, 25]}
|
||||
)
|
||||
await setup_platform(hass, SENSOR_DOMAIN, devices=[device])
|
||||
state = hass.states.get("sensor.three_axis_x_coordinate")
|
||||
assert state.state == "100"
|
||||
assert state.attributes[ATTR_FRIENDLY_NAME] == f"{device.label} X Coordinate"
|
||||
state = hass.states.get("sensor.three_axis_y_coordinate")
|
||||
assert state.state == "75"
|
||||
assert state.attributes[ATTR_FRIENDLY_NAME] == f"{device.label} Y Coordinate"
|
||||
state = hass.states.get("sensor.three_axis_z_coordinate")
|
||||
assert state.state == "25"
|
||||
assert state.attributes[ATTR_FRIENDLY_NAME] == f"{device.label} Z Coordinate"
|
||||
|
||||
|
||||
async def test_entity_three_axis_invalid_state(
|
||||
hass: HomeAssistant, device_factory
|
||||
) -> None:
|
||||
"""Tests the state attributes properly match the three axis types."""
|
||||
device = device_factory(
|
||||
"Three Axis", [Capability.three_axis], {Attribute.three_axis: []}
|
||||
)
|
||||
await setup_platform(hass, SENSOR_DOMAIN, devices=[device])
|
||||
state = hass.states.get("sensor.three_axis_x_coordinate")
|
||||
assert state.state == STATE_UNKNOWN
|
||||
state = hass.states.get("sensor.three_axis_y_coordinate")
|
||||
assert state.state == STATE_UNKNOWN
|
||||
state = hass.states.get("sensor.three_axis_z_coordinate")
|
||||
assert state.state == STATE_UNKNOWN
|
||||
|
||||
|
||||
async def test_entity_and_device_attributes(
|
||||
hass: HomeAssistant,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
entity_registry: er.EntityRegistry,
|
||||
device_factory,
|
||||
) -> None:
|
||||
"""Test the attributes of the entity are correct."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Sensor 1",
|
||||
[Capability.battery],
|
||||
{
|
||||
Attribute.battery: 100,
|
||||
Attribute.mnmo: "123",
|
||||
Attribute.mnmn: "Generic manufacturer",
|
||||
Attribute.mnhw: "v4.56",
|
||||
Attribute.mnfv: "v7.89",
|
||||
},
|
||||
)
|
||||
# Act
|
||||
await setup_platform(hass, SENSOR_DOMAIN, devices=[device])
|
||||
# Assert
|
||||
entry = entity_registry.async_get("sensor.sensor_1_battery")
|
||||
assert entry
|
||||
assert entry.unique_id == f"{device.device_id}.{Attribute.battery}"
|
||||
assert entry.entity_category is EntityCategory.DIAGNOSTIC
|
||||
entry = device_registry.async_get_device(identifiers={(DOMAIN, device.device_id)})
|
||||
assert entry
|
||||
assert entry.configuration_url == "https://account.smartthings.com"
|
||||
assert entry.identifiers == {(DOMAIN, device.device_id)}
|
||||
assert entry.name == device.label
|
||||
assert entry.model == "123"
|
||||
assert entry.manufacturer == "Generic manufacturer"
|
||||
assert entry.hw_version == "v4.56"
|
||||
assert entry.sw_version == "v7.89"
|
||||
|
||||
|
||||
async def test_energy_sensors_for_switch_device(
|
||||
hass: HomeAssistant,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
entity_registry: er.EntityRegistry,
|
||||
device_factory,
|
||||
) -> None:
|
||||
"""Test the attributes of the entity are correct."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Switch_1",
|
||||
[Capability.switch, Capability.power_meter, Capability.energy_meter],
|
||||
{
|
||||
Attribute.switch: "off",
|
||||
Attribute.power: 355,
|
||||
Attribute.energy: 11.422,
|
||||
Attribute.mnmo: "123",
|
||||
Attribute.mnmn: "Generic manufacturer",
|
||||
Attribute.mnhw: "v4.56",
|
||||
Attribute.mnfv: "v7.89",
|
||||
},
|
||||
)
|
||||
# Act
|
||||
await setup_platform(hass, SENSOR_DOMAIN, devices=[device])
|
||||
# Assert
|
||||
state = hass.states.get("sensor.switch_1_energy_meter")
|
||||
assert state
|
||||
assert state.state == "11.422"
|
||||
entry = entity_registry.async_get("sensor.switch_1_energy_meter")
|
||||
assert entry
|
||||
assert entry.unique_id == f"{device.device_id}.{Attribute.energy}"
|
||||
assert entry.entity_category is None
|
||||
entry = device_registry.async_get_device(identifiers={(DOMAIN, device.device_id)})
|
||||
assert entry
|
||||
assert entry.configuration_url == "https://account.smartthings.com"
|
||||
assert entry.identifiers == {(DOMAIN, device.device_id)}
|
||||
assert entry.name == device.label
|
||||
assert entry.model == "123"
|
||||
assert entry.manufacturer == "Generic manufacturer"
|
||||
assert entry.hw_version == "v4.56"
|
||||
assert entry.sw_version == "v7.89"
|
||||
|
||||
state = hass.states.get("sensor.switch_1_power_meter")
|
||||
assert state
|
||||
assert state.state == "355"
|
||||
entry = entity_registry.async_get("sensor.switch_1_power_meter")
|
||||
assert entry
|
||||
assert entry.unique_id == f"{device.device_id}.{Attribute.power}"
|
||||
assert entry.entity_category is None
|
||||
entry = device_registry.async_get_device(identifiers={(DOMAIN, device.device_id)})
|
||||
assert entry
|
||||
assert entry.configuration_url == "https://account.smartthings.com"
|
||||
assert entry.identifiers == {(DOMAIN, device.device_id)}
|
||||
assert entry.name == device.label
|
||||
assert entry.model == "123"
|
||||
assert entry.manufacturer == "Generic manufacturer"
|
||||
assert entry.hw_version == "v4.56"
|
||||
assert entry.sw_version == "v7.89"
|
||||
|
||||
|
||||
async def test_power_consumption_sensor(
|
||||
hass: HomeAssistant,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
entity_registry: er.EntityRegistry,
|
||||
device_factory,
|
||||
) -> None:
|
||||
"""Test the attributes of the entity are correct."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"refrigerator",
|
||||
[Capability.power_consumption_report],
|
||||
{
|
||||
Attribute.power_consumption: {
|
||||
"energy": 1412002,
|
||||
"deltaEnergy": 25,
|
||||
"power": 109,
|
||||
"powerEnergy": 24.304498331745464,
|
||||
"persistedEnergy": 0,
|
||||
"energySaved": 0,
|
||||
"start": "2021-07-30T16:45:25Z",
|
||||
"end": "2021-07-30T16:58:33Z",
|
||||
},
|
||||
Attribute.mnmo: "123",
|
||||
Attribute.mnmn: "Generic manufacturer",
|
||||
Attribute.mnhw: "v4.56",
|
||||
Attribute.mnfv: "v7.89",
|
||||
},
|
||||
)
|
||||
# Act
|
||||
await setup_platform(hass, SENSOR_DOMAIN, devices=[device])
|
||||
# Assert
|
||||
state = hass.states.get("sensor.refrigerator_energy")
|
||||
assert state
|
||||
assert state.state == "1412.002"
|
||||
entry = entity_registry.async_get("sensor.refrigerator_energy")
|
||||
assert entry
|
||||
assert entry.unique_id == f"{device.device_id}.energy_meter"
|
||||
entry = device_registry.async_get_device(identifiers={(DOMAIN, device.device_id)})
|
||||
assert entry
|
||||
assert entry.configuration_url == "https://account.smartthings.com"
|
||||
assert entry.identifiers == {(DOMAIN, device.device_id)}
|
||||
assert entry.name == device.label
|
||||
assert entry.model == "123"
|
||||
assert entry.manufacturer == "Generic manufacturer"
|
||||
assert entry.hw_version == "v4.56"
|
||||
assert entry.sw_version == "v7.89"
|
||||
|
||||
state = hass.states.get("sensor.refrigerator_power")
|
||||
assert state
|
||||
assert state.state == "109"
|
||||
assert state.attributes["power_consumption_start"] == "2021-07-30T16:45:25Z"
|
||||
assert state.attributes["power_consumption_end"] == "2021-07-30T16:58:33Z"
|
||||
entry = entity_registry.async_get("sensor.refrigerator_power")
|
||||
assert entry
|
||||
assert entry.unique_id == f"{device.device_id}.power_meter"
|
||||
entry = device_registry.async_get_device(identifiers={(DOMAIN, device.device_id)})
|
||||
assert entry
|
||||
assert entry.configuration_url == "https://account.smartthings.com"
|
||||
assert entry.identifiers == {(DOMAIN, device.device_id)}
|
||||
assert entry.name == device.label
|
||||
assert entry.model == "123"
|
||||
assert entry.manufacturer == "Generic manufacturer"
|
||||
assert entry.hw_version == "v4.56"
|
||||
assert entry.sw_version == "v7.89"
|
||||
|
||||
device = device_factory(
|
||||
"vacuum",
|
||||
[Capability.power_consumption_report],
|
||||
{
|
||||
Attribute.power_consumption: {},
|
||||
Attribute.mnmo: "123",
|
||||
Attribute.mnmn: "Generic manufacturer",
|
||||
Attribute.mnhw: "v4.56",
|
||||
Attribute.mnfv: "v7.89",
|
||||
},
|
||||
)
|
||||
# Act
|
||||
await setup_platform(hass, SENSOR_DOMAIN, devices=[device])
|
||||
# Assert
|
||||
state = hass.states.get("sensor.vacuum_energy")
|
||||
assert state
|
||||
assert state.state == "unknown"
|
||||
entry = entity_registry.async_get("sensor.vacuum_energy")
|
||||
assert entry
|
||||
assert entry.unique_id == f"{device.device_id}.energy_meter"
|
||||
entry = device_registry.async_get_device(identifiers={(DOMAIN, device.device_id)})
|
||||
assert entry
|
||||
assert entry.configuration_url == "https://account.smartthings.com"
|
||||
assert entry.identifiers == {(DOMAIN, device.device_id)}
|
||||
assert entry.name == device.label
|
||||
assert entry.model == "123"
|
||||
assert entry.manufacturer == "Generic manufacturer"
|
||||
assert entry.hw_version == "v4.56"
|
||||
assert entry.sw_version == "v7.89"
|
||||
|
||||
|
||||
async def test_update_from_signal(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Test the binary_sensor updates when receiving a signal."""
|
||||
# Arrange
|
||||
device = device_factory("Sensor 1", [Capability.battery], {Attribute.battery: 100})
|
||||
await setup_platform(hass, SENSOR_DOMAIN, devices=[device])
|
||||
device.status.apply_attribute_update(
|
||||
"main", Capability.battery, Attribute.battery, 75
|
||||
)
|
||||
# Act
|
||||
async_dispatcher_send(hass, SIGNAL_SMARTTHINGS_UPDATE, [device.device_id])
|
||||
# Assert
|
||||
await hass.async_block_till_done()
|
||||
state = hass.states.get("sensor.sensor_1_battery")
|
||||
assert state is not None
|
||||
assert state.state == "75"
|
||||
|
||||
|
||||
async def test_unload_config_entry(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Test the binary_sensor is removed when the config entry is unloaded."""
|
||||
# Arrange
|
||||
device = device_factory("Sensor 1", [Capability.battery], {Attribute.battery: 100})
|
||||
config_entry = await setup_platform(hass, SENSOR_DOMAIN, devices=[device])
|
||||
config_entry.mock_state(hass, ConfigEntryState.LOADED)
|
||||
# Act
|
||||
await hass.config_entries.async_forward_entry_unload(config_entry, "sensor")
|
||||
# Assert
|
||||
assert hass.states.get("sensor.sensor_1_battery").state == STATE_UNAVAILABLE
|
||||
186
home-assistant/tests/components/smartthings/test_smartapp.py
Normal file
186
home-assistant/tests/components/smartthings/test_smartapp.py
Normal file
@@ -0,0 +1,186 @@
|
||||
"""Tests for the smartapp module."""
|
||||
|
||||
from unittest.mock import AsyncMock, Mock, patch
|
||||
from uuid import uuid4
|
||||
|
||||
from pysmartthings import CAPABILITIES, AppEntity, Capability
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.smartthings import smartapp
|
||||
from homeassistant.components.smartthings.const import (
|
||||
CONF_REFRESH_TOKEN,
|
||||
DATA_MANAGER,
|
||||
DOMAIN,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
|
||||
async def test_update_app(hass: HomeAssistant, app) -> None:
|
||||
"""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: HomeAssistant, app) -> None:
|
||||
"""Test update_app updates when an app is needed."""
|
||||
mock_app = Mock(AppEntity)
|
||||
mock_app.app_name = "Test"
|
||||
|
||||
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_update_saves_token(
|
||||
hass: HomeAssistant, smartthings_mock, location, device_factory
|
||||
) -> None:
|
||||
"""Test update saves token."""
|
||||
# Arrange
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN, data={"installed_app_id": str(uuid4()), "app_id": str(uuid4())}
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
app = Mock()
|
||||
app.app_id = entry.data["app_id"]
|
||||
request = Mock()
|
||||
request.installed_app_id = entry.data["installed_app_id"]
|
||||
request.auth_token = str(uuid4())
|
||||
request.refresh_token = str(uuid4())
|
||||
request.location_id = location.location_id
|
||||
|
||||
# Act
|
||||
await smartapp.smartapp_update(hass, request, None, app)
|
||||
# Assert
|
||||
assert entry.data[CONF_REFRESH_TOKEN] == request.refresh_token
|
||||
|
||||
|
||||
async def test_smartapp_uninstall(hass: HomeAssistant, config_entry) -> None:
|
||||
"""Test the config entry is unloaded when the app is uninstalled."""
|
||||
config_entry.add_to_hass(hass)
|
||||
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") as remove:
|
||||
await smartapp.smartapp_uninstall(hass, request, None, app)
|
||||
assert remove.call_count == 1
|
||||
|
||||
|
||||
async def test_smartapp_webhook(hass: HomeAssistant) -> None:
|
||||
"""Test the smartapp webhook calls the manager."""
|
||||
manager = Mock()
|
||||
manager.handle_request = AsyncMock(return_value={})
|
||||
hass.data[DOMAIN][DATA_MANAGER] = manager
|
||||
request = Mock()
|
||||
request.headers = []
|
||||
request.json = AsyncMock(return_value={})
|
||||
result = await smartapp.smartapp_webhook(hass, "", request)
|
||||
|
||||
assert result.body == b"{}"
|
||||
|
||||
|
||||
async def test_smartapp_sync_subscriptions(
|
||||
hass: HomeAssistant, smartthings_mock, device_factory, subscription_factory
|
||||
) -> None:
|
||||
"""Test synchronization adds and removes and ignores unused."""
|
||||
smartthings_mock.subscriptions.return_value = [
|
||||
subscription_factory(Capability.thermostat),
|
||||
subscription_factory(Capability.switch),
|
||||
subscription_factory(Capability.switch_level),
|
||||
]
|
||||
devices = [
|
||||
device_factory("", [Capability.battery, "ping"]),
|
||||
device_factory("", [Capability.switch, Capability.switch_level]),
|
||||
device_factory("", [Capability.switch, Capability.execute]),
|
||||
]
|
||||
|
||||
await smartapp.smartapp_sync_subscriptions(
|
||||
hass, str(uuid4()), str(uuid4()), str(uuid4()), devices
|
||||
)
|
||||
|
||||
assert smartthings_mock.subscriptions.call_count == 1
|
||||
assert smartthings_mock.delete_subscription.call_count == 1
|
||||
assert smartthings_mock.create_subscription.call_count == 1
|
||||
|
||||
|
||||
async def test_smartapp_sync_subscriptions_up_to_date(
|
||||
hass: HomeAssistant, smartthings_mock, device_factory, subscription_factory
|
||||
) -> None:
|
||||
"""Test synchronization does nothing when current."""
|
||||
smartthings_mock.subscriptions.return_value = [
|
||||
subscription_factory(Capability.battery),
|
||||
subscription_factory(Capability.switch),
|
||||
subscription_factory(Capability.switch_level),
|
||||
]
|
||||
devices = [
|
||||
device_factory("", [Capability.battery, "ping"]),
|
||||
device_factory("", [Capability.switch, Capability.switch_level]),
|
||||
device_factory("", [Capability.switch]),
|
||||
]
|
||||
|
||||
await smartapp.smartapp_sync_subscriptions(
|
||||
hass, str(uuid4()), str(uuid4()), str(uuid4()), devices
|
||||
)
|
||||
|
||||
assert smartthings_mock.subscriptions.call_count == 1
|
||||
assert smartthings_mock.delete_subscription.call_count == 0
|
||||
assert smartthings_mock.create_subscription.call_count == 0
|
||||
|
||||
|
||||
async def test_smartapp_sync_subscriptions_limit_warning(
|
||||
hass: HomeAssistant,
|
||||
smartthings_mock,
|
||||
device_factory,
|
||||
subscription_factory,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Test synchronization over the limit logs a warning."""
|
||||
smartthings_mock.subscriptions.return_value = []
|
||||
devices = [
|
||||
device_factory("", CAPABILITIES),
|
||||
]
|
||||
|
||||
await smartapp.smartapp_sync_subscriptions(
|
||||
hass, str(uuid4()), str(uuid4()), str(uuid4()), devices
|
||||
)
|
||||
|
||||
assert (
|
||||
"Some device attributes may not receive push updates and there may be "
|
||||
"subscription creation failures" in caplog.text
|
||||
)
|
||||
|
||||
|
||||
async def test_smartapp_sync_subscriptions_handles_exceptions(
|
||||
hass: HomeAssistant, smartthings_mock, device_factory, subscription_factory
|
||||
) -> None:
|
||||
"""Test synchronization does nothing when current."""
|
||||
smartthings_mock.delete_subscription.side_effect = Exception
|
||||
smartthings_mock.create_subscription.side_effect = Exception
|
||||
smartthings_mock.subscriptions.return_value = [
|
||||
subscription_factory(Capability.battery),
|
||||
subscription_factory(Capability.switch),
|
||||
subscription_factory(Capability.switch_level),
|
||||
]
|
||||
devices = [
|
||||
device_factory("", [Capability.thermostat, "ping"]),
|
||||
device_factory("", [Capability.switch, Capability.switch_level]),
|
||||
device_factory("", [Capability.switch]),
|
||||
]
|
||||
|
||||
await smartapp.smartapp_sync_subscriptions(
|
||||
hass, str(uuid4()), str(uuid4()), str(uuid4()), devices
|
||||
)
|
||||
|
||||
assert smartthings_mock.subscriptions.call_count == 1
|
||||
assert smartthings_mock.delete_subscription.call_count == 1
|
||||
assert smartthings_mock.create_subscription.call_count == 1
|
||||
115
home-assistant/tests/components/smartthings/test_switch.py
Normal file
115
home-assistant/tests/components/smartthings/test_switch.py
Normal file
@@ -0,0 +1,115 @@
|
||||
"""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.const import DOMAIN, SIGNAL_SMARTTHINGS_UPDATE
|
||||
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.const import STATE_UNAVAILABLE
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
||||
from homeassistant.helpers.dispatcher import async_dispatcher_send
|
||||
|
||||
from .conftest import setup_platform
|
||||
|
||||
|
||||
async def test_entity_and_device_attributes(
|
||||
hass: HomeAssistant,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
entity_registry: er.EntityRegistry,
|
||||
device_factory,
|
||||
) -> None:
|
||||
"""Test the attributes of the entity are correct."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Switch_1",
|
||||
[Capability.switch],
|
||||
{
|
||||
Attribute.switch: "on",
|
||||
Attribute.mnmo: "123",
|
||||
Attribute.mnmn: "Generic manufacturer",
|
||||
Attribute.mnhw: "v4.56",
|
||||
Attribute.mnfv: "v7.89",
|
||||
},
|
||||
)
|
||||
# Act
|
||||
await setup_platform(hass, SWITCH_DOMAIN, devices=[device])
|
||||
# Assert
|
||||
entry = entity_registry.async_get("switch.switch_1")
|
||||
assert entry
|
||||
assert entry.unique_id == device.device_id
|
||||
|
||||
entry = device_registry.async_get_device(identifiers={(DOMAIN, device.device_id)})
|
||||
assert entry
|
||||
assert entry.configuration_url == "https://account.smartthings.com"
|
||||
assert entry.identifiers == {(DOMAIN, device.device_id)}
|
||||
assert entry.name == device.label
|
||||
assert entry.model == "123"
|
||||
assert entry.manufacturer == "Generic manufacturer"
|
||||
assert entry.hw_version == "v4.56"
|
||||
assert entry.sw_version == "v7.89"
|
||||
|
||||
|
||||
async def test_turn_off(hass: HomeAssistant, device_factory) -> None:
|
||||
"""Test the switch turns of successfully."""
|
||||
# Arrange
|
||||
device = device_factory("Switch_1", [Capability.switch], {Attribute.switch: "on"})
|
||||
await setup_platform(hass, SWITCH_DOMAIN, devices=[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: HomeAssistant, device_factory) -> None:
|
||||
"""Test the switch turns of successfully."""
|
||||
# Arrange
|
||||
device = device_factory(
|
||||
"Switch_1",
|
||||
[Capability.switch, Capability.power_meter, Capability.energy_meter],
|
||||
{Attribute.switch: "off", Attribute.power: 355, Attribute.energy: 11.422},
|
||||
)
|
||||
await setup_platform(hass, SWITCH_DOMAIN, devices=[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: HomeAssistant, device_factory) -> None:
|
||||
"""Test the switch updates when receiving a signal."""
|
||||
# Arrange
|
||||
device = device_factory("Switch_1", [Capability.switch], {Attribute.switch: "off"})
|
||||
await setup_platform(hass, SWITCH_DOMAIN, devices=[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: HomeAssistant, device_factory) -> None:
|
||||
"""Test the switch is removed when the config entry is unloaded."""
|
||||
# Arrange
|
||||
device = device_factory("Switch 1", [Capability.switch], {Attribute.switch: "on"})
|
||||
config_entry = await setup_platform(hass, SWITCH_DOMAIN, devices=[device])
|
||||
config_entry.mock_state(hass, ConfigEntryState.LOADED)
|
||||
# Act
|
||||
await hass.config_entries.async_forward_entry_unload(config_entry, "switch")
|
||||
# Assert
|
||||
assert hass.states.get("switch.switch_1").state == STATE_UNAVAILABLE
|
||||
Reference in New Issue
Block a user