input
stringlengths
53
297k
output
stringclasses
604 values
repo_name
stringclasses
376 values
test_path
stringclasses
583 values
code_path
stringlengths
7
116
"""Support for OpenTherm Gateway devices.""" import asyncio from datetime import date, datetime import logging import pyotgw import pyotgw.vars as gw_vars import voluptuous as vol from homeassistant.components.binary_sensor import DOMAIN as COMP_BINARY_SENSOR from homeassistant.components.climate import DOMAIN as COMP_CLIMATE from homeassistant.components.sensor import DOMAIN as COMP_SENSOR from homeassistant.config_entries import SOURCE_IMPORT from homeassistant.const import ( ATTR_DATE, ATTR_ID, ATTR_MODE, ATTR_TEMPERATURE, ATTR_TIME, CONF_DEVICE, CONF_ID, CONF_NAME, EVENT_HOMEASSISTANT_STOP, PRECISION_HALVES, PRECISION_TENTHS, PRECISION_WHOLE, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.device_registry import ( async_get_registry as async_get_dev_reg, ) from homeassistant.helpers.dispatcher import async_dispatcher_send from .const import ( ATTR_CH_OVRD, ATTR_DHW_OVRD, ATTR_GW_ID, ATTR_LEVEL, CONF_CLIMATE, CONF_FLOOR_TEMP, CONF_PRECISION, CONF_READ_PRECISION, CONF_SET_PRECISION, DATA_GATEWAYS, DATA_OPENTHERM_GW, DOMAIN, SERVICE_RESET_GATEWAY, SERVICE_SET_CH_OVRD, SERVICE_SET_CLOCK, SERVICE_SET_CONTROL_SETPOINT, SERVICE_SET_GPIO_MODE, SERVICE_SET_HOT_WATER_OVRD, SERVICE_SET_HOT_WATER_SETPOINT, SERVICE_SET_LED_MODE, SERVICE_SET_MAX_MOD, SERVICE_SET_OAT, SERVICE_SET_SB_TEMP, ) _LOGGER = logging.getLogger(__name__) CLIMATE_SCHEMA = vol.Schema( { vol.Optional(CONF_PRECISION): vol.In( [PRECISION_TENTHS, PRECISION_HALVES, PRECISION_WHOLE] ), vol.Optional(CONF_FLOOR_TEMP, default=False): cv.boolean, } ) CONFIG_SCHEMA = vol.Schema( { DOMAIN: cv.schema_with_slug_keys( { vol.Required(CONF_DEVICE): cv.string, vol.Optional(CONF_CLIMATE, default={}): CLIMATE_SCHEMA, vol.Optional(CONF_NAME): cv.string, } ) }, extra=vol.ALLOW_EXTRA, ) async def options_updated(hass, entry): """Handle options update.""" gateway = hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS][entry.data[CONF_ID]] async_dispatcher_send(hass, gateway.options_update_signal, entry) async def async_setup_entry(hass, config_entry): """Set up the OpenTherm Gateway component.""" if DATA_OPENTHERM_GW not in hass.data: hass.data[DATA_OPENTHERM_GW] = {DATA_GATEWAYS: {}} gateway = OpenThermGatewayDevice(hass, config_entry) hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS][config_entry.data[CONF_ID]] = gateway if config_entry.options.get(CONF_PRECISION): migrate_options = dict(config_entry.options) migrate_options.update( { CONF_READ_PRECISION: config_entry.options[CONF_PRECISION], CONF_SET_PRECISION: config_entry.options[CONF_PRECISION], } ) del migrate_options[CONF_PRECISION] hass.config_entries.async_update_entry(config_entry, options=migrate_options) config_entry.add_update_listener(options_updated) # Schedule directly on the loop to avoid blocking HA startup. hass.loop.create_task(gateway.connect_and_subscribe()) for comp in [COMP_BINARY_SENSOR, COMP_CLIMATE, COMP_SENSOR]: hass.async_create_task( hass.config_entries.async_forward_entry_setup(config_entry, comp) ) register_services(hass) return True async def async_setup(hass, config): """Set up the OpenTherm Gateway component.""" if not hass.config_entries.async_entries(DOMAIN) and DOMAIN in config: conf = config[DOMAIN] for device_id, device_config in conf.items(): device_config[CONF_ID] = device_id hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=device_config ) ) return True def register_services(hass): """Register services for the component.""" service_reset_schema = vol.Schema( { vol.Required(ATTR_GW_ID): vol.All( cv.string, vol.In(hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS]) ) } ) service_set_central_heating_ovrd_schema = vol.Schema( { vol.Required(ATTR_GW_ID): vol.All( cv.string, vol.In(hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS]) ), vol.Required(ATTR_CH_OVRD): cv.boolean, } ) service_set_clock_schema = vol.Schema( { vol.Required(ATTR_GW_ID): vol.All( cv.string, vol.In(hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS]) ), vol.Optional(ATTR_DATE, default=date.today()): cv.date, vol.Optional(ATTR_TIME, default=datetime.now().time()): cv.time, } ) service_set_control_setpoint_schema = vol.Schema( { vol.Required(ATTR_GW_ID): vol.All( cv.string, vol.In(hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS]) ), vol.Required(ATTR_TEMPERATURE): vol.All( vol.Coerce(float), vol.Range(min=0, max=90) ), } ) service_set_hot_water_setpoint_schema = service_set_control_setpoint_schema service_set_hot_water_ovrd_schema = vol.Schema( { vol.Required(ATTR_GW_ID): vol.All( cv.string, vol.In(hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS]) ), vol.Required(ATTR_DHW_OVRD): vol.Any( vol.Equal("A"), vol.All(vol.Coerce(int), vol.Range(min=0, max=1)) ), } ) service_set_gpio_mode_schema = vol.Schema( vol.Any( vol.Schema( { vol.Required(ATTR_GW_ID): vol.All( cv.string, vol.In(hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS]) ), vol.Required(ATTR_ID): vol.Equal("A"), vol.Required(ATTR_MODE): vol.All( vol.Coerce(int), vol.Range(min=0, max=6) ), } ), vol.Schema( { vol.Required(ATTR_GW_ID): vol.All( cv.string, vol.In(hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS]) ), vol.Required(ATTR_ID): vol.Equal("B"), vol.Required(ATTR_MODE): vol.All( vol.Coerce(int), vol.Range(min=0, max=7) ), } ), ) ) service_set_led_mode_schema = vol.Schema( { vol.Required(ATTR_GW_ID): vol.All( cv.string, vol.In(hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS]) ), vol.Required(ATTR_ID): vol.In("ABCDEF"), vol.Required(ATTR_MODE): vol.In("RXTBOFHWCEMP"), } ) service_set_max_mod_schema = vol.Schema( { vol.Required(ATTR_GW_ID): vol.All( cv.string, vol.In(hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS]) ), vol.Required(ATTR_LEVEL): vol.All( vol.Coerce(int), vol.Range(min=-1, max=100) ), } ) service_set_oat_schema = vol.Schema( { vol.Required(ATTR_GW_ID): vol.All( cv.string, vol.In(hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS]) ), vol.Required(ATTR_TEMPERATURE): vol.All( vol.Coerce(float), vol.Range(min=-40, max=99) ), } ) service_set_sb_temp_schema = vol.Schema( { vol.Required(ATTR_GW_ID): vol.All( cv.string, vol.In(hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS]) ), vol.Required(ATTR_TEMPERATURE): vol.All( vol.Coerce(float), vol.Range(min=0, max=30) ), } ) async def reset_gateway(call): """Reset the OpenTherm Gateway.""" gw_dev = hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS][call.data[ATTR_GW_ID]] mode_rst = gw_vars.OTGW_MODE_RESET status = await gw_dev.gateway.set_mode(mode_rst) gw_dev.status = status async_dispatcher_send(hass, gw_dev.update_signal, gw_dev.status) hass.services.async_register( DOMAIN, SERVICE_RESET_GATEWAY, reset_gateway, service_reset_schema ) async def set_ch_ovrd(call): """Set the central heating override on the OpenTherm Gateway.""" gw_dev = hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS][call.data[ATTR_GW_ID]] await gw_dev.gateway.set_ch_enable_bit(1 if call.data[ATTR_CH_OVRD] else 0) hass.services.async_register( DOMAIN, SERVICE_SET_CH_OVRD, set_ch_ovrd, service_set_central_heating_ovrd_schema, ) async def set_control_setpoint(call): """Set the control setpoint on the OpenTherm Gateway.""" gw_dev = hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS][call.data[ATTR_GW_ID]] gw_var = gw_vars.DATA_CONTROL_SETPOINT value = await gw_dev.gateway.set_control_setpoint(call.data[ATTR_TEMPERATURE]) gw_dev.status.update({gw_var: value}) async_dispatcher_send(hass, gw_dev.update_signal, gw_dev.status) hass.services.async_register( DOMAIN, SERVICE_SET_CONTROL_SETPOINT, set_control_setpoint, service_set_control_setpoint_schema, ) async def set_dhw_ovrd(call): """Set the domestic hot water override on the OpenTherm Gateway.""" gw_dev = hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS][call.data[ATTR_GW_ID]] gw_var = gw_vars.OTGW_DHW_OVRD value = await gw_dev.gateway.set_hot_water_ovrd(call.data[ATTR_DHW_OVRD]) gw_dev.status.update({gw_var: value}) async_dispatcher_send(hass, gw_dev.update_signal, gw_dev.status) hass.services.async_register( DOMAIN, SERVICE_SET_HOT_WATER_OVRD, set_dhw_ovrd, service_set_hot_water_ovrd_schema, ) async def set_dhw_setpoint(call): """Set the domestic hot water setpoint on the OpenTherm Gateway.""" gw_dev = hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS][call.data[ATTR_GW_ID]] gw_var = gw_vars.DATA_DHW_SETPOINT value = await gw_dev.gateway.set_dhw_setpoint(call.data[ATTR_TEMPERATURE]) gw_dev.status.update({gw_var: value}) async_dispatcher_send(hass, gw_dev.update_signal, gw_dev.status) hass.services.async_register( DOMAIN, SERVICE_SET_HOT_WATER_SETPOINT, set_dhw_setpoint, service_set_hot_water_setpoint_schema, ) async def set_device_clock(call): """Set the clock on the OpenTherm Gateway.""" gw_dev = hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS][call.data[ATTR_GW_ID]] attr_date = call.data[ATTR_DATE] attr_time = call.data[ATTR_TIME] await gw_dev.gateway.set_clock(datetime.combine(attr_date, attr_time)) hass.services.async_register( DOMAIN, SERVICE_SET_CLOCK, set_device_clock, service_set_clock_schema ) async def set_gpio_mode(call): """Set the OpenTherm Gateway GPIO modes.""" gw_dev = hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS][call.data[ATTR_GW_ID]] gpio_id = call.data[ATTR_ID] gpio_mode = call.data[ATTR_MODE] mode = await gw_dev.gateway.set_gpio_mode(gpio_id, gpio_mode) gpio_var = getattr(gw_vars, f"OTGW_GPIO_{gpio_id}") gw_dev.status.update({gpio_var: mode}) async_dispatcher_send(hass, gw_dev.update_signal, gw_dev.status) hass.services.async_register( DOMAIN, SERVICE_SET_GPIO_MODE, set_gpio_mode, service_set_gpio_mode_schema ) async def set_led_mode(call): """Set the OpenTherm Gateway LED modes.""" gw_dev = hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS][call.data[ATTR_GW_ID]] led_id = call.data[ATTR_ID] led_mode = call.data[ATTR_MODE] mode = await gw_dev.gateway.set_led_mode(led_id, led_mode) led_var = getattr(gw_vars, f"OTGW_LED_{led_id}") gw_dev.status.update({led_var: mode}) async_dispatcher_send(hass, gw_dev.update_signal, gw_dev.status) hass.services.async_register( DOMAIN, SERVICE_SET_LED_MODE, set_led_mode, service_set_led_mode_schema ) async def set_max_mod(call): """Set the max modulation level.""" gw_dev = hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS][call.data[ATTR_GW_ID]] gw_var = gw_vars.DATA_SLAVE_MAX_RELATIVE_MOD level = call.data[ATTR_LEVEL] if level == -1: # Backend only clears setting on non-numeric values. level = "-" value = await gw_dev.gateway.set_max_relative_mod(level) gw_dev.status.update({gw_var: value}) async_dispatcher_send(hass, gw_dev.update_signal, gw_dev.status) hass.services.async_register( DOMAIN, SERVICE_SET_MAX_MOD, set_max_mod, service_set_max_mod_schema ) async def set_outside_temp(call): """Provide the outside temperature to the OpenTherm Gateway.""" gw_dev = hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS][call.data[ATTR_GW_ID]] gw_var = gw_vars.DATA_OUTSIDE_TEMP value = await gw_dev.gateway.set_outside_temp(call.data[ATTR_TEMPERATURE]) gw_dev.status.update({gw_var: value}) async_dispatcher_send(hass, gw_dev.update_signal, gw_dev.status) hass.services.async_register( DOMAIN, SERVICE_SET_OAT, set_outside_temp, service_set_oat_schema ) async def set_setback_temp(call): """Set the OpenTherm Gateway SetBack temperature.""" gw_dev = hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS][call.data[ATTR_GW_ID]] gw_var = gw_vars.OTGW_SB_TEMP value = await gw_dev.gateway.set_setback_temp(call.data[ATTR_TEMPERATURE]) gw_dev.status.update({gw_var: value}) async_dispatcher_send(hass, gw_dev.update_signal, gw_dev.status) hass.services.async_register( DOMAIN, SERVICE_SET_SB_TEMP, set_setback_temp, service_set_sb_temp_schema ) async def async_unload_entry(hass, entry): """Cleanup and disconnect from gateway.""" await asyncio.gather( hass.config_entries.async_forward_entry_unload(entry, COMP_BINARY_SENSOR), hass.config_entries.async_forward_entry_unload(entry, COMP_CLIMATE), hass.config_entries.async_forward_entry_unload(entry, COMP_SENSOR), ) gateway = hass.data[DATA_OPENTHERM_GW][DATA_GATEWAYS][entry.data[CONF_ID]] await gateway.cleanup() return True class OpenThermGatewayDevice: """OpenTherm Gateway device class.""" def __init__(self, hass, config_entry): """Initialize the OpenTherm Gateway.""" self.hass = hass self.device_path = config_entry.data[CONF_DEVICE] self.gw_id = config_entry.data[CONF_ID] self.name = config_entry.data[CONF_NAME] self.climate_config = config_entry.options self.config_entry_id = config_entry.entry_id self.status = {} self.update_signal = f"{DATA_OPENTHERM_GW}_{self.gw_id}_update" self.options_update_signal = f"{DATA_OPENTHERM_GW}_{self.gw_id}_options_update" self.gateway = pyotgw.pyotgw() self.gw_version = None async def cleanup(self, event=None): """Reset overrides on the gateway.""" await self.gateway.set_control_setpoint(0) await self.gateway.set_max_relative_mod("-") await self.gateway.disconnect() async def connect_and_subscribe(self): """Connect to serial device and subscribe report handler.""" self.status = await self.gateway.connect(self.hass.loop, self.device_path) version_string = self.status[gw_vars.OTGW].get(gw_vars.OTGW_ABOUT) self.gw_version = version_string[18:] if version_string else None _LOGGER.debug( "Connected to OpenTherm Gateway %s at %s", self.gw_version, self.device_path ) dev_reg = await async_get_dev_reg(self.hass) gw_dev = dev_reg.async_get_or_create( config_entry_id=self.config_entry_id, identifiers={(DOMAIN, self.gw_id)}, name=self.name, manufacturer="Schelte Bron", model="OpenTherm Gateway", sw_version=self.gw_version, ) if gw_dev.sw_version != self.gw_version: dev_reg.async_update_device(gw_dev.id, sw_version=self.gw_version) self.hass.bus.async_listen(EVENT_HOMEASSISTANT_STOP, self.cleanup) async def handle_report(status): """Handle reports from the OpenTherm Gateway.""" _LOGGER.debug("Received report: %s", status) self.status = status async_dispatcher_send(self.hass, self.update_signal, status) self.gateway.subscribe(handle_report)
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/opentherm_gw/__init__.py
"""Constants for the AVM Fritz!Box integration.""" import logging ATTR_STATE_BATTERY_LOW = "battery_low" ATTR_STATE_DEVICE_LOCKED = "device_locked" ATTR_STATE_HOLIDAY_MODE = "holiday_mode" ATTR_STATE_LOCKED = "locked" ATTR_STATE_SUMMER_MODE = "summer_mode" ATTR_STATE_WINDOW_OPEN = "window_open" ATTR_TEMPERATURE_UNIT = "temperature_unit" ATTR_TOTAL_CONSUMPTION = "total_consumption" ATTR_TOTAL_CONSUMPTION_UNIT = "total_consumption_unit" CONF_CONNECTIONS = "connections" DEFAULT_HOST = "fritz.box" DEFAULT_USERNAME = "admin" DOMAIN = "fritzbox" LOGGER = logging.getLogger(__package__) PLATFORMS = ["binary_sensor", "climate", "switch", "sensor"]
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/fritzbox/const.py
"""Support for ESPHome lights.""" from __future__ import annotations from aioesphomeapi import LightInfo, LightState from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_FLASH, ATTR_HS_COLOR, ATTR_TRANSITION, ATTR_WHITE_VALUE, FLASH_LONG, FLASH_SHORT, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP, SUPPORT_EFFECT, SUPPORT_FLASH, SUPPORT_TRANSITION, SUPPORT_WHITE_VALUE, LightEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.helpers.typing import HomeAssistantType import homeassistant.util.color as color_util from . import EsphomeEntity, esphome_state_property, platform_async_setup_entry FLASH_LENGTHS = {FLASH_SHORT: 2, FLASH_LONG: 10} async def async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities ) -> None: """Set up ESPHome lights based on a config entry.""" await platform_async_setup_entry( hass, entry, async_add_entities, component_key="light", info_type=LightInfo, entity_type=EsphomeLight, state_type=LightState, ) class EsphomeLight(EsphomeEntity, LightEntity): """A switch implementation for ESPHome.""" @property def _static_info(self) -> LightInfo: return super()._static_info @property def _state(self) -> LightState | None: return super()._state # https://github.com/PyCQA/pylint/issues/3150 for all @esphome_state_property # pylint: disable=invalid-overridden-method @esphome_state_property def is_on(self) -> bool | None: """Return true if the switch is on.""" return self._state.state async def async_turn_on(self, **kwargs) -> None: """Turn the entity on.""" data = {"key": self._static_info.key, "state": True} if ATTR_HS_COLOR in kwargs: hue, sat = kwargs[ATTR_HS_COLOR] red, green, blue = color_util.color_hsv_to_RGB(hue, sat, 100) data["rgb"] = (red / 255, green / 255, blue / 255) if ATTR_FLASH in kwargs: data["flash_length"] = FLASH_LENGTHS[kwargs[ATTR_FLASH]] if ATTR_TRANSITION in kwargs: data["transition_length"] = kwargs[ATTR_TRANSITION] if ATTR_BRIGHTNESS in kwargs: data["brightness"] = kwargs[ATTR_BRIGHTNESS] / 255 if ATTR_COLOR_TEMP in kwargs: data["color_temperature"] = kwargs[ATTR_COLOR_TEMP] if ATTR_EFFECT in kwargs: data["effect"] = kwargs[ATTR_EFFECT] if ATTR_WHITE_VALUE in kwargs: data["white"] = kwargs[ATTR_WHITE_VALUE] / 255 await self._client.light_command(**data) async def async_turn_off(self, **kwargs) -> None: """Turn the entity off.""" data = {"key": self._static_info.key, "state": False} if ATTR_FLASH in kwargs: data["flash_length"] = FLASH_LENGTHS[kwargs[ATTR_FLASH]] if ATTR_TRANSITION in kwargs: data["transition_length"] = kwargs[ATTR_TRANSITION] await self._client.light_command(**data) @esphome_state_property def brightness(self) -> int | None: """Return the brightness of this light between 0..255.""" return round(self._state.brightness * 255) @esphome_state_property def hs_color(self) -> tuple[float, float] | None: """Return the hue and saturation color value [float, float].""" return color_util.color_RGB_to_hs( self._state.red * 255, self._state.green * 255, self._state.blue * 255 ) @esphome_state_property def color_temp(self) -> float | None: """Return the CT color value in mireds.""" return self._state.color_temperature @esphome_state_property def white_value(self) -> int | None: """Return the white value of this light between 0..255.""" return round(self._state.white * 255) @esphome_state_property def effect(self) -> str | None: """Return the current effect.""" return self._state.effect @property def supported_features(self) -> int: """Flag supported features.""" flags = SUPPORT_FLASH if self._static_info.supports_brightness: flags |= SUPPORT_BRIGHTNESS flags |= SUPPORT_TRANSITION if self._static_info.supports_rgb: flags |= SUPPORT_COLOR if self._static_info.supports_white_value: flags |= SUPPORT_WHITE_VALUE if self._static_info.supports_color_temperature: flags |= SUPPORT_COLOR_TEMP if self._static_info.effects: flags |= SUPPORT_EFFECT return flags @property def effect_list(self) -> list[str]: """Return the list of supported effects.""" return self._static_info.effects @property def min_mireds(self) -> float: """Return the coldest color_temp that this light supports.""" return self._static_info.min_mireds @property def max_mireds(self) -> float: """Return the warmest color_temp that this light supports.""" return self._static_info.max_mireds
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/esphome/light.py
"""This platform provides support for sensor data from RainMachine.""" from functools import partial from typing import Callable from regenmaschine.controller import Controller from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import TEMP_CELSIUS, VOLUME_CUBIC_METERS from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from . import RainMachineEntity from .const import ( DATA_CONTROLLER, DATA_COORDINATOR, DATA_PROVISION_SETTINGS, DATA_RESTRICTIONS_UNIVERSAL, DOMAIN, ) TYPE_FLOW_SENSOR_CLICK_M3 = "flow_sensor_clicks_cubic_meter" TYPE_FLOW_SENSOR_CONSUMED_LITERS = "flow_sensor_consumed_liters" TYPE_FLOW_SENSOR_START_INDEX = "flow_sensor_start_index" TYPE_FLOW_SENSOR_WATERING_CLICKS = "flow_sensor_watering_clicks" TYPE_FREEZE_TEMP = "freeze_protect_temp" SENSORS = { TYPE_FLOW_SENSOR_CLICK_M3: ( "Flow Sensor Clicks", "mdi:water-pump", f"clicks/{VOLUME_CUBIC_METERS}", None, False, DATA_PROVISION_SETTINGS, ), TYPE_FLOW_SENSOR_CONSUMED_LITERS: ( "Flow Sensor Consumed Liters", "mdi:water-pump", "liter", None, False, DATA_PROVISION_SETTINGS, ), TYPE_FLOW_SENSOR_START_INDEX: ( "Flow Sensor Start Index", "mdi:water-pump", "index", None, False, DATA_PROVISION_SETTINGS, ), TYPE_FLOW_SENSOR_WATERING_CLICKS: ( "Flow Sensor Clicks", "mdi:water-pump", "clicks", None, False, DATA_PROVISION_SETTINGS, ), TYPE_FREEZE_TEMP: ( "Freeze Protect Temperature", "mdi:thermometer", TEMP_CELSIUS, "temperature", True, DATA_RESTRICTIONS_UNIVERSAL, ), } async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: Callable ) -> None: """Set up RainMachine sensors based on a config entry.""" controller = hass.data[DOMAIN][DATA_CONTROLLER][entry.entry_id] coordinators = hass.data[DOMAIN][DATA_COORDINATOR][entry.entry_id] @callback def async_get_sensor(api_category: str) -> partial: """Generate the appropriate sensor object for an API category.""" if api_category == DATA_PROVISION_SETTINGS: return partial( ProvisionSettingsSensor, coordinators[DATA_PROVISION_SETTINGS], ) return partial( UniversalRestrictionsSensor, coordinators[DATA_RESTRICTIONS_UNIVERSAL], ) async_add_entities( [ async_get_sensor(api_category)( controller, sensor_type, name, icon, unit, device_class, enabled_by_default, ) for ( sensor_type, (name, icon, unit, device_class, enabled_by_default, api_category), ) in SENSORS.items() ] ) class RainMachineSensor(RainMachineEntity, SensorEntity): """Define a general RainMachine sensor.""" def __init__( self, coordinator: DataUpdateCoordinator, controller: Controller, sensor_type: str, name: str, icon: str, unit: str, device_class: str, enabled_by_default: bool, ) -> None: """Initialize.""" super().__init__(coordinator, controller) self._device_class = device_class self._enabled_by_default = enabled_by_default self._icon = icon self._name = name self._sensor_type = sensor_type self._state = None self._unit = unit @property def entity_registry_enabled_default(self) -> bool: """Determine whether an entity is enabled by default.""" return self._enabled_by_default @property def icon(self) -> str: """Return the icon.""" return self._icon @property def state(self) -> str: """Return the name of the entity.""" return self._state @property def unique_id(self) -> str: """Return a unique, Home Assistant friendly identifier for this entity.""" return f"{self._unique_id}_{self._sensor_type}" @property def unit_of_measurement(self) -> str: """Return the unit the value is expressed in.""" return self._unit class ProvisionSettingsSensor(RainMachineSensor): """Define a sensor that handles provisioning data.""" @callback def update_from_latest_data(self) -> None: """Update the state.""" if self._sensor_type == TYPE_FLOW_SENSOR_CLICK_M3: self._state = self.coordinator.data["system"].get( "flowSensorClicksPerCubicMeter" ) elif self._sensor_type == TYPE_FLOW_SENSOR_CONSUMED_LITERS: clicks = self.coordinator.data["system"].get("flowSensorWateringClicks") clicks_per_m3 = self.coordinator.data["system"].get( "flowSensorClicksPerCubicMeter" ) if clicks and clicks_per_m3: self._state = (clicks * 1000) / clicks_per_m3 else: self._state = None elif self._sensor_type == TYPE_FLOW_SENSOR_START_INDEX: self._state = self.coordinator.data["system"].get("flowSensorStartIndex") elif self._sensor_type == TYPE_FLOW_SENSOR_WATERING_CLICKS: self._state = self.coordinator.data["system"].get( "flowSensorWateringClicks" ) class UniversalRestrictionsSensor(RainMachineSensor): """Define a sensor that handles universal restrictions data.""" @callback def update_from_latest_data(self) -> None: """Update the state.""" if self._sensor_type == TYPE_FREEZE_TEMP: self._state = self.coordinator.data["freezeProtectTemp"]
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/rainmachine/sensor.py
"""Define a config flow manager for AirVisual.""" import asyncio from pyairvisual import CloudAPI, NodeSamba from pyairvisual.errors import ( AirVisualError, InvalidKeyError, NodeProError, NotFoundError, ) import voluptuous as vol from homeassistant import config_entries from homeassistant.const import ( CONF_API_KEY, CONF_IP_ADDRESS, CONF_LATITUDE, CONF_LONGITUDE, CONF_PASSWORD, CONF_SHOW_ON_MAP, CONF_STATE, ) from homeassistant.core import callback from homeassistant.helpers import aiohttp_client, config_validation as cv from . import async_get_geography_id from .const import ( CONF_CITY, CONF_COUNTRY, CONF_INTEGRATION_TYPE, DOMAIN, INTEGRATION_TYPE_GEOGRAPHY_COORDS, INTEGRATION_TYPE_GEOGRAPHY_NAME, INTEGRATION_TYPE_NODE_PRO, LOGGER, ) API_KEY_DATA_SCHEMA = vol.Schema({vol.Required(CONF_API_KEY): cv.string}) GEOGRAPHY_NAME_SCHEMA = API_KEY_DATA_SCHEMA.extend( { vol.Required(CONF_CITY): cv.string, vol.Required(CONF_STATE): cv.string, vol.Required(CONF_COUNTRY): cv.string, } ) NODE_PRO_SCHEMA = vol.Schema( {vol.Required(CONF_IP_ADDRESS): str, vol.Required(CONF_PASSWORD): cv.string} ) PICK_INTEGRATION_TYPE_SCHEMA = vol.Schema( { vol.Required("type"): vol.In( [ INTEGRATION_TYPE_GEOGRAPHY_COORDS, INTEGRATION_TYPE_GEOGRAPHY_NAME, INTEGRATION_TYPE_NODE_PRO, ] ) } ) class AirVisualFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Handle an AirVisual config flow.""" VERSION = 2 CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL def __init__(self): """Initialize the config flow.""" self._entry_data_for_reauth = None self._geo_id = None @property def geography_coords_schema(self): """Return the data schema for the cloud API.""" return API_KEY_DATA_SCHEMA.extend( { vol.Required( CONF_LATITUDE, default=self.hass.config.latitude ): cv.latitude, vol.Required( CONF_LONGITUDE, default=self.hass.config.longitude ): cv.longitude, } ) async def _async_finish_geography(self, user_input, integration_type): """Validate a Cloud API key.""" websession = aiohttp_client.async_get_clientsession(self.hass) cloud_api = CloudAPI(user_input[CONF_API_KEY], session=websession) # If this is the first (and only the first) time we've seen this API key, check # that it's valid: valid_keys = self.hass.data.setdefault("airvisual_checked_api_keys", set()) valid_keys_lock = self.hass.data.setdefault( "airvisual_checked_api_keys_lock", asyncio.Lock() ) if integration_type == INTEGRATION_TYPE_GEOGRAPHY_COORDS: coro = cloud_api.air_quality.nearest_city() error_schema = self.geography_coords_schema error_step = "geography_by_coords" else: coro = cloud_api.air_quality.city( user_input[CONF_CITY], user_input[CONF_STATE], user_input[CONF_COUNTRY] ) error_schema = GEOGRAPHY_NAME_SCHEMA error_step = "geography_by_name" async with valid_keys_lock: if user_input[CONF_API_KEY] not in valid_keys: try: await coro except InvalidKeyError: return self.async_show_form( step_id=error_step, data_schema=error_schema, errors={CONF_API_KEY: "invalid_api_key"}, ) except NotFoundError: return self.async_show_form( step_id=error_step, data_schema=error_schema, errors={CONF_CITY: "location_not_found"}, ) except AirVisualError as err: LOGGER.error(err) return self.async_show_form( step_id=error_step, data_schema=error_schema, errors={"base": "unknown"}, ) valid_keys.add(user_input[CONF_API_KEY]) existing_entry = await self.async_set_unique_id(self._geo_id) if existing_entry: self.hass.config_entries.async_update_entry(existing_entry, data=user_input) return self.async_abort(reason="reauth_successful") return self.async_create_entry( title=f"Cloud API ({self._geo_id})", data={**user_input, CONF_INTEGRATION_TYPE: integration_type}, ) async def _async_init_geography(self, user_input, integration_type): """Handle the initialization of the integration via the cloud API.""" self._geo_id = async_get_geography_id(user_input) await self._async_set_unique_id(self._geo_id) self._abort_if_unique_id_configured() return await self._async_finish_geography(user_input, integration_type) async def _async_set_unique_id(self, unique_id): """Set the unique ID of the config flow and abort if it already exists.""" await self.async_set_unique_id(unique_id) self._abort_if_unique_id_configured() @staticmethod @callback def async_get_options_flow(config_entry): """Define the config flow to handle options.""" return AirVisualOptionsFlowHandler(config_entry) async def async_step_geography_by_coords(self, user_input=None): """Handle the initialization of the cloud API based on latitude/longitude.""" if not user_input: return self.async_show_form( step_id="geography_by_coords", data_schema=self.geography_coords_schema ) return await self._async_init_geography( user_input, INTEGRATION_TYPE_GEOGRAPHY_COORDS ) async def async_step_geography_by_name(self, user_input=None): """Handle the initialization of the cloud API based on city/state/country.""" if not user_input: return self.async_show_form( step_id="geography_by_name", data_schema=GEOGRAPHY_NAME_SCHEMA ) return await self._async_init_geography( user_input, INTEGRATION_TYPE_GEOGRAPHY_NAME ) async def async_step_node_pro(self, user_input=None): """Handle the initialization of the integration with a Node/Pro.""" if not user_input: return self.async_show_form(step_id="node_pro", data_schema=NODE_PRO_SCHEMA) await self._async_set_unique_id(user_input[CONF_IP_ADDRESS]) node = NodeSamba(user_input[CONF_IP_ADDRESS], user_input[CONF_PASSWORD]) try: await node.async_connect() except NodeProError as err: LOGGER.error("Error connecting to Node/Pro unit: %s", err) return self.async_show_form( step_id="node_pro", data_schema=NODE_PRO_SCHEMA, errors={CONF_IP_ADDRESS: "cannot_connect"}, ) await node.async_disconnect() return self.async_create_entry( title=f"Node/Pro ({user_input[CONF_IP_ADDRESS]})", data={**user_input, CONF_INTEGRATION_TYPE: INTEGRATION_TYPE_NODE_PRO}, ) async def async_step_reauth(self, data): """Handle configuration by re-auth.""" self._entry_data_for_reauth = data self._geo_id = async_get_geography_id(data) return await self.async_step_reauth_confirm() async def async_step_reauth_confirm(self, user_input=None): """Handle re-auth completion.""" if not user_input: return self.async_show_form( step_id="reauth_confirm", data_schema=API_KEY_DATA_SCHEMA ) conf = {CONF_API_KEY: user_input[CONF_API_KEY], **self._entry_data_for_reauth} return await self._async_finish_geography( conf, self._entry_data_for_reauth[CONF_INTEGRATION_TYPE] ) async def async_step_user(self, user_input=None): """Handle the start of the config flow.""" if not user_input: return self.async_show_form( step_id="user", data_schema=PICK_INTEGRATION_TYPE_SCHEMA ) if user_input["type"] == INTEGRATION_TYPE_GEOGRAPHY_COORDS: return await self.async_step_geography_by_coords() if user_input["type"] == INTEGRATION_TYPE_GEOGRAPHY_NAME: return await self.async_step_geography_by_name() return await self.async_step_node_pro() class AirVisualOptionsFlowHandler(config_entries.OptionsFlow): """Handle an AirVisual options flow.""" def __init__(self, config_entry): """Initialize.""" self.config_entry = config_entry async def async_step_init(self, user_input=None): """Manage the options.""" if user_input is not None: return self.async_create_entry(title="", data=user_input) return self.async_show_form( step_id="init", data_schema=vol.Schema( { vol.Required( CONF_SHOW_ON_MAP, default=self.config_entry.options.get(CONF_SHOW_ON_MAP), ): bool } ), )
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/airvisual/config_flow.py
"""Brother helpers functions.""" import logging import pysnmp.hlapi.asyncio as hlapi from pysnmp.hlapi.asyncio.cmdgen import lcd from homeassistant.const import EVENT_HOMEASSISTANT_STOP from homeassistant.core import callback from homeassistant.helpers import singleton from .const import DOMAIN, SNMP _LOGGER = logging.getLogger(__name__) @singleton.singleton("snmp_engine") def get_snmp_engine(hass): """Get SNMP engine.""" _LOGGER.debug("Creating SNMP engine") snmp_engine = hlapi.SnmpEngine() @callback def shutdown_listener(ev): if hass.data.get(DOMAIN): _LOGGER.debug("Unconfiguring SNMP engine") lcd.unconfigure(hass.data[DOMAIN][SNMP], None) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, shutdown_listener) return snmp_engine
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/brother/utils.py
"""The DirecTV integration.""" from __future__ import annotations import asyncio from datetime import timedelta from typing import Any from directv import DIRECTV, DIRECTVError from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_NAME, CONF_HOST from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.entity import Entity from .const import ( ATTR_IDENTIFIERS, ATTR_MANUFACTURER, ATTR_MODEL, ATTR_SOFTWARE_VERSION, ATTR_VIA_DEVICE, DOMAIN, ) CONFIG_SCHEMA = cv.deprecated(DOMAIN) PLATFORMS = ["media_player", "remote"] SCAN_INTERVAL = timedelta(seconds=30) async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up DirecTV from a config entry.""" dtv = DIRECTV(entry.data[CONF_HOST], session=async_get_clientsession(hass)) try: await dtv.update() except DIRECTVError as err: raise ConfigEntryNotReady from err hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = dtv for platform in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, platform) ) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" unload_ok = all( await asyncio.gather( *[ hass.config_entries.async_forward_entry_unload(entry, platform) for platform in PLATFORMS ] ) ) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) return unload_ok class DIRECTVEntity(Entity): """Defines a base DirecTV entity.""" def __init__(self, *, dtv: DIRECTV, name: str, address: str = "0") -> None: """Initialize the DirecTV entity.""" self._address = address self._device_id = address if address != "0" else dtv.device.info.receiver_id self._is_client = address != "0" self._name = name self.dtv = dtv @property def name(self) -> str: """Return the name of the entity.""" return self._name @property def device_info(self) -> dict[str, Any]: """Return device information about this DirecTV receiver.""" return { ATTR_IDENTIFIERS: {(DOMAIN, self._device_id)}, ATTR_NAME: self.name, ATTR_MANUFACTURER: self.dtv.device.info.brand, ATTR_MODEL: None, ATTR_SOFTWARE_VERSION: self.dtv.device.info.version, ATTR_VIA_DEVICE: (DOMAIN, self.dtv.device.info.receiver_id), }
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/directv/__init__.py
"""Support for interface with a Gree climate systems.""" from __future__ import annotations from homeassistant.components.switch import DEVICE_CLASS_SWITCH, SwitchEntity from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import COORDINATOR, DOMAIN async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Gree HVAC device from a config entry.""" async_add_entities( [ GreeSwitchEntity(coordinator) for coordinator in hass.data[DOMAIN][COORDINATOR] ] ) class GreeSwitchEntity(CoordinatorEntity, SwitchEntity): """Representation of a Gree HVAC device.""" def __init__(self, coordinator): """Initialize the Gree device.""" super().__init__(coordinator) self._name = coordinator.device.device_info.name + " Panel Light" self._mac = coordinator.device.device_info.mac @property def name(self) -> str: """Return the name of the device.""" return self._name @property def unique_id(self) -> str: """Return a unique id for the device.""" return f"{self._mac}-panel-light" @property def icon(self) -> str | None: """Return the icon for the device.""" return "mdi:lightbulb" @property def device_info(self): """Return device specific attributes.""" return { "name": self._name, "identifiers": {(DOMAIN, self._mac)}, "manufacturer": "Gree", "connections": {(CONNECTION_NETWORK_MAC, self._mac)}, } @property def device_class(self): """Return the class of this device, from component DEVICE_CLASSES.""" return DEVICE_CLASS_SWITCH @property def is_on(self) -> bool: """Return if the light is turned on.""" return self.coordinator.device.light async def async_turn_on(self, **kwargs): """Turn the entity on.""" self.coordinator.device.light = True await self.coordinator.push_state_update() self.async_write_ha_state() async def async_turn_off(self, **kwargs): """Turn the entity off.""" self.coordinator.device.light = False await self.coordinator.push_state_update() self.async_write_ha_state()
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/gree/switch.py
"""Implement the Google Smart Home traits.""" from __future__ import annotations import logging from homeassistant.components import ( alarm_control_panel, binary_sensor, camera, cover, fan, group, input_boolean, input_select, light, lock, media_player, scene, script, sensor, switch, vacuum, ) from homeassistant.components.climate import const as climate from homeassistant.components.humidifier import const as humidifier from homeassistant.const import ( ATTR_ASSUMED_STATE, ATTR_CODE, ATTR_DEVICE_CLASS, ATTR_ENTITY_ID, ATTR_MODE, ATTR_SUPPORTED_FEATURES, ATTR_TEMPERATURE, CAST_APP_ID_HOMEASSISTANT, SERVICE_ALARM_ARM_AWAY, SERVICE_ALARM_ARM_CUSTOM_BYPASS, SERVICE_ALARM_ARM_HOME, SERVICE_ALARM_ARM_NIGHT, SERVICE_ALARM_DISARM, SERVICE_ALARM_TRIGGER, SERVICE_TURN_OFF, SERVICE_TURN_ON, STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_CUSTOM_BYPASS, STATE_ALARM_ARMED_HOME, STATE_ALARM_ARMED_NIGHT, STATE_ALARM_DISARMED, STATE_ALARM_PENDING, STATE_ALARM_TRIGGERED, STATE_IDLE, STATE_LOCKED, STATE_OFF, STATE_ON, STATE_PAUSED, STATE_PLAYING, STATE_STANDBY, STATE_UNAVAILABLE, STATE_UNKNOWN, TEMP_CELSIUS, TEMP_FAHRENHEIT, ) from homeassistant.core import DOMAIN as HA_DOMAIN from homeassistant.helpers.network import get_url from homeassistant.util import color as color_util, dt, temperature as temp_util from .const import ( CHALLENGE_ACK_NEEDED, CHALLENGE_FAILED_PIN_NEEDED, CHALLENGE_PIN_NEEDED, ERR_ALREADY_ARMED, ERR_ALREADY_DISARMED, ERR_ALREADY_STOPPED, ERR_CHALLENGE_NOT_SETUP, ERR_NOT_SUPPORTED, ERR_UNSUPPORTED_INPUT, ERR_VALUE_OUT_OF_RANGE, ) from .error import ChallengeNeeded, SmartHomeError _LOGGER = logging.getLogger(__name__) PREFIX_TRAITS = "action.devices.traits." TRAIT_CAMERA_STREAM = f"{PREFIX_TRAITS}CameraStream" TRAIT_ONOFF = f"{PREFIX_TRAITS}OnOff" TRAIT_DOCK = f"{PREFIX_TRAITS}Dock" TRAIT_STARTSTOP = f"{PREFIX_TRAITS}StartStop" TRAIT_BRIGHTNESS = f"{PREFIX_TRAITS}Brightness" TRAIT_COLOR_SETTING = f"{PREFIX_TRAITS}ColorSetting" TRAIT_SCENE = f"{PREFIX_TRAITS}Scene" TRAIT_TEMPERATURE_SETTING = f"{PREFIX_TRAITS}TemperatureSetting" TRAIT_LOCKUNLOCK = f"{PREFIX_TRAITS}LockUnlock" TRAIT_FANSPEED = f"{PREFIX_TRAITS}FanSpeed" TRAIT_MODES = f"{PREFIX_TRAITS}Modes" TRAIT_INPUTSELECTOR = f"{PREFIX_TRAITS}InputSelector" TRAIT_OPENCLOSE = f"{PREFIX_TRAITS}OpenClose" TRAIT_VOLUME = f"{PREFIX_TRAITS}Volume" TRAIT_ARMDISARM = f"{PREFIX_TRAITS}ArmDisarm" TRAIT_HUMIDITY_SETTING = f"{PREFIX_TRAITS}HumiditySetting" TRAIT_TRANSPORT_CONTROL = f"{PREFIX_TRAITS}TransportControl" TRAIT_MEDIA_STATE = f"{PREFIX_TRAITS}MediaState" PREFIX_COMMANDS = "action.devices.commands." COMMAND_ONOFF = f"{PREFIX_COMMANDS}OnOff" COMMAND_GET_CAMERA_STREAM = f"{PREFIX_COMMANDS}GetCameraStream" COMMAND_DOCK = f"{PREFIX_COMMANDS}Dock" COMMAND_STARTSTOP = f"{PREFIX_COMMANDS}StartStop" COMMAND_PAUSEUNPAUSE = f"{PREFIX_COMMANDS}PauseUnpause" COMMAND_BRIGHTNESS_ABSOLUTE = f"{PREFIX_COMMANDS}BrightnessAbsolute" COMMAND_COLOR_ABSOLUTE = f"{PREFIX_COMMANDS}ColorAbsolute" COMMAND_ACTIVATE_SCENE = f"{PREFIX_COMMANDS}ActivateScene" COMMAND_THERMOSTAT_TEMPERATURE_SETPOINT = ( f"{PREFIX_COMMANDS}ThermostatTemperatureSetpoint" ) COMMAND_THERMOSTAT_TEMPERATURE_SET_RANGE = ( f"{PREFIX_COMMANDS}ThermostatTemperatureSetRange" ) COMMAND_THERMOSTAT_SET_MODE = f"{PREFIX_COMMANDS}ThermostatSetMode" COMMAND_LOCKUNLOCK = f"{PREFIX_COMMANDS}LockUnlock" COMMAND_FANSPEED = f"{PREFIX_COMMANDS}SetFanSpeed" COMMAND_MODES = f"{PREFIX_COMMANDS}SetModes" COMMAND_INPUT = f"{PREFIX_COMMANDS}SetInput" COMMAND_NEXT_INPUT = f"{PREFIX_COMMANDS}NextInput" COMMAND_PREVIOUS_INPUT = f"{PREFIX_COMMANDS}PreviousInput" COMMAND_OPENCLOSE = f"{PREFIX_COMMANDS}OpenClose" COMMAND_OPENCLOSE_RELATIVE = f"{PREFIX_COMMANDS}OpenCloseRelative" COMMAND_SET_VOLUME = f"{PREFIX_COMMANDS}setVolume" COMMAND_VOLUME_RELATIVE = f"{PREFIX_COMMANDS}volumeRelative" COMMAND_MUTE = f"{PREFIX_COMMANDS}mute" COMMAND_ARMDISARM = f"{PREFIX_COMMANDS}ArmDisarm" COMMAND_MEDIA_NEXT = f"{PREFIX_COMMANDS}mediaNext" COMMAND_MEDIA_PAUSE = f"{PREFIX_COMMANDS}mediaPause" COMMAND_MEDIA_PREVIOUS = f"{PREFIX_COMMANDS}mediaPrevious" COMMAND_MEDIA_RESUME = f"{PREFIX_COMMANDS}mediaResume" COMMAND_MEDIA_SEEK_RELATIVE = f"{PREFIX_COMMANDS}mediaSeekRelative" COMMAND_MEDIA_SEEK_TO_POSITION = f"{PREFIX_COMMANDS}mediaSeekToPosition" COMMAND_MEDIA_SHUFFLE = f"{PREFIX_COMMANDS}mediaShuffle" COMMAND_MEDIA_STOP = f"{PREFIX_COMMANDS}mediaStop" COMMAND_SET_HUMIDITY = f"{PREFIX_COMMANDS}SetHumidity" TRAITS = [] def register_trait(trait): """Decorate a function to register a trait.""" TRAITS.append(trait) return trait def _google_temp_unit(units): """Return Google temperature unit.""" if units == TEMP_FAHRENHEIT: return "F" return "C" def _next_selected(items: list[str], selected: str | None) -> str | None: """Return the next item in a item list starting at given value. If selected is missing in items, None is returned """ try: index = items.index(selected) except ValueError: return None next_item = 0 if index == len(items) - 1 else index + 1 return items[next_item] class _Trait: """Represents a Trait inside Google Assistant skill.""" commands = [] @staticmethod def might_2fa(domain, features, device_class): """Return if the trait might ask for 2FA.""" return False def __init__(self, hass, state, config): """Initialize a trait for a state.""" self.hass = hass self.state = state self.config = config def sync_attributes(self): """Return attributes for a sync request.""" raise NotImplementedError def query_attributes(self): """Return the attributes of this trait for this entity.""" raise NotImplementedError def can_execute(self, command, params): """Test if command can be executed.""" return command in self.commands async def execute(self, command, data, params, challenge): """Execute a trait command.""" raise NotImplementedError @register_trait class BrightnessTrait(_Trait): """Trait to control brightness of a device. https://developers.google.com/actions/smarthome/traits/brightness """ name = TRAIT_BRIGHTNESS commands = [COMMAND_BRIGHTNESS_ABSOLUTE] @staticmethod def supported(domain, features, device_class): """Test if state is supported.""" if domain == light.DOMAIN: return features & light.SUPPORT_BRIGHTNESS return False def sync_attributes(self): """Return brightness attributes for a sync request.""" return {} def query_attributes(self): """Return brightness query attributes.""" domain = self.state.domain response = {} if domain == light.DOMAIN: brightness = self.state.attributes.get(light.ATTR_BRIGHTNESS) if brightness is not None: response["brightness"] = int(100 * (brightness / 255)) else: response["brightness"] = 0 return response async def execute(self, command, data, params, challenge): """Execute a brightness command.""" domain = self.state.domain if domain == light.DOMAIN: await self.hass.services.async_call( light.DOMAIN, light.SERVICE_TURN_ON, { ATTR_ENTITY_ID: self.state.entity_id, light.ATTR_BRIGHTNESS_PCT: params["brightness"], }, blocking=True, context=data.context, ) @register_trait class CameraStreamTrait(_Trait): """Trait to stream from cameras. https://developers.google.com/actions/smarthome/traits/camerastream """ name = TRAIT_CAMERA_STREAM commands = [COMMAND_GET_CAMERA_STREAM] stream_info = None @staticmethod def supported(domain, features, device_class): """Test if state is supported.""" if domain == camera.DOMAIN: return features & camera.SUPPORT_STREAM return False def sync_attributes(self): """Return stream attributes for a sync request.""" return { "cameraStreamSupportedProtocols": ["hls"], "cameraStreamNeedAuthToken": False, "cameraStreamNeedDrmEncryption": False, } def query_attributes(self): """Return camera stream attributes.""" return self.stream_info or {} async def execute(self, command, data, params, challenge): """Execute a get camera stream command.""" url = await self.hass.components.camera.async_request_stream( self.state.entity_id, "hls" ) self.stream_info = { "cameraStreamAccessUrl": f"{get_url(self.hass)}{url}", "cameraStreamReceiverAppId": CAST_APP_ID_HOMEASSISTANT, } @register_trait class OnOffTrait(_Trait): """Trait to offer basic on and off functionality. https://developers.google.com/actions/smarthome/traits/onoff """ name = TRAIT_ONOFF commands = [COMMAND_ONOFF] @staticmethod def supported(domain, features, device_class): """Test if state is supported.""" return domain in ( group.DOMAIN, input_boolean.DOMAIN, switch.DOMAIN, fan.DOMAIN, light.DOMAIN, media_player.DOMAIN, humidifier.DOMAIN, ) def sync_attributes(self): """Return OnOff attributes for a sync request.""" if self.state.attributes.get(ATTR_ASSUMED_STATE, False): return {"commandOnlyOnOff": True} return {} def query_attributes(self): """Return OnOff query attributes.""" return {"on": self.state.state not in (STATE_OFF, STATE_UNKNOWN)} async def execute(self, command, data, params, challenge): """Execute an OnOff command.""" domain = self.state.domain if domain == group.DOMAIN: service_domain = HA_DOMAIN service = SERVICE_TURN_ON if params["on"] else SERVICE_TURN_OFF else: service_domain = domain service = SERVICE_TURN_ON if params["on"] else SERVICE_TURN_OFF await self.hass.services.async_call( service_domain, service, {ATTR_ENTITY_ID: self.state.entity_id}, blocking=True, context=data.context, ) @register_trait class ColorSettingTrait(_Trait): """Trait to offer color temperature functionality. https://developers.google.com/actions/smarthome/traits/colortemperature """ name = TRAIT_COLOR_SETTING commands = [COMMAND_COLOR_ABSOLUTE] @staticmethod def supported(domain, features, device_class): """Test if state is supported.""" if domain != light.DOMAIN: return False return features & light.SUPPORT_COLOR_TEMP or features & light.SUPPORT_COLOR def sync_attributes(self): """Return color temperature attributes for a sync request.""" attrs = self.state.attributes features = attrs.get(ATTR_SUPPORTED_FEATURES, 0) response = {} if features & light.SUPPORT_COLOR: response["colorModel"] = "hsv" if features & light.SUPPORT_COLOR_TEMP: # Max Kelvin is Min Mireds K = 1000000 / mireds # Min Kelvin is Max Mireds K = 1000000 / mireds response["colorTemperatureRange"] = { "temperatureMaxK": color_util.color_temperature_mired_to_kelvin( attrs.get(light.ATTR_MIN_MIREDS) ), "temperatureMinK": color_util.color_temperature_mired_to_kelvin( attrs.get(light.ATTR_MAX_MIREDS) ), } return response def query_attributes(self): """Return color temperature query attributes.""" features = self.state.attributes.get(ATTR_SUPPORTED_FEATURES, 0) color = {} if features & light.SUPPORT_COLOR: color_hs = self.state.attributes.get(light.ATTR_HS_COLOR) brightness = self.state.attributes.get(light.ATTR_BRIGHTNESS, 1) if color_hs is not None: color["spectrumHsv"] = { "hue": color_hs[0], "saturation": color_hs[1] / 100, "value": brightness / 255, } if features & light.SUPPORT_COLOR_TEMP: temp = self.state.attributes.get(light.ATTR_COLOR_TEMP) # Some faulty integrations might put 0 in here, raising exception. if temp == 0: _LOGGER.warning( "Entity %s has incorrect color temperature %s", self.state.entity_id, temp, ) elif temp is not None: color["temperatureK"] = color_util.color_temperature_mired_to_kelvin( temp ) response = {} if color: response["color"] = color return response async def execute(self, command, data, params, challenge): """Execute a color temperature command.""" if "temperature" in params["color"]: temp = color_util.color_temperature_kelvin_to_mired( params["color"]["temperature"] ) min_temp = self.state.attributes[light.ATTR_MIN_MIREDS] max_temp = self.state.attributes[light.ATTR_MAX_MIREDS] if temp < min_temp or temp > max_temp: raise SmartHomeError( ERR_VALUE_OUT_OF_RANGE, f"Temperature should be between {min_temp} and {max_temp}", ) await self.hass.services.async_call( light.DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: self.state.entity_id, light.ATTR_COLOR_TEMP: temp}, blocking=True, context=data.context, ) elif "spectrumRGB" in params["color"]: # Convert integer to hex format and left pad with 0's till length 6 hex_value = f"{params['color']['spectrumRGB']:06x}" color = color_util.color_RGB_to_hs( *color_util.rgb_hex_to_rgb_list(hex_value) ) await self.hass.services.async_call( light.DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: self.state.entity_id, light.ATTR_HS_COLOR: color}, blocking=True, context=data.context, ) elif "spectrumHSV" in params["color"]: color = params["color"]["spectrumHSV"] saturation = color["saturation"] * 100 brightness = color["value"] * 255 await self.hass.services.async_call( light.DOMAIN, SERVICE_TURN_ON, { ATTR_ENTITY_ID: self.state.entity_id, light.ATTR_HS_COLOR: [color["hue"], saturation], light.ATTR_BRIGHTNESS: brightness, }, blocking=True, context=data.context, ) @register_trait class SceneTrait(_Trait): """Trait to offer scene functionality. https://developers.google.com/actions/smarthome/traits/scene """ name = TRAIT_SCENE commands = [COMMAND_ACTIVATE_SCENE] @staticmethod def supported(domain, features, device_class): """Test if state is supported.""" return domain in (scene.DOMAIN, script.DOMAIN) def sync_attributes(self): """Return scene attributes for a sync request.""" # Neither supported domain can support sceneReversible return {} def query_attributes(self): """Return scene query attributes.""" return {} async def execute(self, command, data, params, challenge): """Execute a scene command.""" # Don't block for scripts as they can be slow. await self.hass.services.async_call( self.state.domain, SERVICE_TURN_ON, {ATTR_ENTITY_ID: self.state.entity_id}, blocking=self.state.domain != script.DOMAIN, context=data.context, ) @register_trait class DockTrait(_Trait): """Trait to offer dock functionality. https://developers.google.com/actions/smarthome/traits/dock """ name = TRAIT_DOCK commands = [COMMAND_DOCK] @staticmethod def supported(domain, features, device_class): """Test if state is supported.""" return domain == vacuum.DOMAIN def sync_attributes(self): """Return dock attributes for a sync request.""" return {} def query_attributes(self): """Return dock query attributes.""" return {"isDocked": self.state.state == vacuum.STATE_DOCKED} async def execute(self, command, data, params, challenge): """Execute a dock command.""" await self.hass.services.async_call( self.state.domain, vacuum.SERVICE_RETURN_TO_BASE, {ATTR_ENTITY_ID: self.state.entity_id}, blocking=True, context=data.context, ) @register_trait class StartStopTrait(_Trait): """Trait to offer StartStop functionality. https://developers.google.com/actions/smarthome/traits/startstop """ name = TRAIT_STARTSTOP commands = [COMMAND_STARTSTOP, COMMAND_PAUSEUNPAUSE] @staticmethod def supported(domain, features, device_class): """Test if state is supported.""" if domain == vacuum.DOMAIN: return True if domain == cover.DOMAIN and features & cover.SUPPORT_STOP: return True return False def sync_attributes(self): """Return StartStop attributes for a sync request.""" domain = self.state.domain if domain == vacuum.DOMAIN: return { "pausable": self.state.attributes.get(ATTR_SUPPORTED_FEATURES, 0) & vacuum.SUPPORT_PAUSE != 0 } if domain == cover.DOMAIN: return {} def query_attributes(self): """Return StartStop query attributes.""" domain = self.state.domain state = self.state.state if domain == vacuum.DOMAIN: return { "isRunning": state == vacuum.STATE_CLEANING, "isPaused": state == vacuum.STATE_PAUSED, } if domain == cover.DOMAIN: return {"isRunning": state in (cover.STATE_CLOSING, cover.STATE_OPENING)} async def execute(self, command, data, params, challenge): """Execute a StartStop command.""" domain = self.state.domain if domain == vacuum.DOMAIN: return await self._execute_vacuum(command, data, params, challenge) if domain == cover.DOMAIN: return await self._execute_cover(command, data, params, challenge) async def _execute_vacuum(self, command, data, params, challenge): """Execute a StartStop command.""" if command == COMMAND_STARTSTOP: if params["start"]: await self.hass.services.async_call( self.state.domain, vacuum.SERVICE_START, {ATTR_ENTITY_ID: self.state.entity_id}, blocking=True, context=data.context, ) else: await self.hass.services.async_call( self.state.domain, vacuum.SERVICE_STOP, {ATTR_ENTITY_ID: self.state.entity_id}, blocking=True, context=data.context, ) elif command == COMMAND_PAUSEUNPAUSE: if params["pause"]: await self.hass.services.async_call( self.state.domain, vacuum.SERVICE_PAUSE, {ATTR_ENTITY_ID: self.state.entity_id}, blocking=True, context=data.context, ) else: await self.hass.services.async_call( self.state.domain, vacuum.SERVICE_START, {ATTR_ENTITY_ID: self.state.entity_id}, blocking=True, context=data.context, ) async def _execute_cover(self, command, data, params, challenge): """Execute a StartStop command.""" if command == COMMAND_STARTSTOP: if params["start"] is False: if ( self.state.state in ( cover.STATE_CLOSING, cover.STATE_OPENING, ) or self.state.attributes.get(ATTR_ASSUMED_STATE) ): await self.hass.services.async_call( self.state.domain, cover.SERVICE_STOP_COVER, {ATTR_ENTITY_ID: self.state.entity_id}, blocking=True, context=data.context, ) else: raise SmartHomeError( ERR_ALREADY_STOPPED, "Cover is already stopped" ) else: raise SmartHomeError( ERR_NOT_SUPPORTED, "Starting a cover is not supported" ) else: raise SmartHomeError( ERR_NOT_SUPPORTED, f"Command {command} is not supported" ) @register_trait class TemperatureSettingTrait(_Trait): """Trait to offer handling both temperature point and modes functionality. https://developers.google.com/actions/smarthome/traits/temperaturesetting """ name = TRAIT_TEMPERATURE_SETTING commands = [ COMMAND_THERMOSTAT_TEMPERATURE_SETPOINT, COMMAND_THERMOSTAT_TEMPERATURE_SET_RANGE, COMMAND_THERMOSTAT_SET_MODE, ] # We do not support "on" as we are unable to know how to restore # the last mode. hvac_to_google = { climate.HVAC_MODE_HEAT: "heat", climate.HVAC_MODE_COOL: "cool", climate.HVAC_MODE_OFF: "off", climate.HVAC_MODE_AUTO: "auto", climate.HVAC_MODE_HEAT_COOL: "heatcool", climate.HVAC_MODE_FAN_ONLY: "fan-only", climate.HVAC_MODE_DRY: "dry", } google_to_hvac = {value: key for key, value in hvac_to_google.items()} preset_to_google = {climate.PRESET_ECO: "eco"} google_to_preset = {value: key for key, value in preset_to_google.items()} @staticmethod def supported(domain, features, device_class): """Test if state is supported.""" if domain == climate.DOMAIN: return True return ( domain == sensor.DOMAIN and device_class == sensor.DEVICE_CLASS_TEMPERATURE ) @property def climate_google_modes(self): """Return supported Google modes.""" modes = [] attrs = self.state.attributes for mode in attrs.get(climate.ATTR_HVAC_MODES, []): google_mode = self.hvac_to_google.get(mode) if google_mode and google_mode not in modes: modes.append(google_mode) for preset in attrs.get(climate.ATTR_PRESET_MODES, []): google_mode = self.preset_to_google.get(preset) if google_mode and google_mode not in modes: modes.append(google_mode) return modes def sync_attributes(self): """Return temperature point and modes attributes for a sync request.""" response = {} attrs = self.state.attributes domain = self.state.domain response["thermostatTemperatureUnit"] = _google_temp_unit( self.hass.config.units.temperature_unit ) if domain == sensor.DOMAIN: device_class = attrs.get(ATTR_DEVICE_CLASS) if device_class == sensor.DEVICE_CLASS_TEMPERATURE: response["queryOnlyTemperatureSetting"] = True elif domain == climate.DOMAIN: modes = self.climate_google_modes # Some integrations don't support modes (e.g. opentherm), but Google doesn't # support changing the temperature if we don't have any modes. If there's # only one Google doesn't support changing it, so the default mode here is # only cosmetic. if len(modes) == 0: modes.append("heat") if "off" in modes and any( mode in modes for mode in ("heatcool", "heat", "cool") ): modes.append("on") response["availableThermostatModes"] = modes return response def query_attributes(self): """Return temperature point and modes query attributes.""" response = {} attrs = self.state.attributes domain = self.state.domain unit = self.hass.config.units.temperature_unit if domain == sensor.DOMAIN: device_class = attrs.get(ATTR_DEVICE_CLASS) if device_class == sensor.DEVICE_CLASS_TEMPERATURE: current_temp = self.state.state if current_temp not in (STATE_UNKNOWN, STATE_UNAVAILABLE): response["thermostatTemperatureAmbient"] = round( temp_util.convert(float(current_temp), unit, TEMP_CELSIUS), 1 ) elif domain == climate.DOMAIN: operation = self.state.state preset = attrs.get(climate.ATTR_PRESET_MODE) supported = attrs.get(ATTR_SUPPORTED_FEATURES, 0) if preset in self.preset_to_google: response["thermostatMode"] = self.preset_to_google[preset] else: response["thermostatMode"] = self.hvac_to_google.get(operation) current_temp = attrs.get(climate.ATTR_CURRENT_TEMPERATURE) if current_temp is not None: response["thermostatTemperatureAmbient"] = round( temp_util.convert(current_temp, unit, TEMP_CELSIUS), 1 ) current_humidity = attrs.get(climate.ATTR_CURRENT_HUMIDITY) if current_humidity is not None: response["thermostatHumidityAmbient"] = current_humidity if operation in (climate.HVAC_MODE_AUTO, climate.HVAC_MODE_HEAT_COOL): if supported & climate.SUPPORT_TARGET_TEMPERATURE_RANGE: response["thermostatTemperatureSetpointHigh"] = round( temp_util.convert( attrs[climate.ATTR_TARGET_TEMP_HIGH], unit, TEMP_CELSIUS ), 1, ) response["thermostatTemperatureSetpointLow"] = round( temp_util.convert( attrs[climate.ATTR_TARGET_TEMP_LOW], unit, TEMP_CELSIUS ), 1, ) else: target_temp = attrs.get(ATTR_TEMPERATURE) if target_temp is not None: target_temp = round( temp_util.convert(target_temp, unit, TEMP_CELSIUS), 1 ) response["thermostatTemperatureSetpointHigh"] = target_temp response["thermostatTemperatureSetpointLow"] = target_temp else: target_temp = attrs.get(ATTR_TEMPERATURE) if target_temp is not None: response["thermostatTemperatureSetpoint"] = round( temp_util.convert(target_temp, unit, TEMP_CELSIUS), 1 ) return response async def execute(self, command, data, params, challenge): """Execute a temperature point or mode command.""" domain = self.state.domain if domain == sensor.DOMAIN: raise SmartHomeError( ERR_NOT_SUPPORTED, "Execute is not supported by sensor" ) # All sent in temperatures are always in Celsius unit = self.hass.config.units.temperature_unit min_temp = self.state.attributes[climate.ATTR_MIN_TEMP] max_temp = self.state.attributes[climate.ATTR_MAX_TEMP] if command == COMMAND_THERMOSTAT_TEMPERATURE_SETPOINT: temp = temp_util.convert( params["thermostatTemperatureSetpoint"], TEMP_CELSIUS, unit ) if unit == TEMP_FAHRENHEIT: temp = round(temp) if temp < min_temp or temp > max_temp: raise SmartHomeError( ERR_VALUE_OUT_OF_RANGE, f"Temperature should be between {min_temp} and {max_temp}", ) await self.hass.services.async_call( climate.DOMAIN, climate.SERVICE_SET_TEMPERATURE, {ATTR_ENTITY_ID: self.state.entity_id, ATTR_TEMPERATURE: temp}, blocking=True, context=data.context, ) elif command == COMMAND_THERMOSTAT_TEMPERATURE_SET_RANGE: temp_high = temp_util.convert( params["thermostatTemperatureSetpointHigh"], TEMP_CELSIUS, unit ) if unit == TEMP_FAHRENHEIT: temp_high = round(temp_high) if temp_high < min_temp or temp_high > max_temp: raise SmartHomeError( ERR_VALUE_OUT_OF_RANGE, ( f"Upper bound for temperature range should be between " f"{min_temp} and {max_temp}" ), ) temp_low = temp_util.convert( params["thermostatTemperatureSetpointLow"], TEMP_CELSIUS, unit ) if unit == TEMP_FAHRENHEIT: temp_low = round(temp_low) if temp_low < min_temp or temp_low > max_temp: raise SmartHomeError( ERR_VALUE_OUT_OF_RANGE, ( f"Lower bound for temperature range should be between " f"{min_temp} and {max_temp}" ), ) supported = self.state.attributes.get(ATTR_SUPPORTED_FEATURES) svc_data = {ATTR_ENTITY_ID: self.state.entity_id} if supported & climate.SUPPORT_TARGET_TEMPERATURE_RANGE: svc_data[climate.ATTR_TARGET_TEMP_HIGH] = temp_high svc_data[climate.ATTR_TARGET_TEMP_LOW] = temp_low else: svc_data[ATTR_TEMPERATURE] = (temp_high + temp_low) / 2 await self.hass.services.async_call( climate.DOMAIN, climate.SERVICE_SET_TEMPERATURE, svc_data, blocking=True, context=data.context, ) elif command == COMMAND_THERMOSTAT_SET_MODE: target_mode = params["thermostatMode"] supported = self.state.attributes.get(ATTR_SUPPORTED_FEATURES) if target_mode == "on": await self.hass.services.async_call( climate.DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: self.state.entity_id}, blocking=True, context=data.context, ) return if target_mode == "off": await self.hass.services.async_call( climate.DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: self.state.entity_id}, blocking=True, context=data.context, ) return if target_mode in self.google_to_preset: await self.hass.services.async_call( climate.DOMAIN, climate.SERVICE_SET_PRESET_MODE, { climate.ATTR_PRESET_MODE: self.google_to_preset[target_mode], ATTR_ENTITY_ID: self.state.entity_id, }, blocking=True, context=data.context, ) return await self.hass.services.async_call( climate.DOMAIN, climate.SERVICE_SET_HVAC_MODE, { ATTR_ENTITY_ID: self.state.entity_id, climate.ATTR_HVAC_MODE: self.google_to_hvac[target_mode], }, blocking=True, context=data.context, ) @register_trait class HumiditySettingTrait(_Trait): """Trait to offer humidity setting functionality. https://developers.google.com/actions/smarthome/traits/humiditysetting """ name = TRAIT_HUMIDITY_SETTING commands = [COMMAND_SET_HUMIDITY] @staticmethod def supported(domain, features, device_class): """Test if state is supported.""" if domain == humidifier.DOMAIN: return True return domain == sensor.DOMAIN and device_class == sensor.DEVICE_CLASS_HUMIDITY def sync_attributes(self): """Return humidity attributes for a sync request.""" response = {} attrs = self.state.attributes domain = self.state.domain if domain == sensor.DOMAIN: device_class = attrs.get(ATTR_DEVICE_CLASS) if device_class == sensor.DEVICE_CLASS_HUMIDITY: response["queryOnlyHumiditySetting"] = True elif domain == humidifier.DOMAIN: response["humiditySetpointRange"] = { "minPercent": round( float(self.state.attributes[humidifier.ATTR_MIN_HUMIDITY]) ), "maxPercent": round( float(self.state.attributes[humidifier.ATTR_MAX_HUMIDITY]) ), } return response def query_attributes(self): """Return humidity query attributes.""" response = {} attrs = self.state.attributes domain = self.state.domain if domain == sensor.DOMAIN: device_class = attrs.get(ATTR_DEVICE_CLASS) if device_class == sensor.DEVICE_CLASS_HUMIDITY: current_humidity = self.state.state if current_humidity not in (STATE_UNKNOWN, STATE_UNAVAILABLE): response["humidityAmbientPercent"] = round(float(current_humidity)) elif domain == humidifier.DOMAIN: target_humidity = attrs.get(humidifier.ATTR_HUMIDITY) if target_humidity is not None: response["humiditySetpointPercent"] = round(float(target_humidity)) return response async def execute(self, command, data, params, challenge): """Execute a humidity command.""" domain = self.state.domain if domain == sensor.DOMAIN: raise SmartHomeError( ERR_NOT_SUPPORTED, "Execute is not supported by sensor" ) if command == COMMAND_SET_HUMIDITY: await self.hass.services.async_call( humidifier.DOMAIN, humidifier.SERVICE_SET_HUMIDITY, { ATTR_ENTITY_ID: self.state.entity_id, humidifier.ATTR_HUMIDITY: params["humidity"], }, blocking=True, context=data.context, ) @register_trait class LockUnlockTrait(_Trait): """Trait to lock or unlock a lock. https://developers.google.com/actions/smarthome/traits/lockunlock """ name = TRAIT_LOCKUNLOCK commands = [COMMAND_LOCKUNLOCK] @staticmethod def supported(domain, features, device_class): """Test if state is supported.""" return domain == lock.DOMAIN @staticmethod def might_2fa(domain, features, device_class): """Return if the trait might ask for 2FA.""" return True def sync_attributes(self): """Return LockUnlock attributes for a sync request.""" return {} def query_attributes(self): """Return LockUnlock query attributes.""" return {"isLocked": self.state.state == STATE_LOCKED} async def execute(self, command, data, params, challenge): """Execute an LockUnlock command.""" if params["lock"]: service = lock.SERVICE_LOCK else: _verify_pin_challenge(data, self.state, challenge) service = lock.SERVICE_UNLOCK await self.hass.services.async_call( lock.DOMAIN, service, {ATTR_ENTITY_ID: self.state.entity_id}, blocking=True, context=data.context, ) @register_trait class ArmDisArmTrait(_Trait): """Trait to Arm or Disarm a Security System. https://developers.google.com/actions/smarthome/traits/armdisarm """ name = TRAIT_ARMDISARM commands = [COMMAND_ARMDISARM] state_to_service = { STATE_ALARM_ARMED_HOME: SERVICE_ALARM_ARM_HOME, STATE_ALARM_ARMED_AWAY: SERVICE_ALARM_ARM_AWAY, STATE_ALARM_ARMED_NIGHT: SERVICE_ALARM_ARM_NIGHT, STATE_ALARM_ARMED_CUSTOM_BYPASS: SERVICE_ALARM_ARM_CUSTOM_BYPASS, STATE_ALARM_TRIGGERED: SERVICE_ALARM_TRIGGER, } state_to_support = { STATE_ALARM_ARMED_HOME: alarm_control_panel.const.SUPPORT_ALARM_ARM_HOME, STATE_ALARM_ARMED_AWAY: alarm_control_panel.const.SUPPORT_ALARM_ARM_AWAY, STATE_ALARM_ARMED_NIGHT: alarm_control_panel.const.SUPPORT_ALARM_ARM_NIGHT, STATE_ALARM_ARMED_CUSTOM_BYPASS: alarm_control_panel.const.SUPPORT_ALARM_ARM_CUSTOM_BYPASS, STATE_ALARM_TRIGGERED: alarm_control_panel.const.SUPPORT_ALARM_TRIGGER, } @staticmethod def supported(domain, features, device_class): """Test if state is supported.""" return domain == alarm_control_panel.DOMAIN @staticmethod def might_2fa(domain, features, device_class): """Return if the trait might ask for 2FA.""" return True def _supported_states(self): """Return supported states.""" features = self.state.attributes.get(ATTR_SUPPORTED_FEATURES, 0) return [ state for state, required_feature in self.state_to_support.items() if features & required_feature != 0 ] def sync_attributes(self): """Return ArmDisarm attributes for a sync request.""" response = {} levels = [] for state in self._supported_states(): # level synonyms are generated from state names # 'armed_away' becomes 'armed away' or 'away' level_synonym = [state.replace("_", " ")] if state != STATE_ALARM_TRIGGERED: level_synonym.append(state.split("_")[1]) level = { "level_name": state, "level_values": [{"level_synonym": level_synonym, "lang": "en"}], } levels.append(level) response["availableArmLevels"] = {"levels": levels, "ordered": False} return response def query_attributes(self): """Return ArmDisarm query attributes.""" if "next_state" in self.state.attributes: armed_state = self.state.attributes["next_state"] else: armed_state = self.state.state response = {"isArmed": armed_state in self.state_to_service} if response["isArmed"]: response.update({"currentArmLevel": armed_state}) return response async def execute(self, command, data, params, challenge): """Execute an ArmDisarm command.""" if params["arm"] and not params.get("cancel"): arm_level = params.get("armLevel") # If no arm level given, we can only arm it if there is # only one supported arm type. We never default to triggered. if not arm_level: states = self._supported_states() if STATE_ALARM_TRIGGERED in states: states.remove(STATE_ALARM_TRIGGERED) if len(states) != 1: raise SmartHomeError(ERR_NOT_SUPPORTED, "ArmLevel missing") arm_level = states[0] if self.state.state == arm_level: raise SmartHomeError(ERR_ALREADY_ARMED, "System is already armed") if self.state.attributes["code_arm_required"]: _verify_pin_challenge(data, self.state, challenge) service = self.state_to_service[arm_level] # disarm the system without asking for code when # 'cancel' arming action is received while current status is pending elif ( params["arm"] and params.get("cancel") and self.state.state == STATE_ALARM_PENDING ): service = SERVICE_ALARM_DISARM else: if self.state.state == STATE_ALARM_DISARMED: raise SmartHomeError(ERR_ALREADY_DISARMED, "System is already disarmed") _verify_pin_challenge(data, self.state, challenge) service = SERVICE_ALARM_DISARM await self.hass.services.async_call( alarm_control_panel.DOMAIN, service, { ATTR_ENTITY_ID: self.state.entity_id, ATTR_CODE: data.config.secure_devices_pin, }, blocking=True, context=data.context, ) @register_trait class FanSpeedTrait(_Trait): """Trait to control speed of Fan. https://developers.google.com/actions/smarthome/traits/fanspeed """ name = TRAIT_FANSPEED commands = [COMMAND_FANSPEED] speed_synonyms = { fan.SPEED_OFF: ["stop", "off"], fan.SPEED_LOW: ["slow", "low", "slowest", "lowest"], fan.SPEED_MEDIUM: ["medium", "mid", "middle"], fan.SPEED_HIGH: ["high", "max", "fast", "highest", "fastest", "maximum"], } @staticmethod def supported(domain, features, device_class): """Test if state is supported.""" if domain == fan.DOMAIN: return features & fan.SUPPORT_SET_SPEED if domain == climate.DOMAIN: return features & climate.SUPPORT_FAN_MODE return False def sync_attributes(self): """Return speed point and modes attributes for a sync request.""" domain = self.state.domain speeds = [] reversible = False if domain == fan.DOMAIN: modes = self.state.attributes.get(fan.ATTR_SPEED_LIST, []) for mode in modes: if mode not in self.speed_synonyms: continue speed = { "speed_name": mode, "speed_values": [ {"speed_synonym": self.speed_synonyms.get(mode), "lang": "en"} ], } speeds.append(speed) reversible = bool( self.state.attributes.get(ATTR_SUPPORTED_FEATURES, 0) & fan.SUPPORT_DIRECTION ) elif domain == climate.DOMAIN: modes = self.state.attributes.get(climate.ATTR_FAN_MODES, []) for mode in modes: speed = { "speed_name": mode, "speed_values": [{"speed_synonym": [mode], "lang": "en"}], } speeds.append(speed) return { "availableFanSpeeds": {"speeds": speeds, "ordered": True}, "reversible": reversible, "supportsFanSpeedPercent": True, } def query_attributes(self): """Return speed point and modes query attributes.""" attrs = self.state.attributes domain = self.state.domain response = {} if domain == climate.DOMAIN: speed = attrs.get(climate.ATTR_FAN_MODE) if speed is not None: response["currentFanSpeedSetting"] = speed if domain == fan.DOMAIN: speed = attrs.get(fan.ATTR_SPEED) percent = attrs.get(fan.ATTR_PERCENTAGE) or 0 if speed is not None: response["on"] = speed != fan.SPEED_OFF response["currentFanSpeedSetting"] = speed response["currentFanSpeedPercent"] = percent return response async def execute(self, command, data, params, challenge): """Execute an SetFanSpeed command.""" domain = self.state.domain if domain == climate.DOMAIN: await self.hass.services.async_call( climate.DOMAIN, climate.SERVICE_SET_FAN_MODE, { ATTR_ENTITY_ID: self.state.entity_id, climate.ATTR_FAN_MODE: params["fanSpeed"], }, blocking=True, context=data.context, ) if domain == fan.DOMAIN: service_params = { ATTR_ENTITY_ID: self.state.entity_id, } if "fanSpeedPercent" in params: service = fan.SERVICE_SET_PERCENTAGE service_params[fan.ATTR_PERCENTAGE] = params["fanSpeedPercent"] else: service = fan.SERVICE_SET_SPEED service_params[fan.ATTR_SPEED] = params["fanSpeed"] await self.hass.services.async_call( fan.DOMAIN, service, service_params, blocking=True, context=data.context, ) @register_trait class ModesTrait(_Trait): """Trait to set modes. https://developers.google.com/actions/smarthome/traits/modes """ name = TRAIT_MODES commands = [COMMAND_MODES] SYNONYMS = { "sound mode": ["sound mode", "effects"], "option": ["option", "setting", "mode", "value"], } @staticmethod def supported(domain, features, device_class): """Test if state is supported.""" if domain == input_select.DOMAIN: return True if domain == humidifier.DOMAIN and features & humidifier.SUPPORT_MODES: return True if domain == light.DOMAIN and features & light.SUPPORT_EFFECT: return True if domain != media_player.DOMAIN: return False return features & media_player.SUPPORT_SELECT_SOUND_MODE def _generate(self, name, settings): """Generate a list of modes.""" mode = { "name": name, "name_values": [ {"name_synonym": self.SYNONYMS.get(name, [name]), "lang": "en"} ], "settings": [], "ordered": False, } for setting in settings: mode["settings"].append( { "setting_name": setting, "setting_values": [ { "setting_synonym": self.SYNONYMS.get(setting, [setting]), "lang": "en", } ], } ) return mode def sync_attributes(self): """Return mode attributes for a sync request.""" modes = [] for domain, attr, name in ( (media_player.DOMAIN, media_player.ATTR_SOUND_MODE_LIST, "sound mode"), (input_select.DOMAIN, input_select.ATTR_OPTIONS, "option"), (humidifier.DOMAIN, humidifier.ATTR_AVAILABLE_MODES, "mode"), (light.DOMAIN, light.ATTR_EFFECT_LIST, "effect"), ): if self.state.domain != domain: continue items = self.state.attributes.get(attr) if items is not None: modes.append(self._generate(name, items)) # Shortcut since all domains are currently unique break payload = {"availableModes": modes} return payload def query_attributes(self): """Return current modes.""" attrs = self.state.attributes response = {} mode_settings = {} if self.state.domain == media_player.DOMAIN: if media_player.ATTR_SOUND_MODE_LIST in attrs: mode_settings["sound mode"] = attrs.get(media_player.ATTR_SOUND_MODE) elif self.state.domain == input_select.DOMAIN: mode_settings["option"] = self.state.state elif self.state.domain == humidifier.DOMAIN: if ATTR_MODE in attrs: mode_settings["mode"] = attrs.get(ATTR_MODE) elif self.state.domain == light.DOMAIN and light.ATTR_EFFECT in attrs: mode_settings["effect"] = attrs.get(light.ATTR_EFFECT) if mode_settings: response["on"] = self.state.state not in (STATE_OFF, STATE_UNKNOWN) response["currentModeSettings"] = mode_settings return response async def execute(self, command, data, params, challenge): """Execute a SetModes command.""" settings = params.get("updateModeSettings") if self.state.domain == input_select.DOMAIN: option = params["updateModeSettings"]["option"] await self.hass.services.async_call( input_select.DOMAIN, input_select.SERVICE_SELECT_OPTION, { ATTR_ENTITY_ID: self.state.entity_id, input_select.ATTR_OPTION: option, }, blocking=True, context=data.context, ) return if self.state.domain == humidifier.DOMAIN: requested_mode = settings["mode"] await self.hass.services.async_call( humidifier.DOMAIN, humidifier.SERVICE_SET_MODE, { ATTR_MODE: requested_mode, ATTR_ENTITY_ID: self.state.entity_id, }, blocking=True, context=data.context, ) return if self.state.domain == light.DOMAIN: requested_effect = settings["effect"] await self.hass.services.async_call( light.DOMAIN, SERVICE_TURN_ON, { ATTR_ENTITY_ID: self.state.entity_id, light.ATTR_EFFECT: requested_effect, }, blocking=True, context=data.context, ) return if self.state.domain != media_player.DOMAIN: _LOGGER.info( "Received an Options command for unrecognised domain %s", self.state.domain, ) return sound_mode = settings.get("sound mode") if sound_mode: await self.hass.services.async_call( media_player.DOMAIN, media_player.SERVICE_SELECT_SOUND_MODE, { ATTR_ENTITY_ID: self.state.entity_id, media_player.ATTR_SOUND_MODE: sound_mode, }, blocking=True, context=data.context, ) @register_trait class InputSelectorTrait(_Trait): """Trait to set modes. https://developers.google.com/assistant/smarthome/traits/inputselector """ name = TRAIT_INPUTSELECTOR commands = [COMMAND_INPUT, COMMAND_NEXT_INPUT, COMMAND_PREVIOUS_INPUT] SYNONYMS = {} @staticmethod def supported(domain, features, device_class): """Test if state is supported.""" if domain == media_player.DOMAIN and ( features & media_player.SUPPORT_SELECT_SOURCE ): return True return False def sync_attributes(self): """Return mode attributes for a sync request.""" attrs = self.state.attributes inputs = [ {"key": source, "names": [{"name_synonym": [source], "lang": "en"}]} for source in attrs.get(media_player.ATTR_INPUT_SOURCE_LIST, []) ] payload = {"availableInputs": inputs, "orderedInputs": True} return payload def query_attributes(self): """Return current modes.""" attrs = self.state.attributes return {"currentInput": attrs.get(media_player.ATTR_INPUT_SOURCE, "")} async def execute(self, command, data, params, challenge): """Execute an SetInputSource command.""" sources = self.state.attributes.get(media_player.ATTR_INPUT_SOURCE_LIST) or [] source = self.state.attributes.get(media_player.ATTR_INPUT_SOURCE) if command == COMMAND_INPUT: requested_source = params.get("newInput") elif command == COMMAND_NEXT_INPUT: requested_source = _next_selected(sources, source) elif command == COMMAND_PREVIOUS_INPUT: requested_source = _next_selected(list(reversed(sources)), source) else: raise SmartHomeError(ERR_NOT_SUPPORTED, "Unsupported command") if requested_source not in sources: raise SmartHomeError(ERR_UNSUPPORTED_INPUT, "Unsupported input") await self.hass.services.async_call( media_player.DOMAIN, media_player.SERVICE_SELECT_SOURCE, { ATTR_ENTITY_ID: self.state.entity_id, media_player.ATTR_INPUT_SOURCE: requested_source, }, blocking=True, context=data.context, ) @register_trait class OpenCloseTrait(_Trait): """Trait to open and close a cover. https://developers.google.com/actions/smarthome/traits/openclose """ # Cover device classes that require 2FA COVER_2FA = ( cover.DEVICE_CLASS_DOOR, cover.DEVICE_CLASS_GARAGE, cover.DEVICE_CLASS_GATE, ) name = TRAIT_OPENCLOSE commands = [COMMAND_OPENCLOSE, COMMAND_OPENCLOSE_RELATIVE] @staticmethod def supported(domain, features, device_class): """Test if state is supported.""" if domain == cover.DOMAIN: return True return domain == binary_sensor.DOMAIN and device_class in ( binary_sensor.DEVICE_CLASS_DOOR, binary_sensor.DEVICE_CLASS_GARAGE_DOOR, binary_sensor.DEVICE_CLASS_LOCK, binary_sensor.DEVICE_CLASS_OPENING, binary_sensor.DEVICE_CLASS_WINDOW, ) @staticmethod def might_2fa(domain, features, device_class): """Return if the trait might ask for 2FA.""" return domain == cover.DOMAIN and device_class in OpenCloseTrait.COVER_2FA def sync_attributes(self): """Return opening direction.""" response = {} features = self.state.attributes.get(ATTR_SUPPORTED_FEATURES, 0) if self.state.domain == binary_sensor.DOMAIN: response["queryOnlyOpenClose"] = True response["discreteOnlyOpenClose"] = True elif ( self.state.domain == cover.DOMAIN and features & cover.SUPPORT_SET_POSITION == 0 ): response["discreteOnlyOpenClose"] = True if ( features & cover.SUPPORT_OPEN == 0 and features & cover.SUPPORT_CLOSE == 0 ): response["queryOnlyOpenClose"] = True if self.state.attributes.get(ATTR_ASSUMED_STATE): response["commandOnlyOpenClose"] = True return response def query_attributes(self): """Return state query attributes.""" domain = self.state.domain response = {} # When it's an assumed state, we will return empty state # This shouldn't happen because we set `commandOnlyOpenClose` # but Google still queries. Erroring here will cause device # to show up offline. if self.state.attributes.get(ATTR_ASSUMED_STATE): return response if domain == cover.DOMAIN: if self.state.state == STATE_UNKNOWN: raise SmartHomeError( ERR_NOT_SUPPORTED, "Querying state is not supported" ) position = self.state.attributes.get(cover.ATTR_CURRENT_POSITION) if position is not None: response["openPercent"] = position elif self.state.state != cover.STATE_CLOSED: response["openPercent"] = 100 else: response["openPercent"] = 0 elif domain == binary_sensor.DOMAIN: if self.state.state == STATE_ON: response["openPercent"] = 100 else: response["openPercent"] = 0 return response async def execute(self, command, data, params, challenge): """Execute an Open, close, Set position command.""" domain = self.state.domain features = self.state.attributes.get(ATTR_SUPPORTED_FEATURES, 0) if domain == cover.DOMAIN: svc_params = {ATTR_ENTITY_ID: self.state.entity_id} should_verify = False if command == COMMAND_OPENCLOSE_RELATIVE: position = self.state.attributes.get(cover.ATTR_CURRENT_POSITION) if position is None: raise SmartHomeError( ERR_NOT_SUPPORTED, "Current position not know for relative command", ) position = max(0, min(100, position + params["openRelativePercent"])) else: position = params["openPercent"] if position == 0: service = cover.SERVICE_CLOSE_COVER should_verify = False elif position == 100: service = cover.SERVICE_OPEN_COVER should_verify = True elif features & cover.SUPPORT_SET_POSITION: service = cover.SERVICE_SET_COVER_POSITION if position > 0: should_verify = True svc_params[cover.ATTR_POSITION] = position else: raise SmartHomeError( ERR_NOT_SUPPORTED, "No support for partial open close" ) if ( should_verify and self.state.attributes.get(ATTR_DEVICE_CLASS) in OpenCloseTrait.COVER_2FA ): _verify_pin_challenge(data, self.state, challenge) await self.hass.services.async_call( cover.DOMAIN, service, svc_params, blocking=True, context=data.context ) @register_trait class VolumeTrait(_Trait): """Trait to control volume of a device. https://developers.google.com/actions/smarthome/traits/volume """ name = TRAIT_VOLUME commands = [COMMAND_SET_VOLUME, COMMAND_VOLUME_RELATIVE, COMMAND_MUTE] @staticmethod def supported(domain, features, device_class): """Test if trait is supported.""" if domain == media_player.DOMAIN: return features & ( media_player.SUPPORT_VOLUME_SET | media_player.SUPPORT_VOLUME_STEP ) return False def sync_attributes(self): """Return volume attributes for a sync request.""" features = self.state.attributes.get(ATTR_SUPPORTED_FEATURES, 0) return { "volumeCanMuteAndUnmute": bool(features & media_player.SUPPORT_VOLUME_MUTE), "commandOnlyVolume": self.state.attributes.get(ATTR_ASSUMED_STATE, False), # Volume amounts in SET_VOLUME and VOLUME_RELATIVE are on a scale # from 0 to this value. "volumeMaxLevel": 100, # Default change for queries like "Hey Google, volume up". # 10% corresponds to the default behavior for the # media_player.volume{up,down} services. "levelStepSize": 10, } def query_attributes(self): """Return volume query attributes.""" response = {} level = self.state.attributes.get(media_player.ATTR_MEDIA_VOLUME_LEVEL) if level is not None: # Convert 0.0-1.0 to 0-100 response["currentVolume"] = int(level * 100) muted = self.state.attributes.get(media_player.ATTR_MEDIA_VOLUME_MUTED) if muted is not None: response["isMuted"] = bool(muted) return response async def _set_volume_absolute(self, data, level): await self.hass.services.async_call( media_player.DOMAIN, media_player.SERVICE_VOLUME_SET, { ATTR_ENTITY_ID: self.state.entity_id, media_player.ATTR_MEDIA_VOLUME_LEVEL: level, }, blocking=True, context=data.context, ) async def _execute_set_volume(self, data, params): level = max(0, min(100, params["volumeLevel"])) if not ( self.state.attributes.get(ATTR_SUPPORTED_FEATURES, 0) & media_player.SUPPORT_VOLUME_SET ): raise SmartHomeError(ERR_NOT_SUPPORTED, "Command not supported") await self._set_volume_absolute(data, level / 100) async def _execute_volume_relative(self, data, params): relative = params["relativeSteps"] features = self.state.attributes.get(ATTR_SUPPORTED_FEATURES, 0) if features & media_player.SUPPORT_VOLUME_SET: current = self.state.attributes.get(media_player.ATTR_MEDIA_VOLUME_LEVEL) target = max(0.0, min(1.0, current + relative / 100)) await self._set_volume_absolute(data, target) elif features & media_player.SUPPORT_VOLUME_STEP: svc = media_player.SERVICE_VOLUME_UP if relative < 0: svc = media_player.SERVICE_VOLUME_DOWN relative = -relative for _ in range(relative): await self.hass.services.async_call( media_player.DOMAIN, svc, {ATTR_ENTITY_ID: self.state.entity_id}, blocking=True, context=data.context, ) else: raise SmartHomeError(ERR_NOT_SUPPORTED, "Command not supported") async def _execute_mute(self, data, params): mute = params["mute"] if not ( self.state.attributes.get(ATTR_SUPPORTED_FEATURES, 0) & media_player.SUPPORT_VOLUME_MUTE ): raise SmartHomeError(ERR_NOT_SUPPORTED, "Command not supported") await self.hass.services.async_call( media_player.DOMAIN, media_player.SERVICE_VOLUME_MUTE, { ATTR_ENTITY_ID: self.state.entity_id, media_player.ATTR_MEDIA_VOLUME_MUTED: mute, }, blocking=True, context=data.context, ) async def execute(self, command, data, params, challenge): """Execute a volume command.""" if command == COMMAND_SET_VOLUME: await self._execute_set_volume(data, params) elif command == COMMAND_VOLUME_RELATIVE: await self._execute_volume_relative(data, params) elif command == COMMAND_MUTE: await self._execute_mute(data, params) else: raise SmartHomeError(ERR_NOT_SUPPORTED, "Command not supported") def _verify_pin_challenge(data, state, challenge): """Verify a pin challenge.""" if not data.config.should_2fa(state): return if not data.config.secure_devices_pin: raise SmartHomeError(ERR_CHALLENGE_NOT_SETUP, "Challenge is not set up") if not challenge: raise ChallengeNeeded(CHALLENGE_PIN_NEEDED) pin = challenge.get("pin") if pin != data.config.secure_devices_pin: raise ChallengeNeeded(CHALLENGE_FAILED_PIN_NEEDED) def _verify_ack_challenge(data, state, challenge): """Verify an ack challenge.""" if not data.config.should_2fa(state): return if not challenge or not challenge.get("ack"): raise ChallengeNeeded(CHALLENGE_ACK_NEEDED) MEDIA_COMMAND_SUPPORT_MAPPING = { COMMAND_MEDIA_NEXT: media_player.SUPPORT_NEXT_TRACK, COMMAND_MEDIA_PAUSE: media_player.SUPPORT_PAUSE, COMMAND_MEDIA_PREVIOUS: media_player.SUPPORT_PREVIOUS_TRACK, COMMAND_MEDIA_RESUME: media_player.SUPPORT_PLAY, COMMAND_MEDIA_SEEK_RELATIVE: media_player.SUPPORT_SEEK, COMMAND_MEDIA_SEEK_TO_POSITION: media_player.SUPPORT_SEEK, COMMAND_MEDIA_SHUFFLE: media_player.SUPPORT_SHUFFLE_SET, COMMAND_MEDIA_STOP: media_player.SUPPORT_STOP, } MEDIA_COMMAND_ATTRIBUTES = { COMMAND_MEDIA_NEXT: "NEXT", COMMAND_MEDIA_PAUSE: "PAUSE", COMMAND_MEDIA_PREVIOUS: "PREVIOUS", COMMAND_MEDIA_RESUME: "RESUME", COMMAND_MEDIA_SEEK_RELATIVE: "SEEK_RELATIVE", COMMAND_MEDIA_SEEK_TO_POSITION: "SEEK_TO_POSITION", COMMAND_MEDIA_SHUFFLE: "SHUFFLE", COMMAND_MEDIA_STOP: "STOP", } @register_trait class TransportControlTrait(_Trait): """Trait to control media playback. https://developers.google.com/actions/smarthome/traits/transportcontrol """ name = TRAIT_TRANSPORT_CONTROL commands = [ COMMAND_MEDIA_NEXT, COMMAND_MEDIA_PAUSE, COMMAND_MEDIA_PREVIOUS, COMMAND_MEDIA_RESUME, COMMAND_MEDIA_SEEK_RELATIVE, COMMAND_MEDIA_SEEK_TO_POSITION, COMMAND_MEDIA_SHUFFLE, COMMAND_MEDIA_STOP, ] @staticmethod def supported(domain, features, device_class): """Test if state is supported.""" if domain == media_player.DOMAIN: for feature in MEDIA_COMMAND_SUPPORT_MAPPING.values(): if features & feature: return True return False def sync_attributes(self): """Return opening direction.""" response = {} if self.state.domain == media_player.DOMAIN: features = self.state.attributes.get(ATTR_SUPPORTED_FEATURES, 0) support = [] for command, feature in MEDIA_COMMAND_SUPPORT_MAPPING.items(): if features & feature: support.append(MEDIA_COMMAND_ATTRIBUTES[command]) response["transportControlSupportedCommands"] = support return response def query_attributes(self): """Return the attributes of this trait for this entity.""" return {} async def execute(self, command, data, params, challenge): """Execute a media command.""" service_attrs = {ATTR_ENTITY_ID: self.state.entity_id} if command == COMMAND_MEDIA_SEEK_RELATIVE: service = media_player.SERVICE_MEDIA_SEEK rel_position = params["relativePositionMs"] / 1000 seconds_since = 0 # Default to 0 seconds if self.state.state == STATE_PLAYING: now = dt.utcnow() upd_at = self.state.attributes.get( media_player.ATTR_MEDIA_POSITION_UPDATED_AT, now ) seconds_since = (now - upd_at).total_seconds() position = self.state.attributes.get(media_player.ATTR_MEDIA_POSITION, 0) max_position = self.state.attributes.get( media_player.ATTR_MEDIA_DURATION, 0 ) service_attrs[media_player.ATTR_MEDIA_SEEK_POSITION] = min( max(position + seconds_since + rel_position, 0), max_position ) elif command == COMMAND_MEDIA_SEEK_TO_POSITION: service = media_player.SERVICE_MEDIA_SEEK max_position = self.state.attributes.get( media_player.ATTR_MEDIA_DURATION, 0 ) service_attrs[media_player.ATTR_MEDIA_SEEK_POSITION] = min( max(params["absPositionMs"] / 1000, 0), max_position ) elif command == COMMAND_MEDIA_NEXT: service = media_player.SERVICE_MEDIA_NEXT_TRACK elif command == COMMAND_MEDIA_PAUSE: service = media_player.SERVICE_MEDIA_PAUSE elif command == COMMAND_MEDIA_PREVIOUS: service = media_player.SERVICE_MEDIA_PREVIOUS_TRACK elif command == COMMAND_MEDIA_RESUME: service = media_player.SERVICE_MEDIA_PLAY elif command == COMMAND_MEDIA_SHUFFLE: service = media_player.SERVICE_SHUFFLE_SET # Google Assistant only supports enabling shuffle service_attrs[media_player.ATTR_MEDIA_SHUFFLE] = True elif command == COMMAND_MEDIA_STOP: service = media_player.SERVICE_MEDIA_STOP else: raise SmartHomeError(ERR_NOT_SUPPORTED, "Command not supported") await self.hass.services.async_call( media_player.DOMAIN, service, service_attrs, blocking=True, context=data.context, ) @register_trait class MediaStateTrait(_Trait): """Trait to get media playback state. https://developers.google.com/actions/smarthome/traits/mediastate """ name = TRAIT_MEDIA_STATE commands = [] activity_lookup = { STATE_OFF: "INACTIVE", STATE_IDLE: "STANDBY", STATE_PLAYING: "ACTIVE", STATE_ON: "STANDBY", STATE_PAUSED: "STANDBY", STATE_STANDBY: "STANDBY", STATE_UNAVAILABLE: "INACTIVE", STATE_UNKNOWN: "INACTIVE", } playback_lookup = { STATE_OFF: "STOPPED", STATE_IDLE: "STOPPED", STATE_PLAYING: "PLAYING", STATE_ON: "STOPPED", STATE_PAUSED: "PAUSED", STATE_STANDBY: "STOPPED", STATE_UNAVAILABLE: "STOPPED", STATE_UNKNOWN: "STOPPED", } @staticmethod def supported(domain, features, device_class): """Test if state is supported.""" return domain == media_player.DOMAIN def sync_attributes(self): """Return attributes for a sync request.""" return {"supportActivityState": True, "supportPlaybackState": True} def query_attributes(self): """Return the attributes of this trait for this entity.""" return { "activityState": self.activity_lookup.get(self.state.state, "INACTIVE"), "playbackState": self.playback_lookup.get(self.state.state, "STOPPED"), }
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/google_assistant/trait.py
"""Support for Z-Wave lights.""" from __future__ import annotations import logging from typing import Any, Callable from zwave_js_server.client import Client as ZwaveClient from zwave_js_server.const import ColorComponent, CommandClass from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, ATTR_TRANSITION, ATTR_WHITE_VALUE, DOMAIN as LIGHT_DOMAIN, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP, SUPPORT_TRANSITION, SUPPORT_WHITE_VALUE, LightEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.dispatcher import async_dispatcher_connect import homeassistant.util.color as color_util from .const import DATA_CLIENT, DATA_UNSUBSCRIBE, DOMAIN from .discovery import ZwaveDiscoveryInfo from .entity import ZWaveBaseEntity LOGGER = logging.getLogger(__name__) MULTI_COLOR_MAP = { ColorComponent.WARM_WHITE: "warmWhite", ColorComponent.COLD_WHITE: "coldWhite", ColorComponent.RED: "red", ColorComponent.GREEN: "green", ColorComponent.BLUE: "blue", ColorComponent.AMBER: "amber", ColorComponent.CYAN: "cyan", ColorComponent.PURPLE: "purple", } async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: Callable ) -> None: """Set up Z-Wave Light from Config Entry.""" client: ZwaveClient = hass.data[DOMAIN][config_entry.entry_id][DATA_CLIENT] @callback def async_add_light(info: ZwaveDiscoveryInfo) -> None: """Add Z-Wave Light.""" light = ZwaveLight(config_entry, client, info) async_add_entities([light]) hass.data[DOMAIN][config_entry.entry_id][DATA_UNSUBSCRIBE].append( async_dispatcher_connect( hass, f"{DOMAIN}_{config_entry.entry_id}_add_{LIGHT_DOMAIN}", async_add_light, ) ) def byte_to_zwave_brightness(value: int) -> int: """Convert brightness in 0-255 scale to 0-99 scale. `value` -- (int) Brightness byte value from 0-255. """ if value > 0: return max(1, round((value / 255) * 99)) return 0 class ZwaveLight(ZWaveBaseEntity, LightEntity): """Representation of a Z-Wave light.""" def __init__( self, config_entry: ConfigEntry, client: ZwaveClient, info: ZwaveDiscoveryInfo ) -> None: """Initialize the light.""" super().__init__(config_entry, client, info) self._supports_color = False self._supports_white_value = False self._supports_color_temp = False self._hs_color: tuple[float, float] | None = None self._white_value: int | None = None self._color_temp: int | None = None self._min_mireds = 153 # 6500K as a safe default self._max_mireds = 370 # 2700K as a safe default self._supported_features = SUPPORT_BRIGHTNESS # get additional (optional) values and set features self._target_value = self.get_zwave_value("targetValue") self._dimming_duration = self.get_zwave_value("duration") if self._dimming_duration is not None: self._supported_features |= SUPPORT_TRANSITION self._calculate_color_values() if self._supports_color: self._supported_features |= SUPPORT_COLOR if self._supports_color_temp: self._supported_features |= SUPPORT_COLOR_TEMP if self._supports_white_value: self._supported_features |= SUPPORT_WHITE_VALUE @callback def on_value_update(self) -> None: """Call when a watched value is added or updated.""" self._calculate_color_values() @property def brightness(self) -> int: """Return the brightness of this light between 0..255. Z-Wave multilevel switches use a range of [0, 99] to control brightness. """ if self.info.primary_value.value is not None: return round((self.info.primary_value.value / 99) * 255) return 0 @property def is_on(self) -> bool: """Return true if device is on (brightness above 0).""" return self.brightness > 0 @property def hs_color(self) -> tuple[float, float] | None: """Return the hs color.""" return self._hs_color @property def white_value(self) -> int | None: """Return the white value of this light between 0..255.""" return self._white_value @property def color_temp(self) -> int | None: """Return the color temperature.""" return self._color_temp @property def min_mireds(self) -> int: """Return the coldest color_temp that this light supports.""" return self._min_mireds @property def max_mireds(self) -> int: """Return the warmest color_temp that this light supports.""" return self._max_mireds @property def supported_features(self) -> int: """Flag supported features.""" return self._supported_features async def async_turn_on(self, **kwargs: Any) -> None: """Turn the device on.""" # RGB/HS color hs_color = kwargs.get(ATTR_HS_COLOR) if hs_color is not None and self._supports_color: red, green, blue = color_util.color_hs_to_RGB(*hs_color) colors = { ColorComponent.RED: red, ColorComponent.GREEN: green, ColorComponent.BLUE: blue, } if self._supports_color_temp: # turn of white leds when setting rgb colors[ColorComponent.WARM_WHITE] = 0 colors[ColorComponent.COLD_WHITE] = 0 await self._async_set_colors(colors) # Color temperature color_temp = kwargs.get(ATTR_COLOR_TEMP) if color_temp is not None and self._supports_color_temp: # Limit color temp to min/max values cold = max( 0, min( 255, round( (self._max_mireds - color_temp) / (self._max_mireds - self._min_mireds) * 255 ), ), ) warm = 255 - cold await self._async_set_colors( { # turn off color leds when setting color temperature ColorComponent.RED: 0, ColorComponent.GREEN: 0, ColorComponent.BLUE: 0, ColorComponent.WARM_WHITE: warm, ColorComponent.COLD_WHITE: cold, } ) # White value white_value = kwargs.get(ATTR_WHITE_VALUE) if white_value is not None and self._supports_white_value: # white led brightness is controlled by white level # rgb leds (if any) can be on at the same time await self._async_set_colors( { ColorComponent.WARM_WHITE: white_value, ColorComponent.COLD_WHITE: white_value, } ) # set brightness await self._async_set_brightness( kwargs.get(ATTR_BRIGHTNESS), kwargs.get(ATTR_TRANSITION) ) async def async_turn_off(self, **kwargs: Any) -> None: """Turn the light off.""" await self._async_set_brightness(0, kwargs.get(ATTR_TRANSITION)) async def _async_set_colors(self, colors: dict[ColorComponent, int]) -> None: """Set (multiple) defined colors to given value(s).""" # prefer the (new) combined color property # https://github.com/zwave-js/node-zwave-js/pull/1782 combined_color_val = self.get_zwave_value( "targetColor", CommandClass.SWITCH_COLOR, value_property_key=None, ) if combined_color_val and isinstance(combined_color_val.value, dict): colors_dict = {} for color, value in colors.items(): color_name = MULTI_COLOR_MAP[color] colors_dict[color_name] = value # set updated color object await self.info.node.async_set_value(combined_color_val, colors_dict) return # fallback to setting the color(s) one by one if multicolor fails # not sure this is needed at all, but just in case for color, value in colors.items(): await self._async_set_color(color, value) async def _async_set_color(self, color: ColorComponent, new_value: int) -> None: """Set defined color to given value.""" # actually set the new color value target_zwave_value = self.get_zwave_value( "targetColor", CommandClass.SWITCH_COLOR, value_property_key=color.value, ) if target_zwave_value is None: # guard for unsupported color return await self.info.node.async_set_value(target_zwave_value, new_value) async def _async_set_brightness( self, brightness: int | None, transition: int | None = None ) -> None: """Set new brightness to light.""" if brightness is None: # Level 255 means to set it to previous value. zwave_brightness = 255 else: # Zwave multilevel switches use a range of [0, 99] to control brightness. zwave_brightness = byte_to_zwave_brightness(brightness) # set transition value before sending new brightness await self._async_set_transition_duration(transition) # setting a value requires setting targetValue await self.info.node.async_set_value(self._target_value, zwave_brightness) async def _async_set_transition_duration(self, duration: int | None = None) -> None: """Set the transition time for the brightness value.""" if self._dimming_duration is None: return # pylint: disable=fixme,unreachable # TODO: setting duration needs to be fixed upstream # https://github.com/zwave-js/node-zwave-js/issues/1321 return if duration is None: # type: ignore # no transition specified by user, use defaults duration = 7621 # anything over 7620 uses the factory default else: # pragma: no cover # transition specified by user transition = duration if transition <= 127: duration = transition else: minutes = round(transition / 60) LOGGER.debug( "Transition rounded to %d minutes for %s", minutes, self.entity_id, ) duration = minutes + 128 # only send value if it differs from current # this prevents sending a command for nothing if self._dimming_duration.value != duration: # pragma: no cover await self.info.node.async_set_value(self._dimming_duration, duration) @callback def _calculate_color_values(self) -> None: """Calculate light colors.""" # NOTE: We lookup all values here (instead of relying on the multicolor one) # to find out what colors are supported # as this is a simple lookup by key, this not heavy red_val = self.get_zwave_value( "currentColor", CommandClass.SWITCH_COLOR, value_property_key=ColorComponent.RED.value, ) green_val = self.get_zwave_value( "currentColor", CommandClass.SWITCH_COLOR, value_property_key=ColorComponent.GREEN.value, ) blue_val = self.get_zwave_value( "currentColor", CommandClass.SWITCH_COLOR, value_property_key=ColorComponent.BLUE.value, ) ww_val = self.get_zwave_value( "currentColor", CommandClass.SWITCH_COLOR, value_property_key=ColorComponent.WARM_WHITE.value, ) cw_val = self.get_zwave_value( "currentColor", CommandClass.SWITCH_COLOR, value_property_key=ColorComponent.COLD_WHITE.value, ) # prefer the (new) combined color property # https://github.com/zwave-js/node-zwave-js/pull/1782 combined_color_val = self.get_zwave_value( "currentColor", CommandClass.SWITCH_COLOR, value_property_key=None, ) if combined_color_val and isinstance(combined_color_val.value, dict): multi_color = combined_color_val.value else: multi_color = {} # RGB support if red_val and green_val and blue_val: # prefer values from the multicolor property red = multi_color.get("red", red_val.value) green = multi_color.get("green", green_val.value) blue = multi_color.get("blue", blue_val.value) self._supports_color = True # convert to HS self._hs_color = color_util.color_RGB_to_hs(red, green, blue) # color temperature support if ww_val and cw_val: self._supports_color_temp = True warm_white = multi_color.get("warmWhite", ww_val.value) cold_white = multi_color.get("coldWhite", cw_val.value) # Calculate color temps based on whites if cold_white or warm_white: self._color_temp = round( self._max_mireds - ((cold_white / 255) * (self._max_mireds - self._min_mireds)) ) else: self._color_temp = None # only one white channel (warm white) = white_level support elif ww_val: self._supports_white_value = True self._white_value = multi_color.get("warmWhite", ww_val.value) # only one white channel (cool white) = white_level support elif cw_val: self._supports_white_value = True self._white_value = multi_color.get("coldWhite", cw_val.value)
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/zwave_js/light.py
"""Support for Acmeda Roller Blinds.""" from homeassistant.components.cover import ( ATTR_POSITION, SUPPORT_CLOSE, SUPPORT_CLOSE_TILT, SUPPORT_OPEN, SUPPORT_OPEN_TILT, SUPPORT_SET_POSITION, SUPPORT_SET_TILT_POSITION, SUPPORT_STOP, SUPPORT_STOP_TILT, CoverEntity, ) from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from .base import AcmedaBase from .const import ACMEDA_HUB_UPDATE, DOMAIN from .helpers import async_add_acmeda_entities async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Acmeda Rollers from a config entry.""" hub = hass.data[DOMAIN][config_entry.entry_id] current = set() @callback def async_add_acmeda_covers(): async_add_acmeda_entities( hass, AcmedaCover, config_entry, current, async_add_entities ) hub.cleanup_callbacks.append( async_dispatcher_connect( hass, ACMEDA_HUB_UPDATE.format(config_entry.entry_id), async_add_acmeda_covers, ) ) class AcmedaCover(AcmedaBase, CoverEntity): """Representation of a Acmeda cover device.""" @property def current_cover_position(self): """Return the current position of the roller blind. None is unknown, 0 is closed, 100 is fully open. """ position = None if self.roller.type != 7: position = 100 - self.roller.closed_percent return position @property def current_cover_tilt_position(self): """Return the current tilt of the roller blind. None is unknown, 0 is closed, 100 is fully open. """ position = None if self.roller.type in [7, 10]: position = 100 - self.roller.closed_percent return position @property def supported_features(self): """Flag supported features.""" supported_features = 0 if self.current_cover_position is not None: supported_features |= ( SUPPORT_OPEN | SUPPORT_CLOSE | SUPPORT_STOP | SUPPORT_SET_POSITION ) if self.current_cover_tilt_position is not None: supported_features |= ( SUPPORT_OPEN_TILT | SUPPORT_CLOSE_TILT | SUPPORT_STOP_TILT | SUPPORT_SET_TILT_POSITION ) return supported_features @property def is_closed(self): """Return if the cover is closed.""" return self.roller.closed_percent == 100 async def async_close_cover(self, **kwargs): """Close the roller.""" await self.roller.move_down() async def async_open_cover(self, **kwargs): """Open the roller.""" await self.roller.move_up() async def async_stop_cover(self, **kwargs): """Stop the roller.""" await self.roller.move_stop() async def async_set_cover_position(self, **kwargs): """Move the roller shutter to a specific position.""" await self.roller.move_to(100 - kwargs[ATTR_POSITION]) async def async_close_cover_tilt(self, **kwargs): """Close the roller.""" await self.roller.move_down() async def async_open_cover_tilt(self, **kwargs): """Open the roller.""" await self.roller.move_up() async def async_stop_cover_tilt(self, **kwargs): """Stop the roller.""" await self.roller.move_stop() async def async_set_cover_tilt(self, **kwargs): """Tilt the roller shutter to a specific position.""" await self.roller.move_to(100 - kwargs[ATTR_POSITION])
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/acmeda/cover.py
"""Support for Nest Cameras.""" from datetime import timedelta import logging import requests from homeassistant.components.camera import PLATFORM_SCHEMA, SUPPORT_ON_OFF, Camera from homeassistant.util.dt import utcnow from .const import DATA_NEST, DOMAIN _LOGGER = logging.getLogger(__name__) NEST_BRAND = "Nest" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({}) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up a Nest Cam. No longer in use. """ async def async_setup_legacy_entry(hass, entry, async_add_entities): """Set up a Nest sensor based on a config entry.""" camera_devices = await hass.async_add_executor_job(hass.data[DATA_NEST].cameras) cameras = [NestCamera(structure, device) for structure, device in camera_devices] async_add_entities(cameras, True) class NestCamera(Camera): """Representation of a Nest Camera.""" def __init__(self, structure, device): """Initialize a Nest Camera.""" super().__init__() self.structure = structure self.device = device self._location = None self._name = None self._online = None self._is_streaming = None self._is_video_history_enabled = False # Default to non-NestAware subscribed, but will be fixed during update self._time_between_snapshots = timedelta(seconds=30) self._last_image = None self._next_snapshot_at = None @property def name(self): """Return the name of the nest, if any.""" return self._name @property def unique_id(self): """Return the serial number.""" return self.device.device_id @property def device_info(self): """Return information about the device.""" return { "identifiers": {(DOMAIN, self.device.device_id)}, "name": self.device.name_long, "manufacturer": "Nest Labs", "model": "Camera", } @property def should_poll(self): """Nest camera should poll periodically.""" return True @property def is_recording(self): """Return true if the device is recording.""" return self._is_streaming @property def brand(self): """Return the brand of the camera.""" return NEST_BRAND @property def supported_features(self): """Nest Cam support turn on and off.""" return SUPPORT_ON_OFF @property def is_on(self): """Return true if on.""" return self._online and self._is_streaming def turn_off(self): """Turn off camera.""" _LOGGER.debug("Turn off camera %s", self._name) # Calling Nest API in is_streaming setter. # device.is_streaming would not immediately change until the process # finished in Nest Cam. self.device.is_streaming = False def turn_on(self): """Turn on camera.""" if not self._online: _LOGGER.error("Camera %s is offline", self._name) return _LOGGER.debug("Turn on camera %s", self._name) # Calling Nest API in is_streaming setter. # device.is_streaming would not immediately change until the process # finished in Nest Cam. self.device.is_streaming = True def update(self): """Cache value from Python-nest.""" self._location = self.device.where self._name = self.device.name self._online = self.device.online self._is_streaming = self.device.is_streaming self._is_video_history_enabled = self.device.is_video_history_enabled if self._is_video_history_enabled: # NestAware allowed 10/min self._time_between_snapshots = timedelta(seconds=6) else: # Otherwise, 2/min self._time_between_snapshots = timedelta(seconds=30) def _ready_for_snapshot(self, now): return self._next_snapshot_at is None or now > self._next_snapshot_at def camera_image(self): """Return a still image response from the camera.""" now = utcnow() if self._ready_for_snapshot(now): url = self.device.snapshot_url try: response = requests.get(url) except requests.exceptions.RequestException as error: _LOGGER.error("Error getting camera image: %s", error) return None self._next_snapshot_at = now + self._time_between_snapshots self._last_image = response.content return self._last_image
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/nest/legacy/camera.py
"""KIRA interface to receive UDP packets from an IR-IP bridge.""" import logging import os import pykira import voluptuous as vol from voluptuous.error import Error as VoluptuousError import yaml from homeassistant.const import ( CONF_CODE, CONF_DEVICE, CONF_HOST, CONF_NAME, CONF_PORT, CONF_REPEAT, CONF_SENSORS, CONF_TYPE, EVENT_HOMEASSISTANT_STOP, STATE_UNKNOWN, ) from homeassistant.helpers import discovery import homeassistant.helpers.config_validation as cv DOMAIN = "kira" _LOGGER = logging.getLogger(__name__) DEFAULT_HOST = "0.0.0.0" DEFAULT_PORT = 65432 CONF_REMOTES = "remotes" CONF_SENSOR = "sensor" CONF_REMOTE = "remote" CODES_YAML = f"{DOMAIN}_codes.yaml" CODE_SCHEMA = vol.Schema( { vol.Required(CONF_NAME): cv.string, vol.Required(CONF_CODE): cv.string, vol.Optional(CONF_TYPE): cv.string, vol.Optional(CONF_DEVICE): cv.string, vol.Optional(CONF_REPEAT): cv.positive_int, } ) SENSOR_SCHEMA = vol.Schema( { vol.Optional(CONF_NAME, default=DOMAIN): vol.Exclusive(cv.string, "sensors"), vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, } ) REMOTE_SCHEMA = vol.Schema( { vol.Optional(CONF_NAME, default=DOMAIN): vol.Exclusive(cv.string, "remotes"), vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, } ) CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Optional(CONF_SENSORS): [SENSOR_SCHEMA], vol.Optional(CONF_REMOTES): [REMOTE_SCHEMA], } ) }, extra=vol.ALLOW_EXTRA, ) def load_codes(path): """Load KIRA codes from specified file.""" codes = [] if os.path.exists(path): with open(path) as code_file: data = yaml.safe_load(code_file) or [] for code in data: try: codes.append(CODE_SCHEMA(code)) except VoluptuousError as exception: # keep going _LOGGER.warning("KIRA code invalid data: %s", exception) else: with open(path, "w") as code_file: code_file.write("") return codes def setup(hass, config): """Set up the KIRA component.""" sensors = config.get(DOMAIN, {}).get(CONF_SENSORS, []) remotes = config.get(DOMAIN, {}).get(CONF_REMOTES, []) # If no sensors or remotes were specified, add a sensor if not (sensors or remotes): sensors.append({}) codes = load_codes(hass.config.path(CODES_YAML)) hass.data[DOMAIN] = {CONF_SENSOR: {}, CONF_REMOTE: {}} def load_module(platform, idx, module_conf): """Set up the KIRA module and load platform.""" # note: module_name is not the HA device name. it's just a unique name # to ensure the component and platform can share information module_name = ("%s_%d" % (DOMAIN, idx)) if idx else DOMAIN device_name = module_conf.get(CONF_NAME, DOMAIN) port = module_conf.get(CONF_PORT, DEFAULT_PORT) host = module_conf.get(CONF_HOST, DEFAULT_HOST) if platform == CONF_SENSOR: module = pykira.KiraReceiver(host, port) module.start() else: module = pykira.KiraModule(host, port) hass.data[DOMAIN][platform][module_name] = module for code in codes: code_tuple = (code.get(CONF_NAME), code.get(CONF_DEVICE, STATE_UNKNOWN)) module.registerCode(code_tuple, code.get(CONF_CODE)) discovery.load_platform( hass, platform, DOMAIN, {"name": module_name, "device": device_name}, config ) for idx, module_conf in enumerate(sensors): load_module(CONF_SENSOR, idx, module_conf) for idx, module_conf in enumerate(remotes): load_module(CONF_REMOTE, idx, module_conf) def _stop_kira(_event): """Stop the KIRA receiver.""" for receiver in hass.data[DOMAIN][CONF_SENSOR].values(): receiver.stop() _LOGGER.info("Terminated receivers") hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, _stop_kira) return True
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/kira/__init__.py
"""Errors for the cert_expiry integration.""" from homeassistant.exceptions import HomeAssistantError class CertExpiryException(HomeAssistantError): """Base class for cert_expiry exceptions.""" class TemporaryFailure(CertExpiryException): """Temporary failure has occurred.""" class ValidationFailure(CertExpiryException): """Certificate validation failure has occurred.""" class ResolveFailed(TemporaryFailure): """Name resolution failed.""" class ConnectionTimeout(TemporaryFailure): """Network connection timed out.""" class ConnectionRefused(TemporaryFailure): """Network connection refused."""
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/cert_expiry/errors.py
"""Config flow for UpCloud.""" import logging import requests.exceptions import upcloud_api import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_PASSWORD, CONF_SCAN_INTERVAL, CONF_USERNAME from homeassistant.core import callback from .const import DEFAULT_SCAN_INTERVAL, DOMAIN _LOGGER = logging.getLogger(__name__) class UpCloudConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """UpCloud config flow.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL username: str password: str async def async_step_user(self, user_input=None): """Handle user initiated flow.""" if user_input is None: return self._async_show_form(step_id="user") await self.async_set_unique_id(user_input[CONF_USERNAME]) manager = upcloud_api.CloudManager( user_input[CONF_USERNAME], user_input[CONF_PASSWORD] ) errors = {} try: await self.hass.async_add_executor_job(manager.authenticate) except upcloud_api.UpCloudAPIError: errors["base"] = "invalid_auth" _LOGGER.debug("invalid_auth", exc_info=True) except requests.exceptions.RequestException: errors["base"] = "cannot_connect" _LOGGER.debug("cannot_connect", exc_info=True) if errors: return self._async_show_form( step_id="user", user_input=user_input, errors=errors ) return self.async_create_entry(title=user_input[CONF_USERNAME], data=user_input) async def async_step_import(self, user_input=None): """Handle import initiated flow.""" await self.async_set_unique_id(user_input[CONF_USERNAME]) self._abort_if_unique_id_configured() return await self.async_step_user(user_input=user_input) @callback def _async_show_form(self, step_id, user_input=None, errors=None): """Show our form.""" if user_input is None: user_input = {} return self.async_show_form( step_id=step_id, data_schema=vol.Schema( { vol.Required( CONF_USERNAME, default=user_input.get(CONF_USERNAME, "") ): str, vol.Required( CONF_PASSWORD, default=user_input.get(CONF_PASSWORD, "") ): str, } ), errors=errors or {}, ) @staticmethod @callback def async_get_options_flow(config_entry): """Get options flow.""" return UpCloudOptionsFlow(config_entry) class UpCloudOptionsFlow(config_entries.OptionsFlow): """UpCloud options flow.""" def __init__(self, config_entry: config_entries.ConfigEntry): """Initialize options flow.""" self.config_entry = config_entry async def async_step_init(self, user_input=None): """Handle options flow.""" if user_input is not None: return self.async_create_entry(title="", data=user_input) data_schema = vol.Schema( { vol.Optional( CONF_SCAN_INTERVAL, default=self.config_entry.options.get(CONF_SCAN_INTERVAL) or DEFAULT_SCAN_INTERVAL.seconds, ): vol.All(vol.Coerce(int), vol.Range(min=30)), } ) return self.async_show_form(step_id="init", data_schema=data_schema)
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/upcloud/config_flow.py
"""Support for Snips on-device ASR and NLU.""" from datetime import timedelta import json import logging import voluptuous as vol from homeassistant.components import mqtt from homeassistant.core import callback from homeassistant.helpers import config_validation as cv, intent DOMAIN = "snips" CONF_INTENTS = "intents" CONF_ACTION = "action" CONF_FEEDBACK = "feedback_sounds" CONF_PROBABILITY = "probability_threshold" CONF_SITE_IDS = "site_ids" SERVICE_SAY = "say" SERVICE_SAY_ACTION = "say_action" SERVICE_FEEDBACK_ON = "feedback_on" SERVICE_FEEDBACK_OFF = "feedback_off" INTENT_TOPIC = "hermes/intent/#" FEEDBACK_ON_TOPIC = "hermes/feedback/sound/toggleOn" FEEDBACK_OFF_TOPIC = "hermes/feedback/sound/toggleOff" ATTR_TEXT = "text" ATTR_SITE_ID = "site_id" ATTR_CUSTOM_DATA = "custom_data" ATTR_CAN_BE_ENQUEUED = "can_be_enqueued" ATTR_INTENT_FILTER = "intent_filter" _LOGGER = logging.getLogger(__name__) CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Optional(CONF_FEEDBACK): cv.boolean, vol.Optional(CONF_PROBABILITY, default=0): vol.Coerce(float), vol.Optional(CONF_SITE_IDS, default=["default"]): vol.All( cv.ensure_list, [cv.string] ), } ) }, extra=vol.ALLOW_EXTRA, ) INTENT_SCHEMA = vol.Schema( { vol.Required("input"): str, vol.Required("intent"): {vol.Required("intentName"): str}, vol.Optional("slots"): [ { vol.Required("slotName"): str, vol.Required("value"): { vol.Required("kind"): str, vol.Optional("value"): cv.match_all, vol.Optional("rawValue"): cv.match_all, }, } ], }, extra=vol.ALLOW_EXTRA, ) SERVICE_SCHEMA_SAY = vol.Schema( { vol.Required(ATTR_TEXT): str, vol.Optional(ATTR_SITE_ID, default="default"): str, vol.Optional(ATTR_CUSTOM_DATA, default=""): str, } ) SERVICE_SCHEMA_SAY_ACTION = vol.Schema( { vol.Required(ATTR_TEXT): str, vol.Optional(ATTR_SITE_ID, default="default"): str, vol.Optional(ATTR_CUSTOM_DATA, default=""): str, vol.Optional(ATTR_CAN_BE_ENQUEUED, default=True): cv.boolean, vol.Optional(ATTR_INTENT_FILTER): vol.All(cv.ensure_list), } ) SERVICE_SCHEMA_FEEDBACK = vol.Schema( {vol.Optional(ATTR_SITE_ID, default="default"): str} ) async def async_setup(hass, config): """Activate Snips component.""" @callback def async_set_feedback(site_ids, state): """Set Feedback sound state.""" site_ids = site_ids if site_ids else config[DOMAIN].get(CONF_SITE_IDS) topic = FEEDBACK_ON_TOPIC if state else FEEDBACK_OFF_TOPIC for site_id in site_ids: payload = json.dumps({"siteId": site_id}) hass.components.mqtt.async_publish( FEEDBACK_ON_TOPIC, "", qos=0, retain=False ) hass.components.mqtt.async_publish( topic, payload, qos=int(state), retain=state ) if CONF_FEEDBACK in config[DOMAIN]: async_set_feedback(None, config[DOMAIN][CONF_FEEDBACK]) async def message_received(msg): """Handle new messages on MQTT.""" _LOGGER.debug("New intent: %s", msg.payload) try: request = json.loads(msg.payload) except TypeError: _LOGGER.error("Received invalid JSON: %s", msg.payload) return if request["intent"]["confidenceScore"] < config[DOMAIN].get(CONF_PROBABILITY): _LOGGER.warning( "Intent below probaility threshold %s < %s", request["intent"]["confidenceScore"], config[DOMAIN].get(CONF_PROBABILITY), ) return try: request = INTENT_SCHEMA(request) except vol.Invalid as err: _LOGGER.error("Intent has invalid schema: %s. %s", err, request) return if request["intent"]["intentName"].startswith("user_"): intent_type = request["intent"]["intentName"].split("__")[-1] else: intent_type = request["intent"]["intentName"].split(":")[-1] slots = {} for slot in request.get("slots", []): slots[slot["slotName"]] = {"value": resolve_slot_values(slot)} slots["{}_raw".format(slot["slotName"])] = {"value": slot["rawValue"]} slots["site_id"] = {"value": request.get("siteId")} slots["session_id"] = {"value": request.get("sessionId")} slots["confidenceScore"] = {"value": request["intent"]["confidenceScore"]} try: intent_response = await intent.async_handle( hass, DOMAIN, intent_type, slots, request["input"] ) notification = {"sessionId": request.get("sessionId", "default")} if "plain" in intent_response.speech: notification["text"] = intent_response.speech["plain"]["speech"] _LOGGER.debug("send_response %s", json.dumps(notification)) mqtt.async_publish( hass, "hermes/dialogueManager/endSession", json.dumps(notification) ) except intent.UnknownIntent: _LOGGER.warning( "Received unknown intent %s", request["intent"]["intentName"] ) except intent.IntentError: _LOGGER.exception("Error while handling intent: %s", intent_type) await hass.components.mqtt.async_subscribe(INTENT_TOPIC, message_received) async def snips_say(call): """Send a Snips notification message.""" notification = { "siteId": call.data.get(ATTR_SITE_ID, "default"), "customData": call.data.get(ATTR_CUSTOM_DATA, ""), "init": {"type": "notification", "text": call.data.get(ATTR_TEXT)}, } mqtt.async_publish( hass, "hermes/dialogueManager/startSession", json.dumps(notification) ) return async def snips_say_action(call): """Send a Snips action message.""" notification = { "siteId": call.data.get(ATTR_SITE_ID, "default"), "customData": call.data.get(ATTR_CUSTOM_DATA, ""), "init": { "type": "action", "text": call.data.get(ATTR_TEXT), "canBeEnqueued": call.data.get(ATTR_CAN_BE_ENQUEUED, True), "intentFilter": call.data.get(ATTR_INTENT_FILTER, []), }, } mqtt.async_publish( hass, "hermes/dialogueManager/startSession", json.dumps(notification) ) return async def feedback_on(call): """Turn feedback sounds on.""" async_set_feedback(call.data.get(ATTR_SITE_ID), True) async def feedback_off(call): """Turn feedback sounds off.""" async_set_feedback(call.data.get(ATTR_SITE_ID), False) hass.services.async_register( DOMAIN, SERVICE_SAY, snips_say, schema=SERVICE_SCHEMA_SAY ) hass.services.async_register( DOMAIN, SERVICE_SAY_ACTION, snips_say_action, schema=SERVICE_SCHEMA_SAY_ACTION ) hass.services.async_register( DOMAIN, SERVICE_FEEDBACK_ON, feedback_on, schema=SERVICE_SCHEMA_FEEDBACK ) hass.services.async_register( DOMAIN, SERVICE_FEEDBACK_OFF, feedback_off, schema=SERVICE_SCHEMA_FEEDBACK ) return True def resolve_slot_values(slot): """Convert snips builtin types to usable values.""" if "value" in slot["value"]: value = slot["value"]["value"] else: value = slot["rawValue"] if slot.get("entity") == "snips/duration": delta = timedelta( weeks=slot["value"]["weeks"], days=slot["value"]["days"], hours=slot["value"]["hours"], minutes=slot["value"]["minutes"], seconds=slot["value"]["seconds"], ) value = delta.seconds return value
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/snips/__init__.py
"""Config flow for Network UPS Tools (NUT) integration.""" import logging import voluptuous as vol from homeassistant import config_entries, core, exceptions from homeassistant.const import ( CONF_ALIAS, CONF_BASE, CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_RESOURCES, CONF_SCAN_INTERVAL, CONF_USERNAME, ) from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from . import PyNUTData, find_resources_in_config_entry from .const import ( DEFAULT_HOST, DEFAULT_PORT, DEFAULT_SCAN_INTERVAL, DOMAIN, KEY_STATUS, KEY_STATUS_DISPLAY, SENSOR_NAME, SENSOR_TYPES, ) _LOGGER = logging.getLogger(__name__) SENSOR_DICT = { sensor_id: sensor_spec[SENSOR_NAME] for sensor_id, sensor_spec in SENSOR_TYPES.items() } def _base_schema(discovery_info): """Generate base schema.""" base_schema = {} if not discovery_info: base_schema.update( { vol.Optional(CONF_HOST, default=DEFAULT_HOST): str, vol.Optional(CONF_PORT, default=DEFAULT_PORT): int, } ) base_schema.update( {vol.Optional(CONF_USERNAME): str, vol.Optional(CONF_PASSWORD): str} ) return vol.Schema(base_schema) def _resource_schema_base(available_resources, selected_resources): """Resource selection schema.""" known_available_resources = { sensor_id: sensor[SENSOR_NAME] for sensor_id, sensor in SENSOR_TYPES.items() if sensor_id in available_resources } if KEY_STATUS in known_available_resources: known_available_resources[KEY_STATUS_DISPLAY] = SENSOR_TYPES[ KEY_STATUS_DISPLAY ][SENSOR_NAME] return { vol.Required(CONF_RESOURCES, default=selected_resources): cv.multi_select( known_available_resources ) } def _ups_schema(ups_list): """UPS selection schema.""" return vol.Schema({vol.Required(CONF_ALIAS): vol.In(ups_list)}) async def validate_input(hass: core.HomeAssistant, data): """Validate the user input allows us to connect. Data has the keys from _base_schema with values provided by the user. """ host = data[CONF_HOST] port = data[CONF_PORT] alias = data.get(CONF_ALIAS) username = data.get(CONF_USERNAME) password = data.get(CONF_PASSWORD) data = PyNUTData(host, port, alias, username, password) await hass.async_add_executor_job(data.update) status = data.status if not status: raise CannotConnect return {"ups_list": data.ups_list, "available_resources": status} def _format_host_port_alias(user_input): """Format a host, port, and alias so it can be used for comparison or display.""" host = user_input[CONF_HOST] port = user_input[CONF_PORT] alias = user_input.get(CONF_ALIAS) if alias: return f"{alias}@{host}:{port}" return f"{host}:{port}" class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Handle a config flow for Network UPS Tools (NUT).""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL def __init__(self): """Initialize the nut config flow.""" self.nut_config = {} self.available_resources = {} self.discovery_info = {} self.ups_list = None self.title = None async def async_step_zeroconf(self, discovery_info): """Prepare configuration for a discovered nut device.""" self.discovery_info = discovery_info await self._async_handle_discovery_without_unique_id() self.context["title_placeholders"] = { CONF_PORT: discovery_info.get(CONF_PORT, DEFAULT_PORT), CONF_HOST: discovery_info[CONF_HOST], } return await self.async_step_user() async def async_step_user(self, user_input=None): """Handle the user input.""" errors = {} if user_input is not None: if self.discovery_info: user_input.update( { CONF_HOST: self.discovery_info[CONF_HOST], CONF_PORT: self.discovery_info.get(CONF_PORT, DEFAULT_PORT), } ) info, errors = await self._async_validate_or_error(user_input) if not errors: self.nut_config.update(user_input) if len(info["ups_list"]) > 1: self.ups_list = info["ups_list"] return await self.async_step_ups() if self._host_port_alias_already_configured(self.nut_config): return self.async_abort(reason="already_configured") self.available_resources.update(info["available_resources"]) return await self.async_step_resources() return self.async_show_form( step_id="user", data_schema=_base_schema(self.discovery_info), errors=errors ) async def async_step_ups(self, user_input=None): """Handle the picking the ups.""" errors = {} if user_input is not None: self.nut_config.update(user_input) if self._host_port_alias_already_configured(self.nut_config): return self.async_abort(reason="already_configured") info, errors = await self._async_validate_or_error(self.nut_config) if not errors: self.available_resources.update(info["available_resources"]) return await self.async_step_resources() return self.async_show_form( step_id="ups", data_schema=_ups_schema(self.ups_list), errors=errors, ) async def async_step_resources(self, user_input=None): """Handle the picking the resources.""" if user_input is None: return self.async_show_form( step_id="resources", data_schema=vol.Schema( _resource_schema_base(self.available_resources, []) ), ) self.nut_config.update(user_input) title = _format_host_port_alias(self.nut_config) return self.async_create_entry(title=title, data=self.nut_config) def _host_port_alias_already_configured(self, user_input): """See if we already have a nut entry matching user input configured.""" existing_host_port_aliases = { _format_host_port_alias(entry.data) for entry in self._async_current_entries() if CONF_HOST in entry.data } return _format_host_port_alias(user_input) in existing_host_port_aliases async def _async_validate_or_error(self, config): errors = {} info = {} try: info = await validate_input(self.hass, config) except CannotConnect: errors[CONF_BASE] = "cannot_connect" except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") errors[CONF_BASE] = "unknown" return info, errors @staticmethod @callback def async_get_options_flow(config_entry): """Get the options flow for this handler.""" return OptionsFlowHandler(config_entry) class OptionsFlowHandler(config_entries.OptionsFlow): """Handle a option flow for nut.""" def __init__(self, config_entry: config_entries.ConfigEntry): """Initialize options flow.""" self.config_entry = config_entry async def async_step_init(self, user_input=None): """Handle options flow.""" if user_input is not None: return self.async_create_entry(title="", data=user_input) resources = find_resources_in_config_entry(self.config_entry) scan_interval = self.config_entry.options.get( CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL ) errors = {} try: info = await validate_input(self.hass, self.config_entry.data) except CannotConnect: errors[CONF_BASE] = "cannot_connect" except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") errors[CONF_BASE] = "unknown" if errors: return self.async_show_form(step_id="abort", errors=errors) base_schema = _resource_schema_base(info["available_resources"], resources) base_schema[ vol.Optional(CONF_SCAN_INTERVAL, default=scan_interval) ] = cv.positive_int return self.async_show_form( step_id="init", data_schema=vol.Schema(base_schema), errors=errors ) async def async_step_abort(self, user_input=None): """Abort options flow.""" return self.async_create_entry(title="", data=self.config_entry.options) class CannotConnect(exceptions.HomeAssistantError): """Error to indicate we cannot connect."""
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/nut/config_flow.py
"""The fritzbox_callmonitor integration.""" from asyncio import gather import logging from fritzconnection.core.exceptions import FritzConnectionException, FritzSecurityError from requests.exceptions import ConnectionError as RequestsConnectionError from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME from homeassistant.exceptions import ConfigEntryNotReady from .base import FritzBoxPhonebook from .const import ( CONF_PHONEBOOK, CONF_PREFIXES, DOMAIN, FRITZBOX_PHONEBOOK, PLATFORMS, UNDO_UPDATE_LISTENER, ) _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass, config_entry): """Set up the fritzbox_callmonitor platforms.""" fritzbox_phonebook = FritzBoxPhonebook( host=config_entry.data[CONF_HOST], username=config_entry.data[CONF_USERNAME], password=config_entry.data[CONF_PASSWORD], phonebook_id=config_entry.data[CONF_PHONEBOOK], prefixes=config_entry.options.get(CONF_PREFIXES), ) try: await hass.async_add_executor_job(fritzbox_phonebook.init_phonebook) except FritzSecurityError as ex: _LOGGER.error( "User has insufficient permissions to access AVM FRITZ!Box settings and its phonebooks: %s", ex, ) return False except FritzConnectionException as ex: _LOGGER.error("Invalid authentication: %s", ex) return False except RequestsConnectionError as ex: _LOGGER.error("Unable to connect to AVM FRITZ!Box call monitor: %s", ex) raise ConfigEntryNotReady from ex undo_listener = config_entry.add_update_listener(update_listener) hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][config_entry.entry_id] = { FRITZBOX_PHONEBOOK: fritzbox_phonebook, UNDO_UPDATE_LISTENER: undo_listener, } for platform in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(config_entry, platform) ) return True async def async_unload_entry(hass, config_entry): """Unloading the fritzbox_callmonitor platforms.""" unload_ok = all( await gather( *[ hass.config_entries.async_forward_entry_unload(config_entry, platform) for platform in PLATFORMS ] ) ) hass.data[DOMAIN][config_entry.entry_id][UNDO_UPDATE_LISTENER]() if unload_ok: hass.data[DOMAIN].pop(config_entry.entry_id) return unload_ok async def update_listener(hass, config_entry): """Update listener to reload after option has changed.""" await hass.config_entries.async_reload(config_entry.entry_id)
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/fritzbox_callmonitor/__init__.py
"""Support for Axis binary sensors.""" from datetime import timedelta from axis.event_stream import ( CLASS_INPUT, CLASS_LIGHT, CLASS_MOTION, CLASS_OUTPUT, CLASS_PTZ, CLASS_SOUND, FenceGuard, LoiteringGuard, MotionGuard, ObjectAnalytics, Vmd4, ) from homeassistant.components.binary_sensor import ( DEVICE_CLASS_CONNECTIVITY, DEVICE_CLASS_LIGHT, DEVICE_CLASS_MOTION, DEVICE_CLASS_SOUND, BinarySensorEntity, ) from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.event import async_track_point_in_utc_time from homeassistant.util.dt import utcnow from .axis_base import AxisEventBase from .const import DOMAIN as AXIS_DOMAIN DEVICE_CLASS = { CLASS_INPUT: DEVICE_CLASS_CONNECTIVITY, CLASS_LIGHT: DEVICE_CLASS_LIGHT, CLASS_MOTION: DEVICE_CLASS_MOTION, CLASS_SOUND: DEVICE_CLASS_SOUND, } async def async_setup_entry(hass, config_entry, async_add_entities): """Set up a Axis binary sensor.""" device = hass.data[AXIS_DOMAIN][config_entry.unique_id] @callback def async_add_sensor(event_id): """Add binary sensor from Axis device.""" event = device.api.event[event_id] if event.CLASS not in (CLASS_OUTPUT, CLASS_PTZ) and not ( event.CLASS == CLASS_LIGHT and event.TYPE == "Light" ): async_add_entities([AxisBinarySensor(event, device)]) device.listeners.append( async_dispatcher_connect(hass, device.signal_new_event, async_add_sensor) ) class AxisBinarySensor(AxisEventBase, BinarySensorEntity): """Representation of a binary Axis event.""" def __init__(self, event, device): """Initialize the Axis binary sensor.""" super().__init__(event, device) self.cancel_scheduled_update = None @callback def update_callback(self, no_delay=False): """Update the sensor's state, if needed. Parameter no_delay is True when device_event_reachable is sent. """ @callback def scheduled_update(now): """Timer callback for sensor update.""" self.cancel_scheduled_update = None self.async_write_ha_state() if self.cancel_scheduled_update is not None: self.cancel_scheduled_update() self.cancel_scheduled_update = None if self.is_on or self.device.option_trigger_time == 0 or no_delay: self.async_write_ha_state() return self.cancel_scheduled_update = async_track_point_in_utc_time( self.hass, scheduled_update, utcnow() + timedelta(seconds=self.device.option_trigger_time), ) @property def is_on(self): """Return true if event is active.""" return self.event.is_tripped @property def name(self): """Return the name of the event.""" if ( self.event.CLASS == CLASS_INPUT and self.event.id in self.device.api.vapix.ports and self.device.api.vapix.ports[self.event.id].name ): return ( f"{self.device.name} {self.device.api.vapix.ports[self.event.id].name}" ) if self.event.CLASS == CLASS_MOTION: for event_class, event_data in ( (FenceGuard, self.device.api.vapix.fence_guard), (LoiteringGuard, self.device.api.vapix.loitering_guard), (MotionGuard, self.device.api.vapix.motion_guard), (ObjectAnalytics, self.device.api.vapix.object_analytics), (Vmd4, self.device.api.vapix.vmd4), ): if ( isinstance(self.event, event_class) and event_data and self.event.id in event_data ): return f"{self.device.name} {self.event.TYPE} {event_data[self.event.id].name}" return super().name @property def device_class(self): """Return the class of the sensor.""" return DEVICE_CLASS.get(self.event.CLASS)
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/axis/binary_sensor.py
"""Support for Axis lights.""" from axis.event_stream import CLASS_LIGHT from homeassistant.components.light import ( ATTR_BRIGHTNESS, SUPPORT_BRIGHTNESS, LightEntity, ) from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from .axis_base import AxisEventBase from .const import DOMAIN as AXIS_DOMAIN async def async_setup_entry(hass, config_entry, async_add_entities): """Set up a Axis light.""" device = hass.data[AXIS_DOMAIN][config_entry.unique_id] if ( device.api.vapix.light_control is None or len(device.api.vapix.light_control) == 0 ): return @callback def async_add_sensor(event_id): """Add light from Axis device.""" event = device.api.event[event_id] if event.CLASS == CLASS_LIGHT and event.TYPE == "Light": async_add_entities([AxisLight(event, device)]) device.listeners.append( async_dispatcher_connect(hass, device.signal_new_event, async_add_sensor) ) class AxisLight(AxisEventBase, LightEntity): """Representation of a light Axis event.""" def __init__(self, event, device): """Initialize the Axis light.""" super().__init__(event, device) self.light_id = f"led{self.event.id}" self.current_intensity = 0 self.max_intensity = 0 self._features = SUPPORT_BRIGHTNESS async def async_added_to_hass(self) -> None: """Subscribe lights events.""" await super().async_added_to_hass() current_intensity = ( await self.device.api.vapix.light_control.get_current_intensity( self.light_id ) ) self.current_intensity = current_intensity["data"]["intensity"] max_intensity = await self.device.api.vapix.light_control.get_valid_intensity( self.light_id ) self.max_intensity = max_intensity["data"]["ranges"][0]["high"] @property def supported_features(self): """Flag supported features.""" return self._features @property def name(self): """Return the name of the light.""" light_type = self.device.api.vapix.light_control[self.light_id].light_type return f"{self.device.name} {light_type} {self.event.TYPE} {self.event.id}" @property def is_on(self): """Return true if light is on.""" return self.event.is_tripped @property def brightness(self): """Return the brightness of this light between 0..255.""" return int((self.current_intensity / self.max_intensity) * 255) async def async_turn_on(self, **kwargs): """Turn on light.""" if not self.is_on: await self.device.api.vapix.light_control.activate_light(self.light_id) if ATTR_BRIGHTNESS in kwargs: intensity = int((kwargs[ATTR_BRIGHTNESS] / 255) * self.max_intensity) await self.device.api.vapix.light_control.set_manual_intensity( self.light_id, intensity ) async def async_turn_off(self, **kwargs): """Turn off light.""" if self.is_on: await self.device.api.vapix.light_control.deactivate_light(self.light_id) async def async_update(self): """Update brightness.""" current_intensity = ( await self.device.api.vapix.light_control.get_current_intensity( self.light_id ) ) self.current_intensity = current_intensity["data"]["intensity"] @property def should_poll(self): """Brightness needs polling.""" return True
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/axis/light.py
"""The Keenetic Client class.""" import logging from homeassistant.components.binary_sensor import ( DEVICE_CLASS_CONNECTIVITY, BinarySensorEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.dispatcher import async_dispatcher_connect from . import KeeneticRouter from .const import DOMAIN, ROUTER _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities ): """Set up device tracker for Keenetic NDMS2 component.""" router: KeeneticRouter = hass.data[DOMAIN][config_entry.entry_id][ROUTER] async_add_entities([RouterOnlineBinarySensor(router)]) class RouterOnlineBinarySensor(BinarySensorEntity): """Representation router connection status.""" def __init__(self, router: KeeneticRouter): """Initialize the APCUPSd binary device.""" self._router = router @property def name(self): """Return the name of the online status sensor.""" return f"{self._router.name} Online" @property def unique_id(self) -> str: """Return a unique identifier for this device.""" return f"online_{self._router.config_entry.entry_id}" @property def is_on(self): """Return true if the UPS is online, else false.""" return self._router.available @property def device_class(self): """Return the class of this device, from component DEVICE_CLASSES.""" return DEVICE_CLASS_CONNECTIVITY @property def should_poll(self) -> bool: """Return False since entity pushes its state to HA.""" return False @property def device_info(self): """Return a client description for device registry.""" return self._router.device_info async def async_added_to_hass(self): """Client entity created.""" self.async_on_remove( async_dispatcher_connect( self.hass, self._router.signal_update, self.async_write_ha_state, ) )
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/keenetic_ndms2/binary_sensor.py
"""Handler for Hass.io.""" import asyncio import logging import os import aiohttp from homeassistant.components.http import ( CONF_SERVER_HOST, CONF_SERVER_PORT, CONF_SSL_CERTIFICATE, ) from homeassistant.const import HTTP_BAD_REQUEST, HTTP_OK, SERVER_PORT from .const import X_HASSIO _LOGGER = logging.getLogger(__name__) class HassioAPIError(RuntimeError): """Return if a API trow a error.""" def _api_bool(funct): """Return a boolean.""" async def _wrapper(*argv, **kwargs): """Wrap function.""" try: data = await funct(*argv, **kwargs) return data["result"] == "ok" except HassioAPIError: return False return _wrapper def api_data(funct): """Return data of an api.""" async def _wrapper(*argv, **kwargs): """Wrap function.""" data = await funct(*argv, **kwargs) if data["result"] == "ok": return data["data"] raise HassioAPIError(data["message"]) return _wrapper class HassIO: """Small API wrapper for Hass.io.""" def __init__( self, loop: asyncio.AbstractEventLoop, websession: aiohttp.ClientSession, ip: str, ) -> None: """Initialize Hass.io API.""" self.loop = loop self.websession = websession self._ip = ip @_api_bool def is_connected(self): """Return true if it connected to Hass.io supervisor. This method return a coroutine. """ return self.send_command("/supervisor/ping", method="get", timeout=15) @api_data def get_info(self): """Return generic Supervisor information. This method return a coroutine. """ return self.send_command("/info", method="get") @api_data def get_host_info(self): """Return data for Host. This method return a coroutine. """ return self.send_command("/host/info", method="get") @api_data def get_os_info(self): """Return data for the OS. This method return a coroutine. """ return self.send_command("/os/info", method="get") @api_data def get_core_info(self): """Return data for Home Asssistant Core. This method returns a coroutine. """ return self.send_command("/core/info", method="get") @api_data def get_supervisor_info(self): """Return data for the Supervisor. This method returns a coroutine. """ return self.send_command("/supervisor/info", method="get") @api_data def get_addon_info(self, addon): """Return data for a Add-on. This method return a coroutine. """ return self.send_command(f"/addons/{addon}/info", method="get") @api_data def get_ingress_panels(self): """Return data for Add-on ingress panels. This method return a coroutine. """ return self.send_command("/ingress/panels", method="get") @_api_bool def restart_homeassistant(self): """Restart Home-Assistant container. This method return a coroutine. """ return self.send_command("/homeassistant/restart") @_api_bool def stop_homeassistant(self): """Stop Home-Assistant container. This method return a coroutine. """ return self.send_command("/homeassistant/stop") @api_data def retrieve_discovery_messages(self): """Return all discovery data from Hass.io API. This method return a coroutine. """ return self.send_command("/discovery", method="get", timeout=60) @api_data def get_discovery_message(self, uuid): """Return a single discovery data message. This method return a coroutine. """ return self.send_command(f"/discovery/{uuid}", method="get") @_api_bool async def update_hass_api(self, http_config, refresh_token): """Update Home Assistant API data on Hass.io.""" port = http_config.get(CONF_SERVER_PORT) or SERVER_PORT options = { "ssl": CONF_SSL_CERTIFICATE in http_config, "port": port, "watchdog": True, "refresh_token": refresh_token.token, } if http_config.get(CONF_SERVER_HOST) is not None: options["watchdog"] = False _LOGGER.warning( "Found incompatible HTTP option 'server_host'. Watchdog feature disabled" ) return await self.send_command("/homeassistant/options", payload=options) @_api_bool def update_hass_timezone(self, timezone): """Update Home-Assistant timezone data on Hass.io. This method return a coroutine. """ return self.send_command("/supervisor/options", payload={"timezone": timezone}) @_api_bool def update_diagnostics(self, diagnostics: bool): """Update Supervisor diagnostics setting. This method return a coroutine. """ return self.send_command( "/supervisor/options", payload={"diagnostics": diagnostics} ) async def send_command(self, command, method="post", payload=None, timeout=10): """Send API command to Hass.io. This method is a coroutine. """ try: request = await self.websession.request( method, f"http://{self._ip}{command}", json=payload, headers={X_HASSIO: os.environ.get("HASSIO_TOKEN", "")}, timeout=aiohttp.ClientTimeout(total=timeout), ) if request.status not in (HTTP_OK, HTTP_BAD_REQUEST): _LOGGER.error("%s return code %d", command, request.status) raise HassioAPIError() answer = await request.json() return answer except asyncio.TimeoutError: _LOGGER.error("Timeout on %s request", command) except aiohttp.ClientError as err: _LOGGER.error("Client error on %s request %s", command, err) raise HassioAPIError()
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/hassio/handler.py
"""Support to select an option from a list.""" from __future__ import annotations import logging import voluptuous as vol from homeassistant.const import ( ATTR_EDITABLE, ATTR_OPTION, CONF_ICON, CONF_ID, CONF_NAME, SERVICE_RELOAD, ) from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import collection import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.restore_state import RestoreEntity import homeassistant.helpers.service from homeassistant.helpers.storage import Store from homeassistant.helpers.typing import ConfigType, ServiceCallType _LOGGER = logging.getLogger(__name__) DOMAIN = "input_select" CONF_INITIAL = "initial" CONF_OPTIONS = "options" ATTR_OPTIONS = "options" ATTR_CYCLE = "cycle" SERVICE_SELECT_OPTION = "select_option" SERVICE_SELECT_NEXT = "select_next" SERVICE_SELECT_PREVIOUS = "select_previous" SERVICE_SELECT_FIRST = "select_first" SERVICE_SELECT_LAST = "select_last" SERVICE_SET_OPTIONS = "set_options" STORAGE_KEY = DOMAIN STORAGE_VERSION = 1 CREATE_FIELDS = { vol.Required(CONF_NAME): vol.All(str, vol.Length(min=1)), vol.Required(CONF_OPTIONS): vol.All(cv.ensure_list, vol.Length(min=1), [cv.string]), vol.Optional(CONF_INITIAL): cv.string, vol.Optional(CONF_ICON): cv.icon, } UPDATE_FIELDS = { vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_OPTIONS): vol.All(cv.ensure_list, vol.Length(min=1), [cv.string]), vol.Optional(CONF_INITIAL): cv.string, vol.Optional(CONF_ICON): cv.icon, } def _cv_input_select(cfg): """Configure validation helper for input select (voluptuous).""" options = cfg[CONF_OPTIONS] initial = cfg.get(CONF_INITIAL) if initial is not None and initial not in options: raise vol.Invalid( f"initial state {initial} is not part of the options: {','.join(options)}" ) return cfg CONFIG_SCHEMA = vol.Schema( { DOMAIN: cv.schema_with_slug_keys( vol.All( { vol.Optional(CONF_NAME): cv.string, vol.Required(CONF_OPTIONS): vol.All( cv.ensure_list, vol.Length(min=1), [cv.string] ), vol.Optional(CONF_INITIAL): cv.string, vol.Optional(CONF_ICON): cv.icon, }, _cv_input_select, ) ) }, extra=vol.ALLOW_EXTRA, ) RELOAD_SERVICE_SCHEMA = vol.Schema({}) async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up an input select.""" component = EntityComponent(_LOGGER, DOMAIN, hass) id_manager = collection.IDManager() yaml_collection = collection.YamlCollection( logging.getLogger(f"{__name__}.yaml_collection"), id_manager ) collection.sync_entity_lifecycle( hass, DOMAIN, DOMAIN, component, yaml_collection, InputSelect.from_yaml ) storage_collection = InputSelectStorageCollection( Store(hass, STORAGE_VERSION, STORAGE_KEY), logging.getLogger(f"{__name__}.storage_collection"), id_manager, ) collection.sync_entity_lifecycle( hass, DOMAIN, DOMAIN, component, storage_collection, InputSelect ) await yaml_collection.async_load( [{CONF_ID: id_, **cfg} for id_, cfg in config.get(DOMAIN, {}).items()] ) await storage_collection.async_load() collection.StorageCollectionWebsocket( storage_collection, DOMAIN, DOMAIN, CREATE_FIELDS, UPDATE_FIELDS ).async_setup(hass) async def reload_service_handler(service_call: ServiceCallType) -> None: """Reload yaml entities.""" conf = await component.async_prepare_reload(skip_reset=True) if conf is None: conf = {DOMAIN: {}} await yaml_collection.async_load( [{CONF_ID: id_, **cfg} for id_, cfg in conf.get(DOMAIN, {}).items()] ) homeassistant.helpers.service.async_register_admin_service( hass, DOMAIN, SERVICE_RELOAD, reload_service_handler, schema=RELOAD_SERVICE_SCHEMA, ) component.async_register_entity_service( SERVICE_SELECT_OPTION, {vol.Required(ATTR_OPTION): cv.string}, "async_select_option", ) component.async_register_entity_service( SERVICE_SELECT_NEXT, {vol.Optional(ATTR_CYCLE, default=True): bool}, "async_next", ) component.async_register_entity_service( SERVICE_SELECT_PREVIOUS, {vol.Optional(ATTR_CYCLE, default=True): bool}, "async_previous", ) component.async_register_entity_service( SERVICE_SELECT_FIRST, {}, callback(lambda entity, call: entity.async_select_index(0)), ) component.async_register_entity_service( SERVICE_SELECT_LAST, {}, callback(lambda entity, call: entity.async_select_index(-1)), ) component.async_register_entity_service( SERVICE_SET_OPTIONS, { vol.Required(ATTR_OPTIONS): vol.All( cv.ensure_list, vol.Length(min=1), [cv.string] ) }, "async_set_options", ) return True class InputSelectStorageCollection(collection.StorageCollection): """Input storage based collection.""" CREATE_SCHEMA = vol.Schema(vol.All(CREATE_FIELDS, _cv_input_select)) UPDATE_SCHEMA = vol.Schema(UPDATE_FIELDS) async def _process_create_data(self, data: dict) -> dict: """Validate the config is valid.""" return self.CREATE_SCHEMA(data) @callback def _get_suggested_id(self, info: dict) -> str: """Suggest an ID based on the config.""" return info[CONF_NAME] async def _update_data(self, data: dict, update_data: dict) -> dict: """Return a new updated data object.""" update_data = self.UPDATE_SCHEMA(update_data) return _cv_input_select({**data, **update_data}) class InputSelect(RestoreEntity): """Representation of a select input.""" def __init__(self, config: dict): """Initialize a select input.""" self._config = config self.editable = True self._current_option = config.get(CONF_INITIAL) @classmethod def from_yaml(cls, config: dict) -> InputSelect: """Return entity instance initialized from yaml storage.""" input_select = cls(config) input_select.entity_id = f"{DOMAIN}.{config[CONF_ID]}" input_select.editable = False return input_select async def async_added_to_hass(self): """Run when entity about to be added.""" await super().async_added_to_hass() if self._current_option is not None: return state = await self.async_get_last_state() if not state or state.state not in self._options: self._current_option = self._options[0] else: self._current_option = state.state @property def should_poll(self): """If entity should be polled.""" return False @property def name(self): """Return the name of the select input.""" return self._config.get(CONF_NAME) @property def icon(self): """Return the icon to be used for this entity.""" return self._config.get(CONF_ICON) @property def _options(self) -> list[str]: """Return a list of selection options.""" return self._config[CONF_OPTIONS] @property def state(self): """Return the state of the component.""" return self._current_option @property def extra_state_attributes(self): """Return the state attributes.""" return {ATTR_OPTIONS: self._config[ATTR_OPTIONS], ATTR_EDITABLE: self.editable} @property def unique_id(self) -> str | None: """Return unique id for the entity.""" return self._config[CONF_ID] @callback def async_select_option(self, option): """Select new option.""" if option not in self._options: _LOGGER.warning( "Invalid option: %s (possible options: %s)", option, ", ".join(self._options), ) return self._current_option = option self.async_write_ha_state() @callback def async_select_index(self, idx): """Select new option by index.""" new_index = idx % len(self._options) self._current_option = self._options[new_index] self.async_write_ha_state() @callback def async_offset_index(self, offset, cycle): """Offset current index.""" current_index = self._options.index(self._current_option) new_index = current_index + offset if cycle: new_index = new_index % len(self._options) else: if new_index < 0: new_index = 0 elif new_index >= len(self._options): new_index = len(self._options) - 1 self._current_option = self._options[new_index] self.async_write_ha_state() @callback def async_next(self, cycle): """Select next option.""" self.async_offset_index(1, cycle) @callback def async_previous(self, cycle): """Select previous option.""" self.async_offset_index(-1, cycle) @callback def async_set_options(self, options): """Set options.""" self._current_option = options[0] self._config[CONF_OPTIONS] = options self.async_write_ha_state() async def async_update_config(self, config: dict) -> None: """Handle when the config is updated.""" self._config = config self.async_write_ha_state()
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/input_select/__init__.py
"""BleBox climate entity.""" from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( CURRENT_HVAC_HEAT, CURRENT_HVAC_IDLE, CURRENT_HVAC_OFF, HVAC_MODE_HEAT, HVAC_MODE_OFF, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS from . import BleBoxEntity, create_blebox_entities async def async_setup_entry(hass, config_entry, async_add_entities): """Set up a BleBox climate entity.""" create_blebox_entities( hass, config_entry, async_add_entities, BleBoxClimateEntity, "climates" ) class BleBoxClimateEntity(BleBoxEntity, ClimateEntity): """Representation of a BleBox climate feature (saunaBox).""" @property def supported_features(self): """Return the supported climate features.""" return SUPPORT_TARGET_TEMPERATURE @property def hvac_mode(self): """Return the desired HVAC mode.""" if self._feature.is_on is None: return None return HVAC_MODE_HEAT if self._feature.is_on else HVAC_MODE_OFF @property def hvac_action(self): """Return the actual current HVAC action.""" is_on = self._feature.is_on if not is_on: return None if is_on is None else CURRENT_HVAC_OFF # NOTE: In practice, there's no need to handle case when is_heating is None return CURRENT_HVAC_HEAT if self._feature.is_heating else CURRENT_HVAC_IDLE @property def hvac_modes(self): """Return a list of possible HVAC modes.""" return [HVAC_MODE_OFF, HVAC_MODE_HEAT] @property def temperature_unit(self): """Return the temperature unit.""" return TEMP_CELSIUS @property def max_temp(self): """Return the maximum temperature supported.""" return self._feature.max_temp @property def min_temp(self): """Return the maximum temperature supported.""" return self._feature.min_temp @property def current_temperature(self): """Return the current temperature.""" return self._feature.current @property def target_temperature(self): """Return the desired thermostat temperature.""" return self._feature.desired async def async_set_hvac_mode(self, hvac_mode): """Set the climate entity mode.""" if hvac_mode == HVAC_MODE_HEAT: await self._feature.async_on() return await self._feature.async_off() async def async_set_temperature(self, **kwargs): """Set the thermostat temperature.""" value = kwargs[ATTR_TEMPERATURE] await self._feature.async_set_temperature(value)
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/blebox/climate.py
"""Component to embed TP-Link smart home devices.""" import logging import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_HOST import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType, HomeAssistantType from .common import ( ATTR_CONFIG, CONF_DIMMER, CONF_DISCOVERY, CONF_LIGHT, CONF_STRIP, CONF_SWITCH, SmartDevices, async_discover_devices, get_static_devices, ) _LOGGER = logging.getLogger(__name__) DOMAIN = "tplink" TPLINK_HOST_SCHEMA = vol.Schema({vol.Required(CONF_HOST): cv.string}) CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Optional(CONF_LIGHT, default=[]): vol.All( cv.ensure_list, [TPLINK_HOST_SCHEMA] ), vol.Optional(CONF_SWITCH, default=[]): vol.All( cv.ensure_list, [TPLINK_HOST_SCHEMA] ), vol.Optional(CONF_STRIP, default=[]): vol.All( cv.ensure_list, [TPLINK_HOST_SCHEMA] ), vol.Optional(CONF_DIMMER, default=[]): vol.All( cv.ensure_list, [TPLINK_HOST_SCHEMA] ), vol.Optional(CONF_DISCOVERY, default=True): cv.boolean, } ) }, extra=vol.ALLOW_EXTRA, ) async def async_setup(hass, config): """Set up the TP-Link component.""" conf = config.get(DOMAIN) hass.data[DOMAIN] = {} hass.data[DOMAIN][ATTR_CONFIG] = conf if conf is not None: hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_IMPORT} ) ) return True async def async_setup_entry(hass: HomeAssistantType, config_entry: ConfigType): """Set up TPLink from a config entry.""" config_data = hass.data[DOMAIN].get(ATTR_CONFIG) # These will contain the initialized devices lights = hass.data[DOMAIN][CONF_LIGHT] = [] switches = hass.data[DOMAIN][CONF_SWITCH] = [] # Add static devices static_devices = SmartDevices() if config_data is not None: static_devices = get_static_devices(config_data) lights.extend(static_devices.lights) switches.extend(static_devices.switches) # Add discovered devices if config_data is None or config_data[CONF_DISCOVERY]: discovered_devices = await async_discover_devices(hass, static_devices) lights.extend(discovered_devices.lights) switches.extend(discovered_devices.switches) forward_setup = hass.config_entries.async_forward_entry_setup if lights: _LOGGER.debug( "Got %s lights: %s", len(lights), ", ".join([d.host for d in lights]) ) hass.async_create_task(forward_setup(config_entry, "light")) if switches: _LOGGER.debug( "Got %s switches: %s", len(switches), ", ".join([d.host for d in switches]) ) hass.async_create_task(forward_setup(config_entry, "switch")) return True async def async_unload_entry(hass, entry): """Unload a config entry.""" forward_unload = hass.config_entries.async_forward_entry_unload remove_lights = remove_switches = False if hass.data[DOMAIN][CONF_LIGHT]: remove_lights = await forward_unload(entry, "light") if hass.data[DOMAIN][CONF_SWITCH]: remove_switches = await forward_unload(entry, "switch") if remove_lights or remove_switches: hass.data[DOMAIN].clear() return True # We were not able to unload the platforms, either because there # were none or one of the forward_unloads failed. return False
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/tplink/__init__.py
"""Network utilities.""" from __future__ import annotations from ipaddress import IPv4Address, IPv6Address, ip_address, ip_network import yarl # RFC6890 - IP addresses of loopback interfaces LOOPBACK_NETWORKS = ( ip_network("127.0.0.0/8"), ip_network("::1/128"), ip_network("::ffff:127.0.0.0/104"), ) # RFC6890 - Address allocation for Private Internets PRIVATE_NETWORKS = ( ip_network("fd00::/8"), ip_network("10.0.0.0/8"), ip_network("172.16.0.0/12"), ip_network("192.168.0.0/16"), ) # RFC6890 - Link local ranges LINK_LOCAL_NETWORK = ip_network("169.254.0.0/16") def is_loopback(address: IPv4Address | IPv6Address) -> bool: """Check if an address is a loopback address.""" return any(address in network for network in LOOPBACK_NETWORKS) def is_private(address: IPv4Address | IPv6Address) -> bool: """Check if an address is a private address.""" return any(address in network for network in PRIVATE_NETWORKS) def is_link_local(address: IPv4Address | IPv6Address) -> bool: """Check if an address is link local.""" return address in LINK_LOCAL_NETWORK def is_local(address: IPv4Address | IPv6Address) -> bool: """Check if an address is loopback or private.""" return is_loopback(address) or is_private(address) def is_invalid(address: IPv4Address | IPv6Address) -> bool: """Check if an address is invalid.""" return bool(address == ip_address("0.0.0.0")) def is_ip_address(address: str) -> bool: """Check if a given string is an IP address.""" try: ip_address(address) except ValueError: return False return True def normalize_url(address: str) -> str: """Normalize a given URL.""" url = yarl.URL(address.rstrip("/")) if url.is_default_port(): return str(url.with_port(None)) return str(url)
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/util/network.py
"""Support for the Daikin HVAC.""" import logging import voluptuous as vol from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateEntity from homeassistant.components.climate.const import ( ATTR_FAN_MODE, ATTR_HVAC_MODE, ATTR_PRESET_MODE, ATTR_SWING_MODE, HVAC_MODE_COOL, HVAC_MODE_DRY, HVAC_MODE_FAN_ONLY, HVAC_MODE_HEAT, HVAC_MODE_HEAT_COOL, HVAC_MODE_OFF, PRESET_AWAY, PRESET_BOOST, PRESET_ECO, PRESET_NONE, SUPPORT_FAN_MODE, SUPPORT_PRESET_MODE, SUPPORT_SWING_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ATTR_TEMPERATURE, CONF_HOST, CONF_NAME, TEMP_CELSIUS import homeassistant.helpers.config_validation as cv from . import DOMAIN as DAIKIN_DOMAIN from .const import ( ATTR_INSIDE_TEMPERATURE, ATTR_OUTSIDE_TEMPERATURE, ATTR_STATE_OFF, ATTR_STATE_ON, ATTR_TARGET_TEMPERATURE, ) _LOGGER = logging.getLogger(__name__) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_NAME): cv.string} ) HA_STATE_TO_DAIKIN = { HVAC_MODE_FAN_ONLY: "fan", HVAC_MODE_DRY: "dry", HVAC_MODE_COOL: "cool", HVAC_MODE_HEAT: "hot", HVAC_MODE_HEAT_COOL: "auto", HVAC_MODE_OFF: "off", } DAIKIN_TO_HA_STATE = { "fan": HVAC_MODE_FAN_ONLY, "dry": HVAC_MODE_DRY, "cool": HVAC_MODE_COOL, "hot": HVAC_MODE_HEAT, "auto": HVAC_MODE_HEAT_COOL, "off": HVAC_MODE_OFF, } HA_PRESET_TO_DAIKIN = { PRESET_AWAY: "on", PRESET_NONE: "off", PRESET_BOOST: "powerful", PRESET_ECO: "econo", } HA_ATTR_TO_DAIKIN = { ATTR_PRESET_MODE: "en_hol", ATTR_HVAC_MODE: "mode", ATTR_FAN_MODE: "f_rate", ATTR_SWING_MODE: "f_dir", ATTR_INSIDE_TEMPERATURE: "htemp", ATTR_OUTSIDE_TEMPERATURE: "otemp", ATTR_TARGET_TEMPERATURE: "stemp", } DAIKIN_ATTR_ADVANCED = "adv" async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Old way of setting up the Daikin HVAC platform. Can only be called when a user accidentally mentions the platform in their config. But even in that case it would have been ignored. """ async def async_setup_entry(hass, entry, async_add_entities): """Set up Daikin climate based on config_entry.""" daikin_api = hass.data[DAIKIN_DOMAIN].get(entry.entry_id) async_add_entities([DaikinClimate(daikin_api)], update_before_add=True) class DaikinClimate(ClimateEntity): """Representation of a Daikin HVAC.""" def __init__(self, api): """Initialize the climate device.""" self._api = api self._list = { ATTR_HVAC_MODE: list(HA_STATE_TO_DAIKIN), ATTR_FAN_MODE: self._api.device.fan_rate, ATTR_SWING_MODE: self._api.device.swing_modes, } self._supported_features = SUPPORT_TARGET_TEMPERATURE if ( self._api.device.support_away_mode or self._api.device.support_advanced_modes ): self._supported_features |= SUPPORT_PRESET_MODE if self._api.device.support_fan_rate: self._supported_features |= SUPPORT_FAN_MODE if self._api.device.support_swing_mode: self._supported_features |= SUPPORT_SWING_MODE async def _set(self, settings): """Set device settings using API.""" values = {} for attr in [ATTR_TEMPERATURE, ATTR_FAN_MODE, ATTR_SWING_MODE, ATTR_HVAC_MODE]: value = settings.get(attr) if value is None: continue daikin_attr = HA_ATTR_TO_DAIKIN.get(attr) if daikin_attr is not None: if attr == ATTR_HVAC_MODE: values[daikin_attr] = HA_STATE_TO_DAIKIN[value] elif value in self._list[attr]: values[daikin_attr] = value.lower() else: _LOGGER.error("Invalid value %s for %s", attr, value) # temperature elif attr == ATTR_TEMPERATURE: try: values[HA_ATTR_TO_DAIKIN[ATTR_TARGET_TEMPERATURE]] = str(int(value)) except ValueError: _LOGGER.error("Invalid temperature %s", value) if values: await self._api.device.set(values) @property def supported_features(self): """Return the list of supported features.""" return self._supported_features @property def name(self): """Return the name of the thermostat, if any.""" return self._api.name @property def unique_id(self): """Return a unique ID.""" return self._api.device.mac @property def temperature_unit(self): """Return the unit of measurement which this thermostat uses.""" return TEMP_CELSIUS @property def current_temperature(self): """Return the current temperature.""" return self._api.device.inside_temperature @property def target_temperature(self): """Return the temperature we try to reach.""" return self._api.device.target_temperature @property def target_temperature_step(self): """Return the supported step of target temperature.""" return 1 async def async_set_temperature(self, **kwargs): """Set new target temperature.""" await self._set(kwargs) @property def hvac_mode(self): """Return current operation ie. heat, cool, idle.""" daikin_mode = self._api.device.represent(HA_ATTR_TO_DAIKIN[ATTR_HVAC_MODE])[1] return DAIKIN_TO_HA_STATE.get(daikin_mode, HVAC_MODE_HEAT_COOL) @property def hvac_modes(self): """Return the list of available operation modes.""" return self._list.get(ATTR_HVAC_MODE) async def async_set_hvac_mode(self, hvac_mode): """Set HVAC mode.""" await self._set({ATTR_HVAC_MODE: hvac_mode}) @property def fan_mode(self): """Return the fan setting.""" return self._api.device.represent(HA_ATTR_TO_DAIKIN[ATTR_FAN_MODE])[1].title() async def async_set_fan_mode(self, fan_mode): """Set fan mode.""" await self._set({ATTR_FAN_MODE: fan_mode}) @property def fan_modes(self): """List of available fan modes.""" return self._list.get(ATTR_FAN_MODE) @property def swing_mode(self): """Return the fan setting.""" return self._api.device.represent(HA_ATTR_TO_DAIKIN[ATTR_SWING_MODE])[1].title() async def async_set_swing_mode(self, swing_mode): """Set new target temperature.""" await self._set({ATTR_SWING_MODE: swing_mode}) @property def swing_modes(self): """List of available swing modes.""" return self._list.get(ATTR_SWING_MODE) @property def preset_mode(self): """Return the preset_mode.""" if ( self._api.device.represent(HA_ATTR_TO_DAIKIN[ATTR_PRESET_MODE])[1] == HA_PRESET_TO_DAIKIN[PRESET_AWAY] ): return PRESET_AWAY if ( HA_PRESET_TO_DAIKIN[PRESET_BOOST] in self._api.device.represent(DAIKIN_ATTR_ADVANCED)[1] ): return PRESET_BOOST if ( HA_PRESET_TO_DAIKIN[PRESET_ECO] in self._api.device.represent(DAIKIN_ATTR_ADVANCED)[1] ): return PRESET_ECO return PRESET_NONE async def async_set_preset_mode(self, preset_mode): """Set preset mode.""" if preset_mode == PRESET_AWAY: await self._api.device.set_holiday(ATTR_STATE_ON) elif preset_mode == PRESET_BOOST: await self._api.device.set_advanced_mode( HA_PRESET_TO_DAIKIN[PRESET_BOOST], ATTR_STATE_ON ) elif preset_mode == PRESET_ECO: await self._api.device.set_advanced_mode( HA_PRESET_TO_DAIKIN[PRESET_ECO], ATTR_STATE_ON ) else: if self.preset_mode == PRESET_AWAY: await self._api.device.set_holiday(ATTR_STATE_OFF) elif self.preset_mode == PRESET_BOOST: await self._api.device.set_advanced_mode( HA_PRESET_TO_DAIKIN[PRESET_BOOST], ATTR_STATE_OFF ) elif self.preset_mode == PRESET_ECO: await self._api.device.set_advanced_mode( HA_PRESET_TO_DAIKIN[PRESET_ECO], ATTR_STATE_OFF ) @property def preset_modes(self): """List of available preset modes.""" ret = [PRESET_NONE] if self._api.device.support_away_mode: ret.append(PRESET_AWAY) if self._api.device.support_advanced_modes: ret += [PRESET_ECO, PRESET_BOOST] return ret async def async_update(self): """Retrieve latest state.""" await self._api.async_update() async def async_turn_on(self): """Turn device on.""" await self._api.device.set({}) async def async_turn_off(self): """Turn device off.""" await self._api.device.set( {HA_ATTR_TO_DAIKIN[ATTR_HVAC_MODE]: HA_STATE_TO_DAIKIN[HVAC_MODE_OFF]} ) @property def device_info(self): """Return a device description for device registry.""" return self._api.device_info
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/daikin/climate.py
"""Describe group states.""" from homeassistant.components.group import GroupIntegrationRegistry from homeassistant.const import STATE_OFF from homeassistant.core import callback from homeassistant.helpers.typing import HomeAssistantType from . import ( STATE_ECO, STATE_ELECTRIC, STATE_GAS, STATE_HEAT_PUMP, STATE_HIGH_DEMAND, STATE_PERFORMANCE, ) @callback def async_describe_on_off_states( hass: HomeAssistantType, registry: GroupIntegrationRegistry ) -> None: """Describe group on off states.""" registry.on_off_states( { STATE_ECO, STATE_ELECTRIC, STATE_PERFORMANCE, STATE_HIGH_DEMAND, STATE_HEAT_PUMP, STATE_GAS, }, STATE_OFF, )
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/water_heater/group.py
"""Describe logbook events.""" from homeassistant.core import callback from .const import DOMAIN, EVENT_ALEXA_SMART_HOME @callback def async_describe_events(hass, async_describe_event): """Describe logbook events.""" @callback def async_describe_logbook_event(event): """Describe a logbook event.""" data = event.data entity_id = data["request"].get("entity_id") if entity_id: state = hass.states.get(entity_id) name = state.name if state else entity_id message = f"send command {data['request']['namespace']}/{data['request']['name']} for {name}" else: message = ( f"send command {data['request']['namespace']}/{data['request']['name']}" ) return {"name": "Amazon Alexa", "message": message, "entity_id": entity_id} async_describe_event(DOMAIN, EVENT_ALEXA_SMART_HOME, async_describe_logbook_event)
"""Tests for iZone.""" from unittest.mock import Mock, patch import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.izone.const import DISPATCH_CONTROLLER_DISCOVERED, IZONE @pytest.fixture def mock_disco(): """Mock discovery service.""" disco = Mock() disco.pi_disco = Mock() disco.pi_disco.controllers = {} yield disco def _mock_start_discovery(hass, mock_disco): from homeassistant.helpers.dispatcher import async_dispatcher_send def do_disovered(*args): async_dispatcher_send(hass, DISPATCH_CONTROLLER_DISCOVERED, True) return mock_disco return do_disovered async def test_not_found(hass, mock_disco): """Test not finding iZone controller.""" with patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.config_flow.async_stop_discovery_service", return_value=None, ) as stop_disco: start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT await hass.async_block_till_done() stop_disco.assert_called_once() async def test_found(hass, mock_disco): """Test not finding iZone controller.""" mock_disco.pi_disco.controllers["blah"] = object() with patch( "homeassistant.components.izone.climate.async_setup_entry", return_value=True, ) as mock_setup, patch( "homeassistant.components.izone.config_flow.async_start_discovery_service" ) as start_disco, patch( "homeassistant.components.izone.async_start_discovery_service", return_value=None, ): start_disco.side_effect = _mock_start_discovery(hass, mock_disco) result = await hass.config_entries.flow.async_init( IZONE, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() mock_setup.assert_called_once()
w1ll1am23/home-assistant
tests/components/izone/test_config_flow.py
homeassistant/components/alexa/logbook.py
# -*- coding: utf-8 -*- import re import six import xmlrpclib from github import Github from urlparse import urlparse from fixtures.pytest_store import store from cfme.utils import classproperty, conf, version from cfme.utils.bz import Bugzilla from cfme.utils.log import logger class Blocker(object): """Base class for all blockers REQUIRED THING! Any subclass' constructors must accept kwargs and after POPping the values required for the blocker's operation, `call to ``super`` with ``**kwargs`` must be done! Failing to do this will render some of the functionality disabled ;). """ blocks = False kwargs = {} def __init__(self, **kwargs): self.forced_streams = kwargs.pop("forced_streams", []) self.__dict__["kwargs"] = kwargs @property def url(self): raise NotImplementedError('You need to implement .url') @classmethod def all_blocker_engines(cls): """Return mapping of name:class of all the blocker engines in this module. Having this as a separate function will later enable to scatter the engines across modules in case of extraction into a separate library. """ return { 'GH': GH, 'BZ': BZ, } @classmethod def parse(cls, blocker, **kwargs): """Create a blocker object from some representation""" if isinstance(blocker, cls): return blocker elif isinstance(blocker, six.string_types): if "#" in blocker: # Generic blocker engine, spec = blocker.split("#", 1) try: engine_class = cls.all_blocker_engines()[engine] except KeyError: raise ValueError( "{} is a wrong engine specification for blocker! ({} available)".format( engine, ", ".join(cls.all_blocker_engines().keys()))) return engine_class(spec, **kwargs) # EXTEND: If someone has other ideas, put them here raise ValueError("Could not parse blocker {}".format(blocker)) else: raise ValueError("Wrong specification of the blockers!") class GH(Blocker): DEFAULT_REPOSITORY = conf.env.get("github", {}).get("default_repo") _issue_cache = {} @classproperty def github(cls): if not hasattr(cls, "_github"): token = conf.env.get("github", {}).get("token") if token is not None: cls._github = Github(token) else: cls._github = Github() # Without auth max 60 req/hr return cls._github def __init__(self, description, **kwargs): super(GH, self).__init__(**kwargs) self._repo = None self.issue = None self.upstream_only = kwargs.get('upstream_only', True) self.since = kwargs.get('since') self.until = kwargs.get('until') if isinstance(description, (list, tuple)): try: self.repo, self.issue = description self.issue = int(self.issue) except ValueError: raise ValueError( "The GH issue specification must have 2 items and issue must be number") elif isinstance(description, int): if self.DEFAULT_REPOSITORY is None: raise ValueError("You must specify github/default_repo in env.yaml!") self.issue = description elif isinstance(description, basestring): try: owner, repo, issue_num = re.match(r"^([^/]+)/([^/:]+):([0-9]+)$", str(description).strip()).groups() except AttributeError: raise ValueError( "Could not parse '{}' as a proper GH issue anchor!".format(str(description))) else: self._repo = "{}/{}".format(owner, repo) self.issue = int(issue_num) else: raise ValueError("GH issue specified wrong") @property def data(self): identifier = "{}:{}".format(self.repo, self.issue) if identifier not in self._issue_cache: self._issue_cache[identifier] = self.github.get_repo(self.repo).get_issue(self.issue) return self._issue_cache[identifier] @property def blocks(self): if self.upstream_only and version.appliance_is_downstream(): return False if self.data.state == "closed": return False # Now let's check versions if self.since is None and self.until is None: # No version specifics return True elif self.since is not None and self.until is not None: # since inclusive, until exclusive return self.since <= version.current_version() < self.until elif self.since is not None: # Only since return version.current_version() >= self.since elif self.until is not None: # Only until return version.current_version() < self.until # All branches covered @property def repo(self): return self._repo or self.DEFAULT_REPOSITORY def __str__(self): return "GitHub Issue https://github.com/{}/issues/{}".format(self.repo, self.issue) @property def url(self): return "https://github.com/{}/issues/{}".format(self.repo, self.issue) class BZ(Blocker): @classproperty def bugzilla(cls): if not hasattr(cls, "_bugzilla"): cls._bugzilla = Bugzilla.from_config() return cls._bugzilla def __init__(self, bug_id, **kwargs): self.ignore_bugs = kwargs.pop("ignore_bugs", []) super(BZ, self).__init__(**kwargs) self.bug_id = int(bug_id) @property def data(self): return self.bugzilla.resolve_blocker( self.bug_id, ignore_bugs=self.ignore_bugs, force_block_streams=self.forced_streams) @property def bugzilla_bug(self): if self.data is None: return None return self.data @property def blocks(self): try: bug = self.data if bug is None: return False result = False if bug.is_opened: result = True if bug.upstream_bug: if not version.appliance_is_downstream() and bug.can_test_on_upstream: result = False if result is False and version.appliance_is_downstream(): if bug.fixed_in is not None: return version.current_version() < bug.fixed_in return result except xmlrpclib.Fault as e: code = e.faultCode s = e.faultString.strip().split("\n")[0] logger.error("Bugzilla thrown a fault: %s/%s", code, s) logger.warning("Ignoring and taking the bug as non-blocking") store.terminalreporter.write( "Bugzila made a booboo: {}/{}\n".format(code, s), bold=True) return False def get_bug_url(self): bz_url = urlparse(self.bugzilla.bugzilla.url) return "{}://{}/show_bug.cgi?id={}".format(bz_url.scheme, bz_url.netloc, self.bug_id) @property def url(self): return self.get_bug_url() def __str__(self): return "Bugzilla bug {} (or one of its copies)".format(self.get_bug_url())
import fauxfactory import pytest from cfme.cloud.provider.openstack import OpenStackProvider from cfme.utils.update import update from cfme.cloud.tenant import TenantCollection from cfme.utils import testgen from cfme.utils.log import logger from cfme.utils.version import current_version pytest_generate_tests = testgen.generate([OpenStackProvider], scope='module') @pytest.yield_fixture(scope='function') def tenant(provider, setup_provider, appliance): collection = TenantCollection(appliance=appliance) tenant = collection.create(name=fauxfactory.gen_alphanumeric(8), provider=provider) yield tenant try: if tenant.exists: tenant.delete() except Exception: logger.warning( 'Exception while attempting to delete tenant fixture, continuing') finally: if tenant.name in provider.mgmt.list_tenant(): provider.mgmt.remove_tenant(tenant.name) @pytest.mark.uncollectif(lambda: current_version() < '5.7') def test_tenant_crud(tenant): """ Tests tenant create and delete Metadata: test_flag: tenant """ with update(tenant): tenant.name = fauxfactory.gen_alphanumeric(8) tenant.wait_for_appear() assert tenant.exists
okolisny/integration_tests
cfme/tests/cloud/test_tenant.py
cfme/utils/blockers.py
import tempfile from os import listdir, mkdir, makedirs, path from shutil import copy, copyfile, rmtree from subprocess import check_output, CalledProcessError, STDOUT import sys from fauxfactory import gen_alphanumeric from cfme.utils import conf from cfme.utils.providers import providers_data from git import Repo from yaml import load, dump local_git_repo = "manageiq_ansible_module" yml_path = path.join(path.dirname(__file__), local_git_repo) yml_templates_path = path.join(path.dirname(__file__), 'ansible_conf') basic_script = "basic_script.yml" yml = ".yml" random_token = str(gen_alphanumeric(906)) random_miq_user = str(gen_alphanumeric(8)) pulled_repo_library_path = path.join(local_git_repo, 'library') remote_git_repo_url = "git://github.com/dkorn/manageiq-ansible-module.git" def create_tmp_directory(): global lib_path lib_path = tempfile.mkdtemp() lib_sub_path = 'ansible_conf' lib_sub_path_library = path.join(lib_sub_path, 'library') makedirs(path.join((lib_path), lib_sub_path_library)) global library_path_to_copy_to global basic_yml_path library_path_to_copy_to = path.join(lib_path, lib_sub_path_library) basic_yml_path = path.join(lib_path, lib_sub_path) def fetch_miq_ansible_module(): if path.isdir(local_git_repo): rmtree(local_git_repo) mkdir(local_git_repo) if path.isdir(library_path_to_copy_to): rmtree(library_path_to_copy_to) mkdir(library_path_to_copy_to) Repo.clone_from(remote_git_repo_url, local_git_repo) src_files = listdir(pulled_repo_library_path) for file_name in src_files: full_file_name = path.join(pulled_repo_library_path, file_name) if path.isfile(full_file_name): copy(full_file_name, library_path_to_copy_to) rmtree(local_git_repo) def get_values_for_providers_test(provider): return { 'name': provider.name, 'state': 'present', 'miq_url': config_formatter(), 'miq_username': conf.credentials['default'].username, 'miq_password': conf.credentials['default'].password, 'provider_api_hostname': providers_data[provider.name]['endpoints']['default'].hostname, 'provider_api_port': providers_data[provider.name]['endpoints']['default'].api_port, 'provider_api_auth_token': providers_data[provider.name]['endpoints']['default'].token, 'monitoring_hostname': providers_data[provider.name]['endpoints']['hawkular'].hostname, 'monitoring_port': providers_data[provider.name]['endpoints']['hawkular'].api_port } def get_values_for_users_test(): return { 'fullname': 'MIQUser', 'name': 'MIQU', 'password': 'smartvm', 'state': 'present', 'miq_url': config_formatter(), 'miq_username': conf.credentials['default'].username, 'miq_password': conf.credentials['default'].password, } def get_values_for_custom_attributes_test(provider): return { 'entity_type': 'provider', 'entity_name': conf.cfme_data.get('management_systems', {}) [provider.key].get('name', []), 'miq_url': config_formatter(), 'miq_username': conf.credentials['default'].username, 'miq_password': conf.credentials['default'].password, } def get_values_for_tags_test(provider): return { 'resource': 'provider', 'resource_name': provider.name, 'miq_url': config_formatter(), 'miq_username': conf.credentials['default'].username, 'miq_password': conf.credentials['default'].password, } def get_values_from_conf(provider, script_type): if script_type == 'providers': return get_values_for_providers_test(provider) if script_type == 'users': return get_values_for_users_test() if script_type == 'custom_attributes': return get_values_for_custom_attributes_test(provider) if script_type == 'tags': return get_values_for_tags_test(provider) # TODO Avoid reading files every time def read_yml(script, value): with open(yml_path + script + yml, 'r') as f: doc = load(f) return doc[0]['tasks'][0]['manageiq_provider'][value] def get_yml_value(script, value): with open(path.join(basic_yml_path, script) + yml, 'r') as f: doc = load(f) return doc[0]['tasks'][0]['manageiq_provider'][value] def setup_basic_script(provider, script_type): script_path_source = path.join(yml_templates_path, script_type + "_" + basic_script) script_path = path.join(basic_yml_path, script_type + "_" + basic_script) copyfile(script_path_source, script_path) with open(script_path, 'rw') as f: doc = load(f) values_dict = get_values_from_conf(provider, script_type) for key in values_dict: if script_type == 'providers': doc[0]['tasks'][0]['manageiq_provider'][key] = values_dict[key] elif script_type == 'users': doc[0]['tasks'][0]['manageiq_user'][key] = values_dict[key] elif script_type == 'custom_attributes': doc[0]['tasks'][0]['manageiq_custom_attributes'][key] = values_dict[key] elif script_type == 'tags': doc[0]['tasks'][0]['manageiq_tag_assignment'][key] = values_dict[key] with open(script_path, 'w') as f: f.write(dump(doc)) def open_yml(script, script_type): copyfile((path.join(basic_yml_path, script_type + "_" + basic_script)), path.join(basic_yml_path, script + yml)) with open(path.join(basic_yml_path, script + yml), 'rw') as f: return load(f) def write_yml(script, doc): with open(path.join(basic_yml_path, script + yml), 'w') as f: f.write(dump(doc)) def setup_ansible_script(provider, script, script_type=None, values_to_update=None): # This function prepares the ansible scripts to work with the correct # appliance configs that will be received from Jenkins setup_basic_script(provider, script_type) doc = open_yml(script, script_type) if script == 'add_provider': write_yml(script, doc) if script == 'add_provider_ssl': doc[0]['tasks'][0]['manageiq_provider']['provider_verify_ssl'] = 'True' write_yml(script, doc) elif script == 'update_provider': for key in values_to_update: doc[0]['tasks'][0]['manageiq_provider'][key] = values_to_update[key] write_yml(script, doc) elif script == 'remove_provider': doc[0]['tasks'][0]['manageiq_provider']['state'] = 'absent' write_yml(script, doc) elif script == 'remove_non_existing_provider': doc[0]['tasks'][0]['manageiq_provider']['state'] = 'absent' doc[0]['tasks'][0]['manageiq_provider']['name'] = random_miq_user write_yml(script, doc) elif script == 'remove_provider_bad_user': doc[0]['tasks'][0]['manageiq_provider']['miq_username'] = random_miq_user write_yml(script, doc) elif script == 'add_provider_bad_token': doc[0]['tasks'][0]['manageiq_provider']['provider_api_auth_token'] = random_token write_yml(script, doc) elif script == 'add_provider_bad_user': doc[0]['tasks'][0]['manageiq_provider']['miq_username'] = random_miq_user write_yml(script, doc) elif script == 'update_non_existing_provider': doc[0]['tasks'][0]['manageiq_provider']['provider_api_hostname'] = random_miq_user write_yml(script, doc) elif script == 'update_provider_bad_user': for key in values_to_update: doc[0]['tasks'][0]['manageiq_provider'][key] = values_to_update[key] doc[0]['tasks'][0]['manageiq_provider']['miq_username'] = random_miq_user write_yml(script, doc) elif script == 'create_user': for key in values_to_update: doc[0]['tasks'][0]['manageiq_user'][key] = values_to_update[key] write_yml(script, doc) elif script == 'update_user': for key in values_to_update: doc[0]['tasks'][0]['manageiq_user'][key] = values_to_update[key] write_yml(script, doc) elif script == 'create_user_bad_user_name': doc[0]['tasks'][0]['manageiq_user']['miq_username'] = random_miq_user for key in values_to_update: doc[0]['tasks'][0]['manageiq_user'][key] = values_to_update[key] write_yml(script, doc) elif script == 'delete_user': doc[0]['tasks'][0]['manageiq_user']['name'] = values_to_update doc[0]['tasks'][0]['manageiq_user']['state'] = 'absent' write_yml(script, doc) elif script == 'add_custom_attributes': count = 0 while count < len(values_to_update): for key in values_to_update: doc[0]['tasks'][0]['manageiq_custom_attributes']['custom_attributes'][count] = key count += 1 write_yml(script, doc) elif script == 'add_custom_attributes_bad_user': doc[0]['tasks'][0]['manageiq_custom_attributes']['miq_username'] = str(random_miq_user) write_yml(script, doc) elif script == 'remove_custom_attributes': count = 0 doc[0]['tasks'][0]['manageiq_custom_attributes']['state'] = 'absent' while count < len(values_to_update): for key in values_to_update: doc[0]['tasks'][0]['manageiq_custom_attributes']['custom_attributes'][count] = key count += 1 write_yml(script, doc) elif script == 'add_tags': count = 0 while count < len(values_to_update): for key in values_to_update: doc[0]['tasks'][0]['manageiq_tag_assignment']['tags'][count]['category'] = \ values_to_update[count]['category'] doc[0]['tasks'][0]['manageiq_tag_assignment']['tags'][count]['name'] = \ values_to_update[count]['name'] count += 1 doc[0]['tasks'][0]['manageiq_tag_assignment']['state'] = 'present' write_yml(script, doc) elif script == 'remove_tags': count = 0 while count < len(values_to_update): for key in values_to_update: doc[0]['tasks'][0]['manageiq_tag_assignment']['tags'][count]['category'] = \ values_to_update[count]['category'] doc[0]['tasks'][0]['manageiq_tag_assignment']['tags'][count]['name'] = \ values_to_update[count]['name'] count += 1 doc[0]['tasks'][0]['manageiq_tag_assignment']['state'] = 'absent' write_yml(script, doc) def run_ansible(script): ansible_playbook_cmd = "ansible-playbook -e ansible_python_interpreter=" interpreter_path = sys.executable script_path = path.join(basic_yml_path, script + ".yml") cmd = '{}{} {}'.format(ansible_playbook_cmd, interpreter_path, script_path) return run_cmd(cmd) def run_cmd(cmd): try: response = check_output(cmd, shell=True, stderr=STDOUT) except CalledProcessError as exc: print("Status : FAIL", exc.returncode, exc.output) return exc.output else: print("Output: \n{}\n".format(response)) # TODO For further usage with reply statuses test. Not being used at the moment def reply_status(reply): ok_status = reply['stats']['localhost']['ok'] changed_status = reply['stats']['localhost']['changed'] failures_status = reply['stats']['localhost']['failures'] skipped_status = reply['stats']['localhost']['skipped'] message_status = reply['plays'][0]['tasks'][2]['hosts']['localhost']['result']['msg'] if not ok_status == '0': ok_status = 'OK' else: ok_status = 'Failed' if changed_status: return 'Changed', message_status, ok_status elif skipped_status: return 'Skipped', message_status, ok_status elif failures_status: return 'Failed', message_status, ok_status else: return 'No Change', message_status, ok_status def config_formatter(): if "https://" in conf.env.get("base_url", None): return conf.env.get("base_url", None) else: return "https://" + conf.env.get("base_url", None) def remove_tmp_files(): rmtree(lib_path, ignore_errors=True)
import fauxfactory import pytest from cfme.cloud.provider.openstack import OpenStackProvider from cfme.utils.update import update from cfme.cloud.tenant import TenantCollection from cfme.utils import testgen from cfme.utils.log import logger from cfme.utils.version import current_version pytest_generate_tests = testgen.generate([OpenStackProvider], scope='module') @pytest.yield_fixture(scope='function') def tenant(provider, setup_provider, appliance): collection = TenantCollection(appliance=appliance) tenant = collection.create(name=fauxfactory.gen_alphanumeric(8), provider=provider) yield tenant try: if tenant.exists: tenant.delete() except Exception: logger.warning( 'Exception while attempting to delete tenant fixture, continuing') finally: if tenant.name in provider.mgmt.list_tenant(): provider.mgmt.remove_tenant(tenant.name) @pytest.mark.uncollectif(lambda: current_version() < '5.7') def test_tenant_crud(tenant): """ Tests tenant create and delete Metadata: test_flag: tenant """ with update(tenant): tenant.name = fauxfactory.gen_alphanumeric(8) tenant.wait_for_appear() assert tenant.exists
okolisny/integration_tests
cfme/tests/cloud/test_tenant.py
cfme/utils/ansible.py
"""Constants for Daikin.""" from homeassistant.const import CONF_ICON, CONF_NAME, CONF_TYPE ATTR_TARGET_TEMPERATURE = 'target_temperature' ATTR_INSIDE_TEMPERATURE = 'inside_temperature' ATTR_OUTSIDE_TEMPERATURE = 'outside_temperature' SENSOR_TYPE_TEMPERATURE = 'temperature' SENSOR_TYPES = { ATTR_INSIDE_TEMPERATURE: { CONF_NAME: 'Inside Temperature', CONF_ICON: 'mdi:thermometer', CONF_TYPE: SENSOR_TYPE_TEMPERATURE }, ATTR_OUTSIDE_TEMPERATURE: { CONF_NAME: 'Outside Temperature', CONF_ICON: 'mdi:thermometer', CONF_TYPE: SENSOR_TYPE_TEMPERATURE } } KEY_MAC = 'mac' KEY_IP = 'ip'
"""Tests for the Z-Wave init.""" import asyncio from collections import OrderedDict from datetime import datetime import unittest from unittest.mock import MagicMock, patch import pytest from pytz import utc import voluptuous as vol from homeassistant.bootstrap import async_setup_component from homeassistant.components import zwave from homeassistant.components.zwave import ( CONF_DEVICE_CONFIG_GLOB, CONFIG_SCHEMA, DATA_NETWORK, const) from homeassistant.components.zwave.binary_sensor import get_device from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.device_registry import ( async_get_registry as get_dev_reg) from homeassistant.setup import setup_component from tests.common import ( async_fire_time_changed, get_test_home_assistant, mock_coro, mock_registry) from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue async def test_valid_device_config(hass, mock_openzwave): """Test valid device config.""" device_config = { 'light.kitchen': { 'ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert result async def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = { 'light.kitchen': { 'some_ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert not result def test_config_access_error(): """Test threading error accessing config values.""" node = MagicMock() def side_effect(): raise RuntimeError node.values.values.side_effect = side_effect result = zwave.get_config_value(node, 1) assert result is None async def test_network_options(hass, mock_openzwave): """Test network options.""" result = await async_setup_component(hass, 'zwave', { 'zwave': { 'usb_path': 'mock_usb_path', 'config_path': 'mock_config_path', }}) await hass.async_block_till_done() assert result network = hass.data[zwave.DATA_NETWORK] assert network.options.device == 'mock_usb_path' assert network.options.config_path == 'mock_config_path' async def test_network_key_validation(hass, mock_openzwave): """Test network key validation.""" test_values = [ ('0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,' '0x0E,0x0F,0x10'), ] for value in test_values: result = zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) assert result['zwave']['network_key'] == value async def test_erronous_network_key_fails_validation(hass, mock_openzwave): """Test failing erronous network key validation.""" test_values = [ ('0x 01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0X01,0X02,0X03,0X04,0X05,0X06,0X07,0X08,0X09,0X0A,0X0B,0X0C,0X0D,' '0X0E,0X0F,0X10'), 'invalid', '1234567', 1234567 ] for value in test_values: with pytest.raises(vol.Invalid): zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) async def test_auto_heal_midnight(hass, mock_openzwave): """Test network auto-heal at midnight.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': True, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert network.heal.called assert len(network.heal.mock_calls) == 1 async def test_auto_heal_disabled(hass, mock_openzwave): """Test network auto-heal disabled.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': False, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert not network.heal.called async def test_setup_platform(hass, mock_openzwave): """Test invalid device config.""" mock_device = MagicMock() hass.data[DATA_NETWORK] = MagicMock() hass.data[zwave.DATA_DEVICES] = {456: mock_device} async_add_entities = MagicMock() result = await zwave.async_setup_platform( hass, None, async_add_entities, None) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 123}) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 456}) assert result assert async_add_entities.called assert len(async_add_entities.mock_calls) == 1 assert async_add_entities.mock_calls[0][1][0] == [mock_device] async def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): """Test device entity base class.""" node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.value_added() device.update_properties() await hass.async_block_till_done() assert not device.should_poll assert device.unique_id == "10-11" assert device.name == 'Mock Node Sensor' assert device.device_state_attributes[zwave.ATTR_POWER] == 50.123 async def test_node_removed(hass, mock_openzwave): """Test node removed in base class.""" # Create a mock node & node entity node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.entity_id = 'zwave.mock_node' device.value_added() device.update_properties() await hass.async_block_till_done() # Save it to the entity registry registry = mock_registry(hass) registry.async_get_or_create('zwave', 'zwave', device.unique_id) device.entity_id = registry.async_get_entity_id( 'zwave', 'zwave', device.unique_id) # Create dummy entity registry entries for other integrations hue_entity = registry.async_get_or_create('light', 'hue', 1234) zha_entity = registry.async_get_or_create('sensor', 'zha', 5678) # Verify our Z-Wave entity is registered assert registry.async_is_registered(device.entity_id) # Remove it entity_id = device.entity_id await device.node_removed() # Verify registry entry for our Z-Wave node is gone assert not registry.async_is_registered(entity_id) # Verify registry entries for our other entities remain assert registry.async_is_registered(hue_entity.entity_id) assert registry.async_is_registered(zha_entity.entity_id) async def test_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node').state == 'unknown' async def test_unparsed_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode( node_id=14, manufacturer_name=None, name=None, is_ready=False) sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert len(sleeps) == const.NODE_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1:] == \ (14, const.NODE_READY_WAIT_SECS) assert hass.states.get('zwave.unknown_node_14').state == 'unknown' async def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': { 'device_config': { 'zwave.mock_node': { 'ignored': True, }}}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None async def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' async def test_value_entities(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = {} def mock_connect(receiver, signal, *args, **kwargs): mock_receivers[signal] = receiver with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert mock_receivers hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_ALL_NODES_QUERIED]) node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) zwave_network.nodes = {node.node_id: node} value = MockValue( data=False, node=node, index=12, instance=1, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values = {'primary': value, value.value_id: value} value2 = MockValue( data=False, node=node, index=12, instance=2, label="Mock Value B", command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values[value2.value_id] = value2 hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_NODE_ADDED], node) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value2) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' assert hass.states.get( 'binary_sensor.mock_node_mock_value_b').state == 'off' ent_reg = await async_get_registry(hass) dev_reg = await get_dev_reg(hass) entry = ent_reg.async_get('zwave.mock_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) node_dev_id = entry.device_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) assert entry.name is None assert entry.device_id == node_dev_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value2.object_id) assert entry.name is None assert entry.device_id != node_dev_id device_id_b = entry.device_id device = dev_reg.async_get(node_dev_id) assert device is not None assert device.name == node.name old_device = device device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming without updating await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_NAME: "Demo Node", }) await hass.async_block_till_done() assert node.name == "Demo Node" entry = ent_reg.async_get('zwave.mock_node') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Node", }) await hass.async_block_till_done() assert node.name == "New Node" entry = ent_reg.async_get('zwave.new_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) entry = ent_reg.async_get('binary_sensor.new_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) await hass.services.async_call('zwave', 'rename_value', { const.ATTR_NODE_ID: node.node_id, const.ATTR_VALUE_ID: value.object_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Label", }) await hass.async_block_till_done() entry = ent_reg.async_get('binary_sensor.new_node_new_label') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) async def test_value_discovery_existing_entity(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_THERMOSTAT) setpoint = MockValue( data=22.0, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, setpoint) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] is None def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): temperature = MockValue( data=23.5, node=node, index=1, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, temperature) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] == 23.5 async def test_power_schemes(hass, mock_openzwave): """Test power attribute.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SWITCH_BINARY) switch = MockValue( data=True, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SWITCH_BINARY, genre=const.GENRE_USER, type=const.TYPE_BOOL) hass.async_add_job(mock_receivers[0], node, switch) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').state == 'on' assert 'power_consumption' not in hass.states.get( 'switch.mock_node_mock_value').attributes def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): power = MockValue( data=23.5, node=node, index=const.INDEX_SENSOR_MULTILEVEL_POWER, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL) hass.async_add_job(mock_receivers[0], node, power) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').attributes[ 'power_consumption'] == 23.5 async def test_network_ready(hass, mock_openzwave): """Test Node network ready event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete_some_dead(hass, mock_openzwave): """Test Node network complete some dead event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE_SOME_DEAD, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 class TestZWaveDeviceEntityValues(unittest.TestCase): """Tests for the ZWaveDeviceEntityValues helper.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() self.registry = mock_registry(self.hass) setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.node = MockNode() self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: ['mock_primary_class'], }, 'secondary': { const.DISC_COMMAND_CLASS: ['mock_secondary_class'], }, 'optional': { const.DISC_COMMAND_CLASS: ['mock_optional_class'], const.DISC_OPTIONAL: True, }}} self.primary = MockValue( command_class='mock_primary_class', node=self.node, value_id=1000) self.secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.duplicate_secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.optional = MockValue( command_class='mock_optional_class', node=self.node) self.no_match_value = MockValue( command_class='mock_bad_class', node=self.node) self.entity_id = 'mock_component.mock_node_mock_value' self.zwave_config = {'zwave': {}} self.device_config = {self.entity_id: {}} def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) assert values.primary is self.primary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) self.hass.block_till_done() assert values.secondary is self.secondary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config discovery.async_load_platform.reset_mock() values.check_value(self.optional) values.check_value(self.duplicate_secondary) values.check_value(self.no_match_value) self.hass.block_till_done() assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called assert len(values._entity.value_added.mock_calls) == 1 assert values._entity.value_changed.called assert len(values._entity.value_changed.mock_calls) == 1 @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, self.optional.value_id: self.optional, self.no_match_value.value_id: self.no_match_value, } values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert values.primary is self.primary assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config assert not self.primary.enable_poll.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_node_schema_mismatch(self, discovery, import_module): """Test node schema mismatch.""" self.node.generic = 'no_match' self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.mock_schema[const.DISC_GENERIC_DEVICE_CLASS] = ['generic_match'] values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.manufacturer_id = '010f' self.node.product_type = '0b00' self.primary.command_class = const.COMMAND_CLASS_SENSOR_ALARM self.entity_id = 'binary_sensor.mock_node_mock_value' self.device_config = {self.entity_id: {}} self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} with patch.object(zwave, 'async_dispatcher_send') as \ mock_dispatch_send: values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert mock_dispatch_send.called assert len(mock_dispatch_send.mock_calls) == 1 args = mock_dispatch_send.mock_calls[0][1] assert args[1] == 'zwave_new_binary_sensor' @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_ignore(self, discovery, import_module): """Test ignore workaround.""" self.node.manufacturer_id = '010f' self.node.product_type = '0301' self.primary.command_class = const.COMMAND_CLASS_SWITCH_BINARY self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore(self, discovery, import_module): """Test ignore config.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_IGNORED: True }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore_with_registry(self, discovery, import_module): """Test ignore config. The case when the device is in entity registry. """ self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {'mock_component.registry_id': { zwave.CONF_IGNORED: True }} with patch.object(self.registry, 'async_schedule_save'): self.registry.async_get_or_create( 'mock_component', zwave.DOMAIN, '567-1000', suggested_object_id='registry_id') zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_platform_ignore(self, discovery, import_module): """Test platform ignore device.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } platform = MagicMock() import_module.return_value = platform platform.get_device.return_value = None zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_config_polling_intensity(self, discovery, import_module): """Test polling intensity.""" mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_POLLING_INTENSITY: 123, }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert discovery.async_load_platform.called assert self.primary.enable_poll.called assert len(self.primary.enable_poll.mock_calls) == 1 assert self.primary.enable_poll.mock_calls[0][1][0] == 123 class TestZwave(unittest.TestCase): """Test zwave init.""" def test_device_config_glob_is_ordered(self): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): """Tests for zwave services.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() # Initialize zwave setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.zwave_network = self.hass.data[DATA_NETWORK] self.zwave_network.state = MockNetwork.STATE_READY self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.block_till_done() def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() self.hass.stop() def test_add_node(self): """Test zwave add_node service.""" self.hass.services.call('zwave', 'add_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller .add_node.mock_calls) == 1 assert len(self.zwave_network.controller .add_node.mock_calls[0][1]) == 0 def test_add_node_secure(self): """Test zwave add_node_secure service.""" self.hass.services.call('zwave', 'add_node_secure', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller.add_node.mock_calls) == 1 assert (self.zwave_network.controller .add_node.mock_calls[0][1][0] is True) def test_remove_node(self): """Test zwave remove_node service.""" self.hass.services.call('zwave', 'remove_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.remove_node.called assert len(self.zwave_network.controller.remove_node.mock_calls) == 1 def test_cancel_command(self): """Test zwave cancel_command service.""" self.hass.services.call('zwave', 'cancel_command', {}) self.hass.block_till_done() assert self.zwave_network.controller.cancel_command.called assert len(self.zwave_network.controller .cancel_command.mock_calls) == 1 def test_heal_network(self): """Test zwave heal_network service.""" self.hass.services.call('zwave', 'heal_network', {}) self.hass.block_till_done() assert self.zwave_network.heal.called assert len(self.zwave_network.heal.mock_calls) == 1 def test_soft_reset(self): """Test zwave soft_reset service.""" self.hass.services.call('zwave', 'soft_reset', {}) self.hass.block_till_done() assert self.zwave_network.controller.soft_reset.called assert len(self.zwave_network.controller.soft_reset.mock_calls) == 1 def test_test_network(self): """Test zwave test_network service.""" self.hass.services.call('zwave', 'test_network', {}) self.hass.block_till_done() assert self.zwave_network.test.called assert len(self.zwave_network.test.mock_calls) == 1 def test_stop_network(self): """Test zwave stop_network service.""" with patch.object(self.hass.bus, 'fire') as mock_fire: self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() assert self.zwave_network.stop.called assert len(self.zwave_network.stop.mock_calls) == 1 assert mock_fire.called assert len(mock_fire.mock_calls) == 1 assert mock_fire.mock_calls[0][1][0] == const.EVENT_NETWORK_STOP def test_rename_node(self): """Test zwave rename_node service.""" self.zwave_network.nodes = {11: MagicMock()} self.hass.services.call('zwave', 'rename_node', { const.ATTR_NODE_ID: 11, const.ATTR_NAME: 'test_name', }) self.hass.block_till_done() assert self.zwave_network.nodes[11].name == 'test_name' def test_rename_value(self): """Test zwave rename_value service.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, label="Old Label") node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.label == "Old Label" self.hass.services.call('zwave', 'rename_value', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_NAME: "New Label", }) self.hass.block_till_done() assert value.label == "New Label" def test_set_poll_intensity_enable(self): """Test zwave set_poll_intensity service, successful set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 2 assert enable_poll.mock_calls[0][1][0] == 4 def test_set_poll_intensity_enable_failed(self): """Test zwave set_poll_intensity service, failed set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) value.enable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 1 def test_set_poll_intensity_disable(self): """Test zwave set_poll_intensity service, successful disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 2 def test_set_poll_intensity_disable_failed(self): """Test zwave set_poll_intensity service, failed disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) value.disable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 1 def test_remove_failed_node(self): """Test zwave remove_failed_node service.""" self.hass.services.call('zwave', 'remove_failed_node', { const.ATTR_NODE_ID: 12, }) self.hass.block_till_done() remove_failed_node = self.zwave_network.controller.remove_failed_node assert remove_failed_node.called assert len(remove_failed_node.mock_calls) == 1 assert remove_failed_node.mock_calls[0][1][0] == 12 def test_replace_failed_node(self): """Test zwave replace_failed_node service.""" self.hass.services.call('zwave', 'replace_failed_node', { const.ATTR_NODE_ID: 13, }) self.hass.block_till_done() replace_failed_node = self.zwave_network.controller.replace_failed_node assert replace_failed_node.called assert len(replace_failed_node.mock_calls) == 1 assert replace_failed_node.mock_calls[0][1][0] == 13 def test_set_config_parameter(self): """Test zwave set_config_parameter service.""" value_byte = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BYTE, ) value_list = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['item1', 'item2', 'item3'], ) value_button = MockValue( index=14, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BUTTON, ) value_list_int = MockValue( index=15, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['1', '2', '3'], ) value_bool = MockValue( index=16, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BOOL, ) node = MockNode(node_id=14) node.get_values.return_value = { 12: value_byte, 13: value_list, 14: value_button, 15: value_list_int, 16: value_bool } self.zwave_network.nodes = {14: node} # Byte self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 12, const.ATTR_CONFIG_VALUE: 7, }) self.hass.block_till_done() assert value_byte.data == 7 # List self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, const.ATTR_CONFIG_VALUE: 'item3', }) self.hass.block_till_done() assert value_list.data == 'item3' # Button self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 14, const.ATTR_CONFIG_VALUE: True, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called assert self.zwave_network.manager.releaseButton.called # List of Ints self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 15, const.ATTR_CONFIG_VALUE: 3, }) self.hass.block_till_done() assert value_list_int.data == '3' # Boolean Truthy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'True', }) self.hass.block_till_done() assert value_bool.data == 1 # Boolean Falsy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'False', }) self.hass.block_till_done() assert value_bool.data == 0 # Different Parameter Size self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 19, const.ATTR_CONFIG_VALUE: 0x01020304, const.ATTR_CONFIG_SIZE: 4 }) self.hass.block_till_done() assert node.set_config_param.called assert len(node.set_config_param.mock_calls) == 1 assert node.set_config_param.mock_calls[0][1][0] == 19 assert node.set_config_param.mock_calls[0][1][1] == 0x01020304 assert node.set_config_param.mock_calls[0][1][2] == 4 node.set_config_param.reset_mock() def test_print_config_parameter(self): """Test zwave print_config_parameter service.""" value1 = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, data=1234, ) value2 = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, data=2345, ) node = MockNode(node_id=14) node.values = {12: value1, 13: value2} self.zwave_network.nodes = {14: node} with patch.object(zwave, '_LOGGER') as mock_logger: self.hass.services.call('zwave', 'print_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, }) self.hass.block_till_done() assert mock_logger.info.called assert len(mock_logger.info.mock_calls) == 1 assert mock_logger.info.mock_calls[0][1][1] == 13 assert mock_logger.info.mock_calls[0][1][2] == 14 assert mock_logger.info.mock_calls[0][1][3] == 2345 def test_print_node(self): """Test zwave print_node_parameter service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} with self.assertLogs(level='DEBUG') as mock_logger: self.hass.services.call('zwave', 'print_node', { const.ATTR_NODE_ID: 14 }) self.hass.block_till_done() assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 15, }) self.hass.block_till_done() assert value.data == 15 node.can_wake_up_value = False self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 20, }) self.hass.block_till_done() assert value.data == 15 def test_reset_node_meters(self): """Test zwave reset_node_meters service.""" value = MockValue( instance=1, index=8, data=99.5, command_class=const.COMMAND_CLASS_METER, ) reset_value = MockValue( instance=1, index=33, command_class=const.COMMAND_CLASS_METER, ) node = MockNode(node_id=14) node.values = {8: value, 33: reset_value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, const.ATTR_INSTANCE: 2, }) self.hass.block_till_done() assert not self.zwave_network.manager.pressButton.called assert not self.zwave_network.manager.releaseButton.called self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called value_id, = self.zwave_network.manager.pressButton.mock_calls.pop(0)[1] assert value_id == reset_value.value_id assert self.zwave_network.manager.releaseButton.called value_id, = ( self.zwave_network.manager.releaseButton.mock_calls.pop(0)[1]) assert value_id == reset_value.value_id def test_add_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'add', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.add_association.called assert len(group.add_association.mock_calls) == 1 assert group.add_association.mock_calls[0][1][0] == 24 assert group.add_association.mock_calls[0][1][1] == 5 def test_remove_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'remove', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.remove_association.called assert len(group.remove_association.mock_calls) == 1 assert group.remove_association.mock_calls[0][1][0] == 24 assert group.remove_association.mock_calls[0][1][1] == 5 def test_refresh_entity(self): """Test zwave refresh_entity service.""" node = MockNode() value = MockValue(data=False, node=node, command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50, node=node, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = get_device(node=node, values=values, node_config={}) device.hass = self.hass device.entity_id = 'binary_sensor.mock_entity_id' self.hass.add_job(device.async_added_to_hass()) self.hass.block_till_done() self.hass.services.call('zwave', 'refresh_entity', { ATTR_ENTITY_ID: 'binary_sensor.mock_entity_id', }) self.hass.block_till_done() assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 assert sorted([node.refresh_value.mock_calls[0][1][0], node.refresh_value.mock_calls[1][1][0]]) == \ sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert node.refresh_info.called assert len(node.refresh_info.mock_calls) == 1 def test_set_node_value(self): """Test zwave set_node_value service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=4 ) node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR]) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12, const.ATTR_CONFIG_VALUE: 2, }) self.hass.block_till_done() assert self.zwave_network.nodes[14].values[12].data == 2 def test_refresh_node_value(self): """Test zwave refresh_node_value service.""" node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR], network=self.zwave_network) value = MockValue( node=node, index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=2 ) value.refresh = MagicMock() node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12 }) self.hass.block_till_done() assert value.refresh.called def test_heal_node(self): """Test zwave heal_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'heal_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.heal.called assert len(node.heal.mock_calls) == 1 def test_test_node(self): """Test the zwave test_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'test_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.test.called assert len(node.test.mock_calls) == 1
jabesq/home-assistant
tests/components/zwave/test_init.py
homeassistant/components/daikin/const.py
"""Support for interface with a Ziggo Mediabox XL.""" import logging import socket import voluptuous as vol from homeassistant.components.media_player import ( MediaPlayerDevice, PLATFORM_SCHEMA) from homeassistant.components.media_player.const import ( SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PLAY, SUPPORT_PREVIOUS_TRACK, SUPPORT_SELECT_SOURCE, SUPPORT_TURN_OFF, SUPPORT_TURN_ON) from homeassistant.const import ( CONF_HOST, CONF_NAME, STATE_OFF, STATE_PAUSED, STATE_PLAYING) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) DATA_KNOWN_DEVICES = 'ziggo_mediabox_xl_known_devices' SUPPORT_ZIGGO = SUPPORT_TURN_ON | SUPPORT_TURN_OFF | \ SUPPORT_NEXT_TRACK | SUPPORT_PAUSE | SUPPORT_PREVIOUS_TRACK | \ SUPPORT_SELECT_SOURCE | SUPPORT_PLAY PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_NAME): cv.string, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Ziggo Mediabox XL platform.""" from ziggo_mediabox_xl import ZiggoMediaboxXL hass.data[DATA_KNOWN_DEVICES] = known_devices = set() # Is this a manual configuration? if config.get(CONF_HOST) is not None: host = config.get(CONF_HOST) name = config.get(CONF_NAME) manual_config = True elif discovery_info is not None: host = discovery_info.get('host') name = discovery_info.get('name') manual_config = False else: _LOGGER.error("Cannot determine device") return # Only add a device once, so discovered devices do not override manual # config. hosts = [] connection_successful = False ip_addr = socket.gethostbyname(host) if ip_addr not in known_devices: try: # Mediabox instance with a timeout of 3 seconds. mediabox = ZiggoMediaboxXL(ip_addr, 3) # Check if a connection can be established to the device. if mediabox.test_connection(): connection_successful = True else: if manual_config: _LOGGER.info("Can't connect to %s", host) else: _LOGGER.error("Can't connect to %s", host) # When the device is in eco mode it's not connected to the network # so it needs to be added anyway if it's configured manually. if manual_config or connection_successful: hosts.append(ZiggoMediaboxXLDevice(mediabox, host, name, connection_successful)) known_devices.add(ip_addr) except socket.error as error: _LOGGER.error("Can't connect to %s: %s", host, error) else: _LOGGER.info("Ignoring duplicate Ziggo Mediabox XL %s", host) add_entities(hosts, True) class ZiggoMediaboxXLDevice(MediaPlayerDevice): """Representation of a Ziggo Mediabox XL Device.""" def __init__(self, mediabox, host, name, available): """Initialize the device.""" self._mediabox = mediabox self._host = host self._name = name self._available = available self._state = None def update(self): """Retrieve the state of the device.""" try: if self._mediabox.test_connection(): if self._mediabox.turned_on(): if self._state != STATE_PAUSED: self._state = STATE_PLAYING else: self._state = STATE_OFF self._available = True else: self._available = False except socket.error: _LOGGER.error("Couldn't fetch state from %s", self._host) self._available = False def send_keys(self, keys): """Send keys to the device and handle exceptions.""" try: self._mediabox.send_keys(keys) except socket.error: _LOGGER.error("Couldn't send keys to %s", self._host) @property def name(self): """Return the name of the device.""" return self._name @property def state(self): """Return the state of the device.""" return self._state @property def available(self): """Return True if the device is available.""" return self._available @property def source_list(self): """List of available sources (channels).""" return [self._mediabox.channels()[c] for c in sorted(self._mediabox.channels().keys())] @property def supported_features(self): """Flag media player features that are supported.""" return SUPPORT_ZIGGO def turn_on(self): """Turn the media player on.""" self.send_keys(['POWER']) def turn_off(self): """Turn off media player.""" self.send_keys(['POWER']) def media_play(self): """Send play command.""" self.send_keys(['PLAY']) self._state = STATE_PLAYING def media_pause(self): """Send pause command.""" self.send_keys(['PAUSE']) self._state = STATE_PAUSED def media_play_pause(self): """Simulate play pause media player.""" self.send_keys(['PAUSE']) if self._state == STATE_PAUSED: self._state = STATE_PLAYING else: self._state = STATE_PAUSED def media_next_track(self): """Channel up.""" self.send_keys(['CHAN_UP']) self._state = STATE_PLAYING def media_previous_track(self): """Channel down.""" self.send_keys(['CHAN_DOWN']) self._state = STATE_PLAYING def select_source(self, source): """Select the channel.""" if str(source).isdigit(): digits = str(source) else: digits = next(( key for key, value in self._mediabox.channels().items() if value == source), None) if digits is None: return self.send_keys(['NUM_{}'.format(digit) for digit in str(digits)]) self._state = STATE_PLAYING
"""Tests for the Z-Wave init.""" import asyncio from collections import OrderedDict from datetime import datetime import unittest from unittest.mock import MagicMock, patch import pytest from pytz import utc import voluptuous as vol from homeassistant.bootstrap import async_setup_component from homeassistant.components import zwave from homeassistant.components.zwave import ( CONF_DEVICE_CONFIG_GLOB, CONFIG_SCHEMA, DATA_NETWORK, const) from homeassistant.components.zwave.binary_sensor import get_device from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.device_registry import ( async_get_registry as get_dev_reg) from homeassistant.setup import setup_component from tests.common import ( async_fire_time_changed, get_test_home_assistant, mock_coro, mock_registry) from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue async def test_valid_device_config(hass, mock_openzwave): """Test valid device config.""" device_config = { 'light.kitchen': { 'ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert result async def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = { 'light.kitchen': { 'some_ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert not result def test_config_access_error(): """Test threading error accessing config values.""" node = MagicMock() def side_effect(): raise RuntimeError node.values.values.side_effect = side_effect result = zwave.get_config_value(node, 1) assert result is None async def test_network_options(hass, mock_openzwave): """Test network options.""" result = await async_setup_component(hass, 'zwave', { 'zwave': { 'usb_path': 'mock_usb_path', 'config_path': 'mock_config_path', }}) await hass.async_block_till_done() assert result network = hass.data[zwave.DATA_NETWORK] assert network.options.device == 'mock_usb_path' assert network.options.config_path == 'mock_config_path' async def test_network_key_validation(hass, mock_openzwave): """Test network key validation.""" test_values = [ ('0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,' '0x0E,0x0F,0x10'), ] for value in test_values: result = zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) assert result['zwave']['network_key'] == value async def test_erronous_network_key_fails_validation(hass, mock_openzwave): """Test failing erronous network key validation.""" test_values = [ ('0x 01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0X01,0X02,0X03,0X04,0X05,0X06,0X07,0X08,0X09,0X0A,0X0B,0X0C,0X0D,' '0X0E,0X0F,0X10'), 'invalid', '1234567', 1234567 ] for value in test_values: with pytest.raises(vol.Invalid): zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) async def test_auto_heal_midnight(hass, mock_openzwave): """Test network auto-heal at midnight.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': True, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert network.heal.called assert len(network.heal.mock_calls) == 1 async def test_auto_heal_disabled(hass, mock_openzwave): """Test network auto-heal disabled.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': False, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert not network.heal.called async def test_setup_platform(hass, mock_openzwave): """Test invalid device config.""" mock_device = MagicMock() hass.data[DATA_NETWORK] = MagicMock() hass.data[zwave.DATA_DEVICES] = {456: mock_device} async_add_entities = MagicMock() result = await zwave.async_setup_platform( hass, None, async_add_entities, None) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 123}) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 456}) assert result assert async_add_entities.called assert len(async_add_entities.mock_calls) == 1 assert async_add_entities.mock_calls[0][1][0] == [mock_device] async def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): """Test device entity base class.""" node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.value_added() device.update_properties() await hass.async_block_till_done() assert not device.should_poll assert device.unique_id == "10-11" assert device.name == 'Mock Node Sensor' assert device.device_state_attributes[zwave.ATTR_POWER] == 50.123 async def test_node_removed(hass, mock_openzwave): """Test node removed in base class.""" # Create a mock node & node entity node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.entity_id = 'zwave.mock_node' device.value_added() device.update_properties() await hass.async_block_till_done() # Save it to the entity registry registry = mock_registry(hass) registry.async_get_or_create('zwave', 'zwave', device.unique_id) device.entity_id = registry.async_get_entity_id( 'zwave', 'zwave', device.unique_id) # Create dummy entity registry entries for other integrations hue_entity = registry.async_get_or_create('light', 'hue', 1234) zha_entity = registry.async_get_or_create('sensor', 'zha', 5678) # Verify our Z-Wave entity is registered assert registry.async_is_registered(device.entity_id) # Remove it entity_id = device.entity_id await device.node_removed() # Verify registry entry for our Z-Wave node is gone assert not registry.async_is_registered(entity_id) # Verify registry entries for our other entities remain assert registry.async_is_registered(hue_entity.entity_id) assert registry.async_is_registered(zha_entity.entity_id) async def test_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node').state == 'unknown' async def test_unparsed_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode( node_id=14, manufacturer_name=None, name=None, is_ready=False) sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert len(sleeps) == const.NODE_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1:] == \ (14, const.NODE_READY_WAIT_SECS) assert hass.states.get('zwave.unknown_node_14').state == 'unknown' async def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': { 'device_config': { 'zwave.mock_node': { 'ignored': True, }}}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None async def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' async def test_value_entities(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = {} def mock_connect(receiver, signal, *args, **kwargs): mock_receivers[signal] = receiver with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert mock_receivers hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_ALL_NODES_QUERIED]) node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) zwave_network.nodes = {node.node_id: node} value = MockValue( data=False, node=node, index=12, instance=1, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values = {'primary': value, value.value_id: value} value2 = MockValue( data=False, node=node, index=12, instance=2, label="Mock Value B", command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values[value2.value_id] = value2 hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_NODE_ADDED], node) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value2) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' assert hass.states.get( 'binary_sensor.mock_node_mock_value_b').state == 'off' ent_reg = await async_get_registry(hass) dev_reg = await get_dev_reg(hass) entry = ent_reg.async_get('zwave.mock_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) node_dev_id = entry.device_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) assert entry.name is None assert entry.device_id == node_dev_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value2.object_id) assert entry.name is None assert entry.device_id != node_dev_id device_id_b = entry.device_id device = dev_reg.async_get(node_dev_id) assert device is not None assert device.name == node.name old_device = device device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming without updating await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_NAME: "Demo Node", }) await hass.async_block_till_done() assert node.name == "Demo Node" entry = ent_reg.async_get('zwave.mock_node') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Node", }) await hass.async_block_till_done() assert node.name == "New Node" entry = ent_reg.async_get('zwave.new_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) entry = ent_reg.async_get('binary_sensor.new_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) await hass.services.async_call('zwave', 'rename_value', { const.ATTR_NODE_ID: node.node_id, const.ATTR_VALUE_ID: value.object_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Label", }) await hass.async_block_till_done() entry = ent_reg.async_get('binary_sensor.new_node_new_label') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) async def test_value_discovery_existing_entity(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_THERMOSTAT) setpoint = MockValue( data=22.0, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, setpoint) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] is None def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): temperature = MockValue( data=23.5, node=node, index=1, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, temperature) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] == 23.5 async def test_power_schemes(hass, mock_openzwave): """Test power attribute.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SWITCH_BINARY) switch = MockValue( data=True, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SWITCH_BINARY, genre=const.GENRE_USER, type=const.TYPE_BOOL) hass.async_add_job(mock_receivers[0], node, switch) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').state == 'on' assert 'power_consumption' not in hass.states.get( 'switch.mock_node_mock_value').attributes def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): power = MockValue( data=23.5, node=node, index=const.INDEX_SENSOR_MULTILEVEL_POWER, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL) hass.async_add_job(mock_receivers[0], node, power) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').attributes[ 'power_consumption'] == 23.5 async def test_network_ready(hass, mock_openzwave): """Test Node network ready event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete_some_dead(hass, mock_openzwave): """Test Node network complete some dead event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE_SOME_DEAD, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 class TestZWaveDeviceEntityValues(unittest.TestCase): """Tests for the ZWaveDeviceEntityValues helper.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() self.registry = mock_registry(self.hass) setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.node = MockNode() self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: ['mock_primary_class'], }, 'secondary': { const.DISC_COMMAND_CLASS: ['mock_secondary_class'], }, 'optional': { const.DISC_COMMAND_CLASS: ['mock_optional_class'], const.DISC_OPTIONAL: True, }}} self.primary = MockValue( command_class='mock_primary_class', node=self.node, value_id=1000) self.secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.duplicate_secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.optional = MockValue( command_class='mock_optional_class', node=self.node) self.no_match_value = MockValue( command_class='mock_bad_class', node=self.node) self.entity_id = 'mock_component.mock_node_mock_value' self.zwave_config = {'zwave': {}} self.device_config = {self.entity_id: {}} def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) assert values.primary is self.primary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) self.hass.block_till_done() assert values.secondary is self.secondary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config discovery.async_load_platform.reset_mock() values.check_value(self.optional) values.check_value(self.duplicate_secondary) values.check_value(self.no_match_value) self.hass.block_till_done() assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called assert len(values._entity.value_added.mock_calls) == 1 assert values._entity.value_changed.called assert len(values._entity.value_changed.mock_calls) == 1 @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, self.optional.value_id: self.optional, self.no_match_value.value_id: self.no_match_value, } values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert values.primary is self.primary assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config assert not self.primary.enable_poll.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_node_schema_mismatch(self, discovery, import_module): """Test node schema mismatch.""" self.node.generic = 'no_match' self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.mock_schema[const.DISC_GENERIC_DEVICE_CLASS] = ['generic_match'] values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.manufacturer_id = '010f' self.node.product_type = '0b00' self.primary.command_class = const.COMMAND_CLASS_SENSOR_ALARM self.entity_id = 'binary_sensor.mock_node_mock_value' self.device_config = {self.entity_id: {}} self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} with patch.object(zwave, 'async_dispatcher_send') as \ mock_dispatch_send: values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert mock_dispatch_send.called assert len(mock_dispatch_send.mock_calls) == 1 args = mock_dispatch_send.mock_calls[0][1] assert args[1] == 'zwave_new_binary_sensor' @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_ignore(self, discovery, import_module): """Test ignore workaround.""" self.node.manufacturer_id = '010f' self.node.product_type = '0301' self.primary.command_class = const.COMMAND_CLASS_SWITCH_BINARY self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore(self, discovery, import_module): """Test ignore config.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_IGNORED: True }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore_with_registry(self, discovery, import_module): """Test ignore config. The case when the device is in entity registry. """ self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {'mock_component.registry_id': { zwave.CONF_IGNORED: True }} with patch.object(self.registry, 'async_schedule_save'): self.registry.async_get_or_create( 'mock_component', zwave.DOMAIN, '567-1000', suggested_object_id='registry_id') zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_platform_ignore(self, discovery, import_module): """Test platform ignore device.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } platform = MagicMock() import_module.return_value = platform platform.get_device.return_value = None zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_config_polling_intensity(self, discovery, import_module): """Test polling intensity.""" mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_POLLING_INTENSITY: 123, }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert discovery.async_load_platform.called assert self.primary.enable_poll.called assert len(self.primary.enable_poll.mock_calls) == 1 assert self.primary.enable_poll.mock_calls[0][1][0] == 123 class TestZwave(unittest.TestCase): """Test zwave init.""" def test_device_config_glob_is_ordered(self): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): """Tests for zwave services.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() # Initialize zwave setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.zwave_network = self.hass.data[DATA_NETWORK] self.zwave_network.state = MockNetwork.STATE_READY self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.block_till_done() def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() self.hass.stop() def test_add_node(self): """Test zwave add_node service.""" self.hass.services.call('zwave', 'add_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller .add_node.mock_calls) == 1 assert len(self.zwave_network.controller .add_node.mock_calls[0][1]) == 0 def test_add_node_secure(self): """Test zwave add_node_secure service.""" self.hass.services.call('zwave', 'add_node_secure', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller.add_node.mock_calls) == 1 assert (self.zwave_network.controller .add_node.mock_calls[0][1][0] is True) def test_remove_node(self): """Test zwave remove_node service.""" self.hass.services.call('zwave', 'remove_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.remove_node.called assert len(self.zwave_network.controller.remove_node.mock_calls) == 1 def test_cancel_command(self): """Test zwave cancel_command service.""" self.hass.services.call('zwave', 'cancel_command', {}) self.hass.block_till_done() assert self.zwave_network.controller.cancel_command.called assert len(self.zwave_network.controller .cancel_command.mock_calls) == 1 def test_heal_network(self): """Test zwave heal_network service.""" self.hass.services.call('zwave', 'heal_network', {}) self.hass.block_till_done() assert self.zwave_network.heal.called assert len(self.zwave_network.heal.mock_calls) == 1 def test_soft_reset(self): """Test zwave soft_reset service.""" self.hass.services.call('zwave', 'soft_reset', {}) self.hass.block_till_done() assert self.zwave_network.controller.soft_reset.called assert len(self.zwave_network.controller.soft_reset.mock_calls) == 1 def test_test_network(self): """Test zwave test_network service.""" self.hass.services.call('zwave', 'test_network', {}) self.hass.block_till_done() assert self.zwave_network.test.called assert len(self.zwave_network.test.mock_calls) == 1 def test_stop_network(self): """Test zwave stop_network service.""" with patch.object(self.hass.bus, 'fire') as mock_fire: self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() assert self.zwave_network.stop.called assert len(self.zwave_network.stop.mock_calls) == 1 assert mock_fire.called assert len(mock_fire.mock_calls) == 1 assert mock_fire.mock_calls[0][1][0] == const.EVENT_NETWORK_STOP def test_rename_node(self): """Test zwave rename_node service.""" self.zwave_network.nodes = {11: MagicMock()} self.hass.services.call('zwave', 'rename_node', { const.ATTR_NODE_ID: 11, const.ATTR_NAME: 'test_name', }) self.hass.block_till_done() assert self.zwave_network.nodes[11].name == 'test_name' def test_rename_value(self): """Test zwave rename_value service.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, label="Old Label") node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.label == "Old Label" self.hass.services.call('zwave', 'rename_value', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_NAME: "New Label", }) self.hass.block_till_done() assert value.label == "New Label" def test_set_poll_intensity_enable(self): """Test zwave set_poll_intensity service, successful set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 2 assert enable_poll.mock_calls[0][1][0] == 4 def test_set_poll_intensity_enable_failed(self): """Test zwave set_poll_intensity service, failed set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) value.enable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 1 def test_set_poll_intensity_disable(self): """Test zwave set_poll_intensity service, successful disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 2 def test_set_poll_intensity_disable_failed(self): """Test zwave set_poll_intensity service, failed disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) value.disable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 1 def test_remove_failed_node(self): """Test zwave remove_failed_node service.""" self.hass.services.call('zwave', 'remove_failed_node', { const.ATTR_NODE_ID: 12, }) self.hass.block_till_done() remove_failed_node = self.zwave_network.controller.remove_failed_node assert remove_failed_node.called assert len(remove_failed_node.mock_calls) == 1 assert remove_failed_node.mock_calls[0][1][0] == 12 def test_replace_failed_node(self): """Test zwave replace_failed_node service.""" self.hass.services.call('zwave', 'replace_failed_node', { const.ATTR_NODE_ID: 13, }) self.hass.block_till_done() replace_failed_node = self.zwave_network.controller.replace_failed_node assert replace_failed_node.called assert len(replace_failed_node.mock_calls) == 1 assert replace_failed_node.mock_calls[0][1][0] == 13 def test_set_config_parameter(self): """Test zwave set_config_parameter service.""" value_byte = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BYTE, ) value_list = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['item1', 'item2', 'item3'], ) value_button = MockValue( index=14, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BUTTON, ) value_list_int = MockValue( index=15, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['1', '2', '3'], ) value_bool = MockValue( index=16, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BOOL, ) node = MockNode(node_id=14) node.get_values.return_value = { 12: value_byte, 13: value_list, 14: value_button, 15: value_list_int, 16: value_bool } self.zwave_network.nodes = {14: node} # Byte self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 12, const.ATTR_CONFIG_VALUE: 7, }) self.hass.block_till_done() assert value_byte.data == 7 # List self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, const.ATTR_CONFIG_VALUE: 'item3', }) self.hass.block_till_done() assert value_list.data == 'item3' # Button self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 14, const.ATTR_CONFIG_VALUE: True, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called assert self.zwave_network.manager.releaseButton.called # List of Ints self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 15, const.ATTR_CONFIG_VALUE: 3, }) self.hass.block_till_done() assert value_list_int.data == '3' # Boolean Truthy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'True', }) self.hass.block_till_done() assert value_bool.data == 1 # Boolean Falsy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'False', }) self.hass.block_till_done() assert value_bool.data == 0 # Different Parameter Size self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 19, const.ATTR_CONFIG_VALUE: 0x01020304, const.ATTR_CONFIG_SIZE: 4 }) self.hass.block_till_done() assert node.set_config_param.called assert len(node.set_config_param.mock_calls) == 1 assert node.set_config_param.mock_calls[0][1][0] == 19 assert node.set_config_param.mock_calls[0][1][1] == 0x01020304 assert node.set_config_param.mock_calls[0][1][2] == 4 node.set_config_param.reset_mock() def test_print_config_parameter(self): """Test zwave print_config_parameter service.""" value1 = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, data=1234, ) value2 = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, data=2345, ) node = MockNode(node_id=14) node.values = {12: value1, 13: value2} self.zwave_network.nodes = {14: node} with patch.object(zwave, '_LOGGER') as mock_logger: self.hass.services.call('zwave', 'print_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, }) self.hass.block_till_done() assert mock_logger.info.called assert len(mock_logger.info.mock_calls) == 1 assert mock_logger.info.mock_calls[0][1][1] == 13 assert mock_logger.info.mock_calls[0][1][2] == 14 assert mock_logger.info.mock_calls[0][1][3] == 2345 def test_print_node(self): """Test zwave print_node_parameter service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} with self.assertLogs(level='DEBUG') as mock_logger: self.hass.services.call('zwave', 'print_node', { const.ATTR_NODE_ID: 14 }) self.hass.block_till_done() assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 15, }) self.hass.block_till_done() assert value.data == 15 node.can_wake_up_value = False self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 20, }) self.hass.block_till_done() assert value.data == 15 def test_reset_node_meters(self): """Test zwave reset_node_meters service.""" value = MockValue( instance=1, index=8, data=99.5, command_class=const.COMMAND_CLASS_METER, ) reset_value = MockValue( instance=1, index=33, command_class=const.COMMAND_CLASS_METER, ) node = MockNode(node_id=14) node.values = {8: value, 33: reset_value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, const.ATTR_INSTANCE: 2, }) self.hass.block_till_done() assert not self.zwave_network.manager.pressButton.called assert not self.zwave_network.manager.releaseButton.called self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called value_id, = self.zwave_network.manager.pressButton.mock_calls.pop(0)[1] assert value_id == reset_value.value_id assert self.zwave_network.manager.releaseButton.called value_id, = ( self.zwave_network.manager.releaseButton.mock_calls.pop(0)[1]) assert value_id == reset_value.value_id def test_add_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'add', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.add_association.called assert len(group.add_association.mock_calls) == 1 assert group.add_association.mock_calls[0][1][0] == 24 assert group.add_association.mock_calls[0][1][1] == 5 def test_remove_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'remove', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.remove_association.called assert len(group.remove_association.mock_calls) == 1 assert group.remove_association.mock_calls[0][1][0] == 24 assert group.remove_association.mock_calls[0][1][1] == 5 def test_refresh_entity(self): """Test zwave refresh_entity service.""" node = MockNode() value = MockValue(data=False, node=node, command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50, node=node, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = get_device(node=node, values=values, node_config={}) device.hass = self.hass device.entity_id = 'binary_sensor.mock_entity_id' self.hass.add_job(device.async_added_to_hass()) self.hass.block_till_done() self.hass.services.call('zwave', 'refresh_entity', { ATTR_ENTITY_ID: 'binary_sensor.mock_entity_id', }) self.hass.block_till_done() assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 assert sorted([node.refresh_value.mock_calls[0][1][0], node.refresh_value.mock_calls[1][1][0]]) == \ sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert node.refresh_info.called assert len(node.refresh_info.mock_calls) == 1 def test_set_node_value(self): """Test zwave set_node_value service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=4 ) node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR]) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12, const.ATTR_CONFIG_VALUE: 2, }) self.hass.block_till_done() assert self.zwave_network.nodes[14].values[12].data == 2 def test_refresh_node_value(self): """Test zwave refresh_node_value service.""" node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR], network=self.zwave_network) value = MockValue( node=node, index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=2 ) value.refresh = MagicMock() node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12 }) self.hass.block_till_done() assert value.refresh.called def test_heal_node(self): """Test zwave heal_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'heal_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.heal.called assert len(node.heal.mock_calls) == 1 def test_test_node(self): """Test the zwave test_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'test_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.test.called assert len(node.test.mock_calls) == 1
jabesq/home-assistant
tests/components/zwave/test_init.py
homeassistant/components/ziggo_mediabox_xl/media_player.py
"""The HTTP api to control the cloud integration.""" import asyncio from functools import wraps import logging import attr import aiohttp import async_timeout import voluptuous as vol from homeassistant.core import callback from homeassistant.components.http import HomeAssistantView from homeassistant.components.http.data_validator import ( RequestDataValidator) from homeassistant.components import websocket_api from homeassistant.components.websocket_api import const as ws_const from homeassistant.components.alexa import ( entities as alexa_entities, errors as alexa_errors, ) from homeassistant.components.google_assistant import helpers as google_helpers from .const import ( DOMAIN, REQUEST_TIMEOUT, PREF_ENABLE_ALEXA, PREF_ENABLE_GOOGLE, PREF_GOOGLE_SECURE_DEVICES_PIN, InvalidTrustedNetworks, InvalidTrustedProxies, PREF_ALEXA_REPORT_STATE, RequireRelink) _LOGGER = logging.getLogger(__name__) WS_TYPE_STATUS = 'cloud/status' SCHEMA_WS_STATUS = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({ vol.Required('type'): WS_TYPE_STATUS, }) WS_TYPE_SUBSCRIPTION = 'cloud/subscription' SCHEMA_WS_SUBSCRIPTION = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({ vol.Required('type'): WS_TYPE_SUBSCRIPTION, }) WS_TYPE_HOOK_CREATE = 'cloud/cloudhook/create' SCHEMA_WS_HOOK_CREATE = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({ vol.Required('type'): WS_TYPE_HOOK_CREATE, vol.Required('webhook_id'): str }) WS_TYPE_HOOK_DELETE = 'cloud/cloudhook/delete' SCHEMA_WS_HOOK_DELETE = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({ vol.Required('type'): WS_TYPE_HOOK_DELETE, vol.Required('webhook_id'): str }) _CLOUD_ERRORS = { InvalidTrustedNetworks: (500, 'Remote UI not compatible with 127.0.0.1/::1' ' as a trusted network.'), InvalidTrustedProxies: (500, 'Remote UI not compatible with 127.0.0.1/::1' ' as trusted proxies.'), } async def async_setup(hass): """Initialize the HTTP API.""" hass.components.websocket_api.async_register_command( WS_TYPE_STATUS, websocket_cloud_status, SCHEMA_WS_STATUS ) hass.components.websocket_api.async_register_command( WS_TYPE_SUBSCRIPTION, websocket_subscription, SCHEMA_WS_SUBSCRIPTION ) hass.components.websocket_api.async_register_command( websocket_update_prefs) hass.components.websocket_api.async_register_command( WS_TYPE_HOOK_CREATE, websocket_hook_create, SCHEMA_WS_HOOK_CREATE ) hass.components.websocket_api.async_register_command( WS_TYPE_HOOK_DELETE, websocket_hook_delete, SCHEMA_WS_HOOK_DELETE ) hass.components.websocket_api.async_register_command( websocket_remote_connect) hass.components.websocket_api.async_register_command( websocket_remote_disconnect) hass.components.websocket_api.async_register_command( google_assistant_list) hass.components.websocket_api.async_register_command( google_assistant_update) hass.components.websocket_api.async_register_command(alexa_list) hass.components.websocket_api.async_register_command(alexa_update) hass.components.websocket_api.async_register_command(alexa_sync) hass.http.register_view(GoogleActionsSyncView) hass.http.register_view(CloudLoginView) hass.http.register_view(CloudLogoutView) hass.http.register_view(CloudRegisterView) hass.http.register_view(CloudResendConfirmView) hass.http.register_view(CloudForgotPasswordView) from hass_nabucasa import auth _CLOUD_ERRORS.update({ auth.UserNotFound: (400, "User does not exist."), auth.UserNotConfirmed: (400, 'Email not confirmed.'), auth.UserExists: (400, 'An account with the given email already exists.'), auth.Unauthenticated: (401, 'Authentication failed.'), auth.PasswordChangeRequired: (400, 'Password change required.'), asyncio.TimeoutError: (502, 'Unable to reach the Home Assistant cloud.'), aiohttp.ClientError: (500, 'Error making internal request'), }) def _handle_cloud_errors(handler): """Webview decorator to handle auth errors.""" @wraps(handler) async def error_handler(view, request, *args, **kwargs): """Handle exceptions that raise from the wrapped request handler.""" try: result = await handler(view, request, *args, **kwargs) return result except Exception as err: # pylint: disable=broad-except status, msg = _process_cloud_exception(err, request.path) return view.json_message( msg, status_code=status, message_code=err.__class__.__name__.lower()) return error_handler def _ws_handle_cloud_errors(handler): """Websocket decorator to handle auth errors.""" @wraps(handler) async def error_handler(hass, connection, msg): """Handle exceptions that raise from the wrapped handler.""" try: return await handler(hass, connection, msg) except Exception as err: # pylint: disable=broad-except err_status, err_msg = _process_cloud_exception(err, msg['type']) connection.send_error(msg['id'], err_status, err_msg) return error_handler def _process_cloud_exception(exc, where): """Process a cloud exception.""" err_info = _CLOUD_ERRORS.get(exc.__class__) if err_info is None: _LOGGER.exception( "Unexpected error processing request for %s", where) err_info = (502, 'Unexpected error: {}'.format(exc)) return err_info class GoogleActionsSyncView(HomeAssistantView): """Trigger a Google Actions Smart Home Sync.""" url = '/api/cloud/google_actions/sync' name = 'api:cloud:google_actions/sync' @_handle_cloud_errors async def post(self, request): """Trigger a Google Actions sync.""" hass = request.app['hass'] cloud = hass.data[DOMAIN] websession = hass.helpers.aiohttp_client.async_get_clientsession() with async_timeout.timeout(REQUEST_TIMEOUT): await hass.async_add_job(cloud.auth.check_token) with async_timeout.timeout(REQUEST_TIMEOUT): req = await websession.post( cloud.google_actions_sync_url, headers={ 'authorization': cloud.id_token }) return self.json({}, status_code=req.status) class CloudLoginView(HomeAssistantView): """Login to Home Assistant cloud.""" url = '/api/cloud/login' name = 'api:cloud:login' @_handle_cloud_errors @RequestDataValidator(vol.Schema({ vol.Required('email'): str, vol.Required('password'): str, })) async def post(self, request, data): """Handle login request.""" hass = request.app['hass'] cloud = hass.data[DOMAIN] with async_timeout.timeout(REQUEST_TIMEOUT): await hass.async_add_job(cloud.auth.login, data['email'], data['password']) hass.async_add_job(cloud.iot.connect) return self.json({'success': True}) class CloudLogoutView(HomeAssistantView): """Log out of the Home Assistant cloud.""" url = '/api/cloud/logout' name = 'api:cloud:logout' @_handle_cloud_errors async def post(self, request): """Handle logout request.""" hass = request.app['hass'] cloud = hass.data[DOMAIN] with async_timeout.timeout(REQUEST_TIMEOUT): await cloud.logout() return self.json_message('ok') class CloudRegisterView(HomeAssistantView): """Register on the Home Assistant cloud.""" url = '/api/cloud/register' name = 'api:cloud:register' @_handle_cloud_errors @RequestDataValidator(vol.Schema({ vol.Required('email'): str, vol.Required('password'): vol.All(str, vol.Length(min=6)), })) async def post(self, request, data): """Handle registration request.""" hass = request.app['hass'] cloud = hass.data[DOMAIN] with async_timeout.timeout(REQUEST_TIMEOUT): await hass.async_add_job( cloud.auth.register, data['email'], data['password']) return self.json_message('ok') class CloudResendConfirmView(HomeAssistantView): """Resend email confirmation code.""" url = '/api/cloud/resend_confirm' name = 'api:cloud:resend_confirm' @_handle_cloud_errors @RequestDataValidator(vol.Schema({ vol.Required('email'): str, })) async def post(self, request, data): """Handle resending confirm email code request.""" hass = request.app['hass'] cloud = hass.data[DOMAIN] with async_timeout.timeout(REQUEST_TIMEOUT): await hass.async_add_job( cloud.auth.resend_email_confirm, data['email']) return self.json_message('ok') class CloudForgotPasswordView(HomeAssistantView): """View to start Forgot Password flow..""" url = '/api/cloud/forgot_password' name = 'api:cloud:forgot_password' @_handle_cloud_errors @RequestDataValidator(vol.Schema({ vol.Required('email'): str, })) async def post(self, request, data): """Handle forgot password request.""" hass = request.app['hass'] cloud = hass.data[DOMAIN] with async_timeout.timeout(REQUEST_TIMEOUT): await hass.async_add_job( cloud.auth.forgot_password, data['email']) return self.json_message('ok') @callback def websocket_cloud_status(hass, connection, msg): """Handle request for account info. Async friendly. """ cloud = hass.data[DOMAIN] connection.send_message( websocket_api.result_message(msg['id'], _account_data(cloud))) def _require_cloud_login(handler): """Websocket decorator that requires cloud to be logged in.""" @wraps(handler) def with_cloud_auth(hass, connection, msg): """Require to be logged into the cloud.""" cloud = hass.data[DOMAIN] if not cloud.is_logged_in: connection.send_message(websocket_api.error_message( msg['id'], 'not_logged_in', 'You need to be logged in to the cloud.')) return handler(hass, connection, msg) return with_cloud_auth @_require_cloud_login @websocket_api.async_response async def websocket_subscription(hass, connection, msg): """Handle request for account info.""" from hass_nabucasa.const import STATE_DISCONNECTED cloud = hass.data[DOMAIN] with async_timeout.timeout(REQUEST_TIMEOUT): response = await cloud.fetch_subscription_info() if response.status != 200: connection.send_message(websocket_api.error_message( msg['id'], 'request_failed', 'Failed to request subscription')) data = await response.json() # Check if a user is subscribed but local info is outdated # In that case, let's refresh and reconnect if data.get('provider') and not cloud.is_connected: _LOGGER.debug( "Found disconnected account with valid subscriotion, connecting") await hass.async_add_executor_job(cloud.auth.renew_access_token) # Cancel reconnect in progress if cloud.iot.state != STATE_DISCONNECTED: await cloud.iot.disconnect() hass.async_create_task(cloud.iot.connect()) connection.send_message(websocket_api.result_message(msg['id'], data)) @_require_cloud_login @websocket_api.async_response @websocket_api.websocket_command({ vol.Required('type'): 'cloud/update_prefs', vol.Optional(PREF_ENABLE_GOOGLE): bool, vol.Optional(PREF_ENABLE_ALEXA): bool, vol.Optional(PREF_ALEXA_REPORT_STATE): bool, vol.Optional(PREF_GOOGLE_SECURE_DEVICES_PIN): vol.Any(None, str), }) async def websocket_update_prefs(hass, connection, msg): """Handle request for account info.""" cloud = hass.data[DOMAIN] changes = dict(msg) changes.pop('id') changes.pop('type') # If we turn alexa linking on, validate that we can fetch access token if changes.get(PREF_ALEXA_REPORT_STATE): try: with async_timeout.timeout(10): await cloud.client.alexa_config.async_get_access_token() except asyncio.TimeoutError: connection.send_error(msg['id'], 'alexa_timeout', 'Timeout validating Alexa access token.') return except (alexa_errors.NoTokenAvailable, RequireRelink): connection.send_error( msg['id'], 'alexa_relink', 'Please go to the Alexa app and re-link the Home Assistant ' 'skill and then try to enable state reporting.' ) return await cloud.client.prefs.async_update(**changes) connection.send_message(websocket_api.result_message(msg['id'])) @_require_cloud_login @websocket_api.async_response @_ws_handle_cloud_errors async def websocket_hook_create(hass, connection, msg): """Handle request for account info.""" cloud = hass.data[DOMAIN] hook = await cloud.cloudhooks.async_create(msg['webhook_id'], False) connection.send_message(websocket_api.result_message(msg['id'], hook)) @_require_cloud_login @websocket_api.async_response @_ws_handle_cloud_errors async def websocket_hook_delete(hass, connection, msg): """Handle request for account info.""" cloud = hass.data[DOMAIN] await cloud.cloudhooks.async_delete(msg['webhook_id']) connection.send_message(websocket_api.result_message(msg['id'])) def _account_data(cloud): """Generate the auth data JSON response.""" from hass_nabucasa.const import STATE_DISCONNECTED if not cloud.is_logged_in: return { 'logged_in': False, 'cloud': STATE_DISCONNECTED, } claims = cloud.claims client = cloud.client remote = cloud.remote # Load remote certificate if remote.certificate: certificate = attr.asdict(remote.certificate) else: certificate = None return { 'logged_in': True, 'email': claims['email'], 'cloud': cloud.iot.state, 'prefs': client.prefs.as_dict(), 'google_entities': client.google_user_config['filter'].config, 'alexa_entities': client.alexa_user_config['filter'].config, 'remote_domain': remote.instance_domain, 'remote_connected': remote.is_connected, 'remote_certificate': certificate, } @websocket_api.require_admin @_require_cloud_login @websocket_api.async_response @_ws_handle_cloud_errors @websocket_api.websocket_command({ 'type': 'cloud/remote/connect' }) async def websocket_remote_connect(hass, connection, msg): """Handle request for connect remote.""" cloud = hass.data[DOMAIN] await cloud.client.prefs.async_update(remote_enabled=True) await cloud.remote.connect() connection.send_result(msg['id'], _account_data(cloud)) @websocket_api.require_admin @_require_cloud_login @websocket_api.async_response @_ws_handle_cloud_errors @websocket_api.websocket_command({ 'type': 'cloud/remote/disconnect' }) async def websocket_remote_disconnect(hass, connection, msg): """Handle request for disconnect remote.""" cloud = hass.data[DOMAIN] await cloud.client.prefs.async_update(remote_enabled=False) await cloud.remote.disconnect() connection.send_result(msg['id'], _account_data(cloud)) @websocket_api.require_admin @_require_cloud_login @websocket_api.async_response @_ws_handle_cloud_errors @websocket_api.websocket_command({ 'type': 'cloud/google_assistant/entities' }) async def google_assistant_list(hass, connection, msg): """List all google assistant entities.""" cloud = hass.data[DOMAIN] entities = google_helpers.async_get_entities( hass, cloud.client.google_config ) result = [] for entity in entities: result.append({ 'entity_id': entity.entity_id, 'traits': [trait.name for trait in entity.traits()], 'might_2fa': entity.might_2fa(), }) connection.send_result(msg['id'], result) @websocket_api.require_admin @_require_cloud_login @websocket_api.async_response @_ws_handle_cloud_errors @websocket_api.websocket_command({ 'type': 'cloud/google_assistant/entities/update', 'entity_id': str, vol.Optional('should_expose'): bool, vol.Optional('override_name'): str, vol.Optional('aliases'): [str], vol.Optional('disable_2fa'): bool, }) async def google_assistant_update(hass, connection, msg): """Update google assistant config.""" cloud = hass.data[DOMAIN] changes = dict(msg) changes.pop('type') changes.pop('id') await cloud.client.prefs.async_update_google_entity_config(**changes) connection.send_result( msg['id'], cloud.client.prefs.google_entity_configs.get(msg['entity_id'])) @websocket_api.require_admin @_require_cloud_login @websocket_api.async_response @_ws_handle_cloud_errors @websocket_api.websocket_command({ 'type': 'cloud/alexa/entities' }) async def alexa_list(hass, connection, msg): """List all alexa entities.""" cloud = hass.data[DOMAIN] entities = alexa_entities.async_get_entities( hass, cloud.client.alexa_config ) result = [] for entity in entities: result.append({ 'entity_id': entity.entity_id, 'display_categories': entity.default_display_categories(), 'interfaces': [ifc.name() for ifc in entity.interfaces()], }) connection.send_result(msg['id'], result) @websocket_api.require_admin @_require_cloud_login @websocket_api.async_response @_ws_handle_cloud_errors @websocket_api.websocket_command({ 'type': 'cloud/alexa/entities/update', 'entity_id': str, vol.Optional('should_expose'): bool, }) async def alexa_update(hass, connection, msg): """Update alexa entity config.""" cloud = hass.data[DOMAIN] changes = dict(msg) changes.pop('type') changes.pop('id') await cloud.client.prefs.async_update_alexa_entity_config(**changes) connection.send_result( msg['id'], cloud.client.prefs.alexa_entity_configs.get(msg['entity_id'])) @websocket_api.require_admin @_require_cloud_login @websocket_api.async_response @websocket_api.websocket_command({ 'type': 'cloud/alexa/sync', }) async def alexa_sync(hass, connection, msg): """Sync with Alexa.""" cloud = hass.data[DOMAIN] with async_timeout.timeout(10): try: success = await cloud.client.alexa_config.async_sync_entities() except alexa_errors.NoTokenAvailable: connection.send_error( msg['id'], 'alexa_relink', 'Please go to the Alexa app and re-link the Home Assistant ' 'skill.' ) return if success: connection.send_result(msg['id']) else: connection.send_error( msg['id'], ws_const.ERR_UNKNOWN_ERROR, 'Unknown error')
"""Tests for the Z-Wave init.""" import asyncio from collections import OrderedDict from datetime import datetime import unittest from unittest.mock import MagicMock, patch import pytest from pytz import utc import voluptuous as vol from homeassistant.bootstrap import async_setup_component from homeassistant.components import zwave from homeassistant.components.zwave import ( CONF_DEVICE_CONFIG_GLOB, CONFIG_SCHEMA, DATA_NETWORK, const) from homeassistant.components.zwave.binary_sensor import get_device from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.device_registry import ( async_get_registry as get_dev_reg) from homeassistant.setup import setup_component from tests.common import ( async_fire_time_changed, get_test_home_assistant, mock_coro, mock_registry) from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue async def test_valid_device_config(hass, mock_openzwave): """Test valid device config.""" device_config = { 'light.kitchen': { 'ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert result async def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = { 'light.kitchen': { 'some_ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert not result def test_config_access_error(): """Test threading error accessing config values.""" node = MagicMock() def side_effect(): raise RuntimeError node.values.values.side_effect = side_effect result = zwave.get_config_value(node, 1) assert result is None async def test_network_options(hass, mock_openzwave): """Test network options.""" result = await async_setup_component(hass, 'zwave', { 'zwave': { 'usb_path': 'mock_usb_path', 'config_path': 'mock_config_path', }}) await hass.async_block_till_done() assert result network = hass.data[zwave.DATA_NETWORK] assert network.options.device == 'mock_usb_path' assert network.options.config_path == 'mock_config_path' async def test_network_key_validation(hass, mock_openzwave): """Test network key validation.""" test_values = [ ('0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,' '0x0E,0x0F,0x10'), ] for value in test_values: result = zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) assert result['zwave']['network_key'] == value async def test_erronous_network_key_fails_validation(hass, mock_openzwave): """Test failing erronous network key validation.""" test_values = [ ('0x 01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0X01,0X02,0X03,0X04,0X05,0X06,0X07,0X08,0X09,0X0A,0X0B,0X0C,0X0D,' '0X0E,0X0F,0X10'), 'invalid', '1234567', 1234567 ] for value in test_values: with pytest.raises(vol.Invalid): zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) async def test_auto_heal_midnight(hass, mock_openzwave): """Test network auto-heal at midnight.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': True, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert network.heal.called assert len(network.heal.mock_calls) == 1 async def test_auto_heal_disabled(hass, mock_openzwave): """Test network auto-heal disabled.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': False, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert not network.heal.called async def test_setup_platform(hass, mock_openzwave): """Test invalid device config.""" mock_device = MagicMock() hass.data[DATA_NETWORK] = MagicMock() hass.data[zwave.DATA_DEVICES] = {456: mock_device} async_add_entities = MagicMock() result = await zwave.async_setup_platform( hass, None, async_add_entities, None) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 123}) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 456}) assert result assert async_add_entities.called assert len(async_add_entities.mock_calls) == 1 assert async_add_entities.mock_calls[0][1][0] == [mock_device] async def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): """Test device entity base class.""" node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.value_added() device.update_properties() await hass.async_block_till_done() assert not device.should_poll assert device.unique_id == "10-11" assert device.name == 'Mock Node Sensor' assert device.device_state_attributes[zwave.ATTR_POWER] == 50.123 async def test_node_removed(hass, mock_openzwave): """Test node removed in base class.""" # Create a mock node & node entity node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.entity_id = 'zwave.mock_node' device.value_added() device.update_properties() await hass.async_block_till_done() # Save it to the entity registry registry = mock_registry(hass) registry.async_get_or_create('zwave', 'zwave', device.unique_id) device.entity_id = registry.async_get_entity_id( 'zwave', 'zwave', device.unique_id) # Create dummy entity registry entries for other integrations hue_entity = registry.async_get_or_create('light', 'hue', 1234) zha_entity = registry.async_get_or_create('sensor', 'zha', 5678) # Verify our Z-Wave entity is registered assert registry.async_is_registered(device.entity_id) # Remove it entity_id = device.entity_id await device.node_removed() # Verify registry entry for our Z-Wave node is gone assert not registry.async_is_registered(entity_id) # Verify registry entries for our other entities remain assert registry.async_is_registered(hue_entity.entity_id) assert registry.async_is_registered(zha_entity.entity_id) async def test_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node').state == 'unknown' async def test_unparsed_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode( node_id=14, manufacturer_name=None, name=None, is_ready=False) sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert len(sleeps) == const.NODE_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1:] == \ (14, const.NODE_READY_WAIT_SECS) assert hass.states.get('zwave.unknown_node_14').state == 'unknown' async def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': { 'device_config': { 'zwave.mock_node': { 'ignored': True, }}}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None async def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' async def test_value_entities(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = {} def mock_connect(receiver, signal, *args, **kwargs): mock_receivers[signal] = receiver with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert mock_receivers hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_ALL_NODES_QUERIED]) node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) zwave_network.nodes = {node.node_id: node} value = MockValue( data=False, node=node, index=12, instance=1, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values = {'primary': value, value.value_id: value} value2 = MockValue( data=False, node=node, index=12, instance=2, label="Mock Value B", command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values[value2.value_id] = value2 hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_NODE_ADDED], node) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value2) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' assert hass.states.get( 'binary_sensor.mock_node_mock_value_b').state == 'off' ent_reg = await async_get_registry(hass) dev_reg = await get_dev_reg(hass) entry = ent_reg.async_get('zwave.mock_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) node_dev_id = entry.device_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) assert entry.name is None assert entry.device_id == node_dev_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value2.object_id) assert entry.name is None assert entry.device_id != node_dev_id device_id_b = entry.device_id device = dev_reg.async_get(node_dev_id) assert device is not None assert device.name == node.name old_device = device device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming without updating await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_NAME: "Demo Node", }) await hass.async_block_till_done() assert node.name == "Demo Node" entry = ent_reg.async_get('zwave.mock_node') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Node", }) await hass.async_block_till_done() assert node.name == "New Node" entry = ent_reg.async_get('zwave.new_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) entry = ent_reg.async_get('binary_sensor.new_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) await hass.services.async_call('zwave', 'rename_value', { const.ATTR_NODE_ID: node.node_id, const.ATTR_VALUE_ID: value.object_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Label", }) await hass.async_block_till_done() entry = ent_reg.async_get('binary_sensor.new_node_new_label') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) async def test_value_discovery_existing_entity(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_THERMOSTAT) setpoint = MockValue( data=22.0, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, setpoint) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] is None def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): temperature = MockValue( data=23.5, node=node, index=1, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, temperature) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] == 23.5 async def test_power_schemes(hass, mock_openzwave): """Test power attribute.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SWITCH_BINARY) switch = MockValue( data=True, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SWITCH_BINARY, genre=const.GENRE_USER, type=const.TYPE_BOOL) hass.async_add_job(mock_receivers[0], node, switch) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').state == 'on' assert 'power_consumption' not in hass.states.get( 'switch.mock_node_mock_value').attributes def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): power = MockValue( data=23.5, node=node, index=const.INDEX_SENSOR_MULTILEVEL_POWER, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL) hass.async_add_job(mock_receivers[0], node, power) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').attributes[ 'power_consumption'] == 23.5 async def test_network_ready(hass, mock_openzwave): """Test Node network ready event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete_some_dead(hass, mock_openzwave): """Test Node network complete some dead event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE_SOME_DEAD, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 class TestZWaveDeviceEntityValues(unittest.TestCase): """Tests for the ZWaveDeviceEntityValues helper.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() self.registry = mock_registry(self.hass) setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.node = MockNode() self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: ['mock_primary_class'], }, 'secondary': { const.DISC_COMMAND_CLASS: ['mock_secondary_class'], }, 'optional': { const.DISC_COMMAND_CLASS: ['mock_optional_class'], const.DISC_OPTIONAL: True, }}} self.primary = MockValue( command_class='mock_primary_class', node=self.node, value_id=1000) self.secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.duplicate_secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.optional = MockValue( command_class='mock_optional_class', node=self.node) self.no_match_value = MockValue( command_class='mock_bad_class', node=self.node) self.entity_id = 'mock_component.mock_node_mock_value' self.zwave_config = {'zwave': {}} self.device_config = {self.entity_id: {}} def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) assert values.primary is self.primary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) self.hass.block_till_done() assert values.secondary is self.secondary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config discovery.async_load_platform.reset_mock() values.check_value(self.optional) values.check_value(self.duplicate_secondary) values.check_value(self.no_match_value) self.hass.block_till_done() assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called assert len(values._entity.value_added.mock_calls) == 1 assert values._entity.value_changed.called assert len(values._entity.value_changed.mock_calls) == 1 @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, self.optional.value_id: self.optional, self.no_match_value.value_id: self.no_match_value, } values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert values.primary is self.primary assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config assert not self.primary.enable_poll.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_node_schema_mismatch(self, discovery, import_module): """Test node schema mismatch.""" self.node.generic = 'no_match' self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.mock_schema[const.DISC_GENERIC_DEVICE_CLASS] = ['generic_match'] values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.manufacturer_id = '010f' self.node.product_type = '0b00' self.primary.command_class = const.COMMAND_CLASS_SENSOR_ALARM self.entity_id = 'binary_sensor.mock_node_mock_value' self.device_config = {self.entity_id: {}} self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} with patch.object(zwave, 'async_dispatcher_send') as \ mock_dispatch_send: values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert mock_dispatch_send.called assert len(mock_dispatch_send.mock_calls) == 1 args = mock_dispatch_send.mock_calls[0][1] assert args[1] == 'zwave_new_binary_sensor' @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_ignore(self, discovery, import_module): """Test ignore workaround.""" self.node.manufacturer_id = '010f' self.node.product_type = '0301' self.primary.command_class = const.COMMAND_CLASS_SWITCH_BINARY self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore(self, discovery, import_module): """Test ignore config.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_IGNORED: True }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore_with_registry(self, discovery, import_module): """Test ignore config. The case when the device is in entity registry. """ self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {'mock_component.registry_id': { zwave.CONF_IGNORED: True }} with patch.object(self.registry, 'async_schedule_save'): self.registry.async_get_or_create( 'mock_component', zwave.DOMAIN, '567-1000', suggested_object_id='registry_id') zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_platform_ignore(self, discovery, import_module): """Test platform ignore device.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } platform = MagicMock() import_module.return_value = platform platform.get_device.return_value = None zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_config_polling_intensity(self, discovery, import_module): """Test polling intensity.""" mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_POLLING_INTENSITY: 123, }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert discovery.async_load_platform.called assert self.primary.enable_poll.called assert len(self.primary.enable_poll.mock_calls) == 1 assert self.primary.enable_poll.mock_calls[0][1][0] == 123 class TestZwave(unittest.TestCase): """Test zwave init.""" def test_device_config_glob_is_ordered(self): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): """Tests for zwave services.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() # Initialize zwave setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.zwave_network = self.hass.data[DATA_NETWORK] self.zwave_network.state = MockNetwork.STATE_READY self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.block_till_done() def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() self.hass.stop() def test_add_node(self): """Test zwave add_node service.""" self.hass.services.call('zwave', 'add_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller .add_node.mock_calls) == 1 assert len(self.zwave_network.controller .add_node.mock_calls[0][1]) == 0 def test_add_node_secure(self): """Test zwave add_node_secure service.""" self.hass.services.call('zwave', 'add_node_secure', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller.add_node.mock_calls) == 1 assert (self.zwave_network.controller .add_node.mock_calls[0][1][0] is True) def test_remove_node(self): """Test zwave remove_node service.""" self.hass.services.call('zwave', 'remove_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.remove_node.called assert len(self.zwave_network.controller.remove_node.mock_calls) == 1 def test_cancel_command(self): """Test zwave cancel_command service.""" self.hass.services.call('zwave', 'cancel_command', {}) self.hass.block_till_done() assert self.zwave_network.controller.cancel_command.called assert len(self.zwave_network.controller .cancel_command.mock_calls) == 1 def test_heal_network(self): """Test zwave heal_network service.""" self.hass.services.call('zwave', 'heal_network', {}) self.hass.block_till_done() assert self.zwave_network.heal.called assert len(self.zwave_network.heal.mock_calls) == 1 def test_soft_reset(self): """Test zwave soft_reset service.""" self.hass.services.call('zwave', 'soft_reset', {}) self.hass.block_till_done() assert self.zwave_network.controller.soft_reset.called assert len(self.zwave_network.controller.soft_reset.mock_calls) == 1 def test_test_network(self): """Test zwave test_network service.""" self.hass.services.call('zwave', 'test_network', {}) self.hass.block_till_done() assert self.zwave_network.test.called assert len(self.zwave_network.test.mock_calls) == 1 def test_stop_network(self): """Test zwave stop_network service.""" with patch.object(self.hass.bus, 'fire') as mock_fire: self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() assert self.zwave_network.stop.called assert len(self.zwave_network.stop.mock_calls) == 1 assert mock_fire.called assert len(mock_fire.mock_calls) == 1 assert mock_fire.mock_calls[0][1][0] == const.EVENT_NETWORK_STOP def test_rename_node(self): """Test zwave rename_node service.""" self.zwave_network.nodes = {11: MagicMock()} self.hass.services.call('zwave', 'rename_node', { const.ATTR_NODE_ID: 11, const.ATTR_NAME: 'test_name', }) self.hass.block_till_done() assert self.zwave_network.nodes[11].name == 'test_name' def test_rename_value(self): """Test zwave rename_value service.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, label="Old Label") node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.label == "Old Label" self.hass.services.call('zwave', 'rename_value', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_NAME: "New Label", }) self.hass.block_till_done() assert value.label == "New Label" def test_set_poll_intensity_enable(self): """Test zwave set_poll_intensity service, successful set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 2 assert enable_poll.mock_calls[0][1][0] == 4 def test_set_poll_intensity_enable_failed(self): """Test zwave set_poll_intensity service, failed set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) value.enable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 1 def test_set_poll_intensity_disable(self): """Test zwave set_poll_intensity service, successful disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 2 def test_set_poll_intensity_disable_failed(self): """Test zwave set_poll_intensity service, failed disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) value.disable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 1 def test_remove_failed_node(self): """Test zwave remove_failed_node service.""" self.hass.services.call('zwave', 'remove_failed_node', { const.ATTR_NODE_ID: 12, }) self.hass.block_till_done() remove_failed_node = self.zwave_network.controller.remove_failed_node assert remove_failed_node.called assert len(remove_failed_node.mock_calls) == 1 assert remove_failed_node.mock_calls[0][1][0] == 12 def test_replace_failed_node(self): """Test zwave replace_failed_node service.""" self.hass.services.call('zwave', 'replace_failed_node', { const.ATTR_NODE_ID: 13, }) self.hass.block_till_done() replace_failed_node = self.zwave_network.controller.replace_failed_node assert replace_failed_node.called assert len(replace_failed_node.mock_calls) == 1 assert replace_failed_node.mock_calls[0][1][0] == 13 def test_set_config_parameter(self): """Test zwave set_config_parameter service.""" value_byte = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BYTE, ) value_list = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['item1', 'item2', 'item3'], ) value_button = MockValue( index=14, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BUTTON, ) value_list_int = MockValue( index=15, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['1', '2', '3'], ) value_bool = MockValue( index=16, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BOOL, ) node = MockNode(node_id=14) node.get_values.return_value = { 12: value_byte, 13: value_list, 14: value_button, 15: value_list_int, 16: value_bool } self.zwave_network.nodes = {14: node} # Byte self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 12, const.ATTR_CONFIG_VALUE: 7, }) self.hass.block_till_done() assert value_byte.data == 7 # List self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, const.ATTR_CONFIG_VALUE: 'item3', }) self.hass.block_till_done() assert value_list.data == 'item3' # Button self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 14, const.ATTR_CONFIG_VALUE: True, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called assert self.zwave_network.manager.releaseButton.called # List of Ints self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 15, const.ATTR_CONFIG_VALUE: 3, }) self.hass.block_till_done() assert value_list_int.data == '3' # Boolean Truthy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'True', }) self.hass.block_till_done() assert value_bool.data == 1 # Boolean Falsy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'False', }) self.hass.block_till_done() assert value_bool.data == 0 # Different Parameter Size self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 19, const.ATTR_CONFIG_VALUE: 0x01020304, const.ATTR_CONFIG_SIZE: 4 }) self.hass.block_till_done() assert node.set_config_param.called assert len(node.set_config_param.mock_calls) == 1 assert node.set_config_param.mock_calls[0][1][0] == 19 assert node.set_config_param.mock_calls[0][1][1] == 0x01020304 assert node.set_config_param.mock_calls[0][1][2] == 4 node.set_config_param.reset_mock() def test_print_config_parameter(self): """Test zwave print_config_parameter service.""" value1 = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, data=1234, ) value2 = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, data=2345, ) node = MockNode(node_id=14) node.values = {12: value1, 13: value2} self.zwave_network.nodes = {14: node} with patch.object(zwave, '_LOGGER') as mock_logger: self.hass.services.call('zwave', 'print_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, }) self.hass.block_till_done() assert mock_logger.info.called assert len(mock_logger.info.mock_calls) == 1 assert mock_logger.info.mock_calls[0][1][1] == 13 assert mock_logger.info.mock_calls[0][1][2] == 14 assert mock_logger.info.mock_calls[0][1][3] == 2345 def test_print_node(self): """Test zwave print_node_parameter service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} with self.assertLogs(level='DEBUG') as mock_logger: self.hass.services.call('zwave', 'print_node', { const.ATTR_NODE_ID: 14 }) self.hass.block_till_done() assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 15, }) self.hass.block_till_done() assert value.data == 15 node.can_wake_up_value = False self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 20, }) self.hass.block_till_done() assert value.data == 15 def test_reset_node_meters(self): """Test zwave reset_node_meters service.""" value = MockValue( instance=1, index=8, data=99.5, command_class=const.COMMAND_CLASS_METER, ) reset_value = MockValue( instance=1, index=33, command_class=const.COMMAND_CLASS_METER, ) node = MockNode(node_id=14) node.values = {8: value, 33: reset_value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, const.ATTR_INSTANCE: 2, }) self.hass.block_till_done() assert not self.zwave_network.manager.pressButton.called assert not self.zwave_network.manager.releaseButton.called self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called value_id, = self.zwave_network.manager.pressButton.mock_calls.pop(0)[1] assert value_id == reset_value.value_id assert self.zwave_network.manager.releaseButton.called value_id, = ( self.zwave_network.manager.releaseButton.mock_calls.pop(0)[1]) assert value_id == reset_value.value_id def test_add_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'add', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.add_association.called assert len(group.add_association.mock_calls) == 1 assert group.add_association.mock_calls[0][1][0] == 24 assert group.add_association.mock_calls[0][1][1] == 5 def test_remove_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'remove', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.remove_association.called assert len(group.remove_association.mock_calls) == 1 assert group.remove_association.mock_calls[0][1][0] == 24 assert group.remove_association.mock_calls[0][1][1] == 5 def test_refresh_entity(self): """Test zwave refresh_entity service.""" node = MockNode() value = MockValue(data=False, node=node, command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50, node=node, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = get_device(node=node, values=values, node_config={}) device.hass = self.hass device.entity_id = 'binary_sensor.mock_entity_id' self.hass.add_job(device.async_added_to_hass()) self.hass.block_till_done() self.hass.services.call('zwave', 'refresh_entity', { ATTR_ENTITY_ID: 'binary_sensor.mock_entity_id', }) self.hass.block_till_done() assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 assert sorted([node.refresh_value.mock_calls[0][1][0], node.refresh_value.mock_calls[1][1][0]]) == \ sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert node.refresh_info.called assert len(node.refresh_info.mock_calls) == 1 def test_set_node_value(self): """Test zwave set_node_value service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=4 ) node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR]) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12, const.ATTR_CONFIG_VALUE: 2, }) self.hass.block_till_done() assert self.zwave_network.nodes[14].values[12].data == 2 def test_refresh_node_value(self): """Test zwave refresh_node_value service.""" node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR], network=self.zwave_network) value = MockValue( node=node, index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=2 ) value.refresh = MagicMock() node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12 }) self.hass.block_till_done() assert value.refresh.called def test_heal_node(self): """Test zwave heal_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'heal_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.heal.called assert len(node.heal.mock_calls) == 1 def test_test_node(self): """Test the zwave test_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'test_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.test.called assert len(node.test.mock_calls) == 1
jabesq/home-assistant
tests/components/zwave/test_init.py
homeassistant/components/cloud/http_api.py
"""Support for Google Home alarm sensor.""" from datetime import timedelta import logging from homeassistant.const import DEVICE_CLASS_TIMESTAMP from homeassistant.helpers.entity import Entity import homeassistant.util.dt as dt_util from . import CLIENT, DOMAIN as GOOGLEHOME_DOMAIN, NAME SCAN_INTERVAL = timedelta(seconds=10) _LOGGER = logging.getLogger(__name__) ICON = 'mdi:alarm' SENSOR_TYPES = { 'timer': 'Timer', 'alarm': 'Alarm', } async def async_setup_platform( hass, config, async_add_entities, discovery_info=None): """Set up the googlehome sensor platform.""" if discovery_info is None: _LOGGER.warning( "To use this you need to configure the 'googlehome' component") return await hass.data[CLIENT].update_info(discovery_info['host']) data = hass.data[GOOGLEHOME_DOMAIN][discovery_info['host']] info = data.get('info', {}) devices = [] for condition in SENSOR_TYPES: device = GoogleHomeAlarm(hass.data[CLIENT], condition, discovery_info, info.get('name', NAME)) devices.append(device) async_add_entities(devices, True) class GoogleHomeAlarm(Entity): """Representation of a GoogleHomeAlarm.""" def __init__(self, client, condition, config, name): """Initialize the GoogleHomeAlarm sensor.""" self._host = config['host'] self._client = client self._condition = condition self._name = None self._state = None self._available = True self._name = "{} {}".format(name, SENSOR_TYPES[self._condition]) async def async_update(self): """Update the data.""" await self._client.update_alarms(self._host) data = self.hass.data[GOOGLEHOME_DOMAIN][self._host] alarms = data.get('alarms')[self._condition] if not alarms: self._available = False return self._available = True time_date = dt_util.utc_from_timestamp(min(element['fire_time'] for element in alarms) / 1000) self._state = time_date.isoformat() @property def state(self): """Return the state.""" return self._state @property def name(self): """Return the name.""" return self._name @property def device_class(self): """Return the device class.""" return DEVICE_CLASS_TIMESTAMP @property def available(self): """Return the availability state.""" return self._available @property def icon(self): """Return the icon.""" return ICON
"""Tests for the Z-Wave init.""" import asyncio from collections import OrderedDict from datetime import datetime import unittest from unittest.mock import MagicMock, patch import pytest from pytz import utc import voluptuous as vol from homeassistant.bootstrap import async_setup_component from homeassistant.components import zwave from homeassistant.components.zwave import ( CONF_DEVICE_CONFIG_GLOB, CONFIG_SCHEMA, DATA_NETWORK, const) from homeassistant.components.zwave.binary_sensor import get_device from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.device_registry import ( async_get_registry as get_dev_reg) from homeassistant.setup import setup_component from tests.common import ( async_fire_time_changed, get_test_home_assistant, mock_coro, mock_registry) from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue async def test_valid_device_config(hass, mock_openzwave): """Test valid device config.""" device_config = { 'light.kitchen': { 'ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert result async def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = { 'light.kitchen': { 'some_ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert not result def test_config_access_error(): """Test threading error accessing config values.""" node = MagicMock() def side_effect(): raise RuntimeError node.values.values.side_effect = side_effect result = zwave.get_config_value(node, 1) assert result is None async def test_network_options(hass, mock_openzwave): """Test network options.""" result = await async_setup_component(hass, 'zwave', { 'zwave': { 'usb_path': 'mock_usb_path', 'config_path': 'mock_config_path', }}) await hass.async_block_till_done() assert result network = hass.data[zwave.DATA_NETWORK] assert network.options.device == 'mock_usb_path' assert network.options.config_path == 'mock_config_path' async def test_network_key_validation(hass, mock_openzwave): """Test network key validation.""" test_values = [ ('0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,' '0x0E,0x0F,0x10'), ] for value in test_values: result = zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) assert result['zwave']['network_key'] == value async def test_erronous_network_key_fails_validation(hass, mock_openzwave): """Test failing erronous network key validation.""" test_values = [ ('0x 01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0X01,0X02,0X03,0X04,0X05,0X06,0X07,0X08,0X09,0X0A,0X0B,0X0C,0X0D,' '0X0E,0X0F,0X10'), 'invalid', '1234567', 1234567 ] for value in test_values: with pytest.raises(vol.Invalid): zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) async def test_auto_heal_midnight(hass, mock_openzwave): """Test network auto-heal at midnight.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': True, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert network.heal.called assert len(network.heal.mock_calls) == 1 async def test_auto_heal_disabled(hass, mock_openzwave): """Test network auto-heal disabled.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': False, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert not network.heal.called async def test_setup_platform(hass, mock_openzwave): """Test invalid device config.""" mock_device = MagicMock() hass.data[DATA_NETWORK] = MagicMock() hass.data[zwave.DATA_DEVICES] = {456: mock_device} async_add_entities = MagicMock() result = await zwave.async_setup_platform( hass, None, async_add_entities, None) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 123}) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 456}) assert result assert async_add_entities.called assert len(async_add_entities.mock_calls) == 1 assert async_add_entities.mock_calls[0][1][0] == [mock_device] async def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): """Test device entity base class.""" node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.value_added() device.update_properties() await hass.async_block_till_done() assert not device.should_poll assert device.unique_id == "10-11" assert device.name == 'Mock Node Sensor' assert device.device_state_attributes[zwave.ATTR_POWER] == 50.123 async def test_node_removed(hass, mock_openzwave): """Test node removed in base class.""" # Create a mock node & node entity node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.entity_id = 'zwave.mock_node' device.value_added() device.update_properties() await hass.async_block_till_done() # Save it to the entity registry registry = mock_registry(hass) registry.async_get_or_create('zwave', 'zwave', device.unique_id) device.entity_id = registry.async_get_entity_id( 'zwave', 'zwave', device.unique_id) # Create dummy entity registry entries for other integrations hue_entity = registry.async_get_or_create('light', 'hue', 1234) zha_entity = registry.async_get_or_create('sensor', 'zha', 5678) # Verify our Z-Wave entity is registered assert registry.async_is_registered(device.entity_id) # Remove it entity_id = device.entity_id await device.node_removed() # Verify registry entry for our Z-Wave node is gone assert not registry.async_is_registered(entity_id) # Verify registry entries for our other entities remain assert registry.async_is_registered(hue_entity.entity_id) assert registry.async_is_registered(zha_entity.entity_id) async def test_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node').state == 'unknown' async def test_unparsed_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode( node_id=14, manufacturer_name=None, name=None, is_ready=False) sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert len(sleeps) == const.NODE_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1:] == \ (14, const.NODE_READY_WAIT_SECS) assert hass.states.get('zwave.unknown_node_14').state == 'unknown' async def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': { 'device_config': { 'zwave.mock_node': { 'ignored': True, }}}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None async def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' async def test_value_entities(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = {} def mock_connect(receiver, signal, *args, **kwargs): mock_receivers[signal] = receiver with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert mock_receivers hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_ALL_NODES_QUERIED]) node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) zwave_network.nodes = {node.node_id: node} value = MockValue( data=False, node=node, index=12, instance=1, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values = {'primary': value, value.value_id: value} value2 = MockValue( data=False, node=node, index=12, instance=2, label="Mock Value B", command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values[value2.value_id] = value2 hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_NODE_ADDED], node) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value2) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' assert hass.states.get( 'binary_sensor.mock_node_mock_value_b').state == 'off' ent_reg = await async_get_registry(hass) dev_reg = await get_dev_reg(hass) entry = ent_reg.async_get('zwave.mock_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) node_dev_id = entry.device_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) assert entry.name is None assert entry.device_id == node_dev_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value2.object_id) assert entry.name is None assert entry.device_id != node_dev_id device_id_b = entry.device_id device = dev_reg.async_get(node_dev_id) assert device is not None assert device.name == node.name old_device = device device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming without updating await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_NAME: "Demo Node", }) await hass.async_block_till_done() assert node.name == "Demo Node" entry = ent_reg.async_get('zwave.mock_node') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Node", }) await hass.async_block_till_done() assert node.name == "New Node" entry = ent_reg.async_get('zwave.new_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) entry = ent_reg.async_get('binary_sensor.new_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) await hass.services.async_call('zwave', 'rename_value', { const.ATTR_NODE_ID: node.node_id, const.ATTR_VALUE_ID: value.object_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Label", }) await hass.async_block_till_done() entry = ent_reg.async_get('binary_sensor.new_node_new_label') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) async def test_value_discovery_existing_entity(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_THERMOSTAT) setpoint = MockValue( data=22.0, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, setpoint) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] is None def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): temperature = MockValue( data=23.5, node=node, index=1, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, temperature) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] == 23.5 async def test_power_schemes(hass, mock_openzwave): """Test power attribute.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SWITCH_BINARY) switch = MockValue( data=True, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SWITCH_BINARY, genre=const.GENRE_USER, type=const.TYPE_BOOL) hass.async_add_job(mock_receivers[0], node, switch) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').state == 'on' assert 'power_consumption' not in hass.states.get( 'switch.mock_node_mock_value').attributes def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): power = MockValue( data=23.5, node=node, index=const.INDEX_SENSOR_MULTILEVEL_POWER, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL) hass.async_add_job(mock_receivers[0], node, power) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').attributes[ 'power_consumption'] == 23.5 async def test_network_ready(hass, mock_openzwave): """Test Node network ready event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete_some_dead(hass, mock_openzwave): """Test Node network complete some dead event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE_SOME_DEAD, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 class TestZWaveDeviceEntityValues(unittest.TestCase): """Tests for the ZWaveDeviceEntityValues helper.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() self.registry = mock_registry(self.hass) setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.node = MockNode() self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: ['mock_primary_class'], }, 'secondary': { const.DISC_COMMAND_CLASS: ['mock_secondary_class'], }, 'optional': { const.DISC_COMMAND_CLASS: ['mock_optional_class'], const.DISC_OPTIONAL: True, }}} self.primary = MockValue( command_class='mock_primary_class', node=self.node, value_id=1000) self.secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.duplicate_secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.optional = MockValue( command_class='mock_optional_class', node=self.node) self.no_match_value = MockValue( command_class='mock_bad_class', node=self.node) self.entity_id = 'mock_component.mock_node_mock_value' self.zwave_config = {'zwave': {}} self.device_config = {self.entity_id: {}} def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) assert values.primary is self.primary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) self.hass.block_till_done() assert values.secondary is self.secondary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config discovery.async_load_platform.reset_mock() values.check_value(self.optional) values.check_value(self.duplicate_secondary) values.check_value(self.no_match_value) self.hass.block_till_done() assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called assert len(values._entity.value_added.mock_calls) == 1 assert values._entity.value_changed.called assert len(values._entity.value_changed.mock_calls) == 1 @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, self.optional.value_id: self.optional, self.no_match_value.value_id: self.no_match_value, } values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert values.primary is self.primary assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config assert not self.primary.enable_poll.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_node_schema_mismatch(self, discovery, import_module): """Test node schema mismatch.""" self.node.generic = 'no_match' self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.mock_schema[const.DISC_GENERIC_DEVICE_CLASS] = ['generic_match'] values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.manufacturer_id = '010f' self.node.product_type = '0b00' self.primary.command_class = const.COMMAND_CLASS_SENSOR_ALARM self.entity_id = 'binary_sensor.mock_node_mock_value' self.device_config = {self.entity_id: {}} self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} with patch.object(zwave, 'async_dispatcher_send') as \ mock_dispatch_send: values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert mock_dispatch_send.called assert len(mock_dispatch_send.mock_calls) == 1 args = mock_dispatch_send.mock_calls[0][1] assert args[1] == 'zwave_new_binary_sensor' @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_ignore(self, discovery, import_module): """Test ignore workaround.""" self.node.manufacturer_id = '010f' self.node.product_type = '0301' self.primary.command_class = const.COMMAND_CLASS_SWITCH_BINARY self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore(self, discovery, import_module): """Test ignore config.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_IGNORED: True }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore_with_registry(self, discovery, import_module): """Test ignore config. The case when the device is in entity registry. """ self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {'mock_component.registry_id': { zwave.CONF_IGNORED: True }} with patch.object(self.registry, 'async_schedule_save'): self.registry.async_get_or_create( 'mock_component', zwave.DOMAIN, '567-1000', suggested_object_id='registry_id') zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_platform_ignore(self, discovery, import_module): """Test platform ignore device.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } platform = MagicMock() import_module.return_value = platform platform.get_device.return_value = None zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_config_polling_intensity(self, discovery, import_module): """Test polling intensity.""" mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_POLLING_INTENSITY: 123, }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert discovery.async_load_platform.called assert self.primary.enable_poll.called assert len(self.primary.enable_poll.mock_calls) == 1 assert self.primary.enable_poll.mock_calls[0][1][0] == 123 class TestZwave(unittest.TestCase): """Test zwave init.""" def test_device_config_glob_is_ordered(self): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): """Tests for zwave services.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() # Initialize zwave setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.zwave_network = self.hass.data[DATA_NETWORK] self.zwave_network.state = MockNetwork.STATE_READY self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.block_till_done() def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() self.hass.stop() def test_add_node(self): """Test zwave add_node service.""" self.hass.services.call('zwave', 'add_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller .add_node.mock_calls) == 1 assert len(self.zwave_network.controller .add_node.mock_calls[0][1]) == 0 def test_add_node_secure(self): """Test zwave add_node_secure service.""" self.hass.services.call('zwave', 'add_node_secure', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller.add_node.mock_calls) == 1 assert (self.zwave_network.controller .add_node.mock_calls[0][1][0] is True) def test_remove_node(self): """Test zwave remove_node service.""" self.hass.services.call('zwave', 'remove_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.remove_node.called assert len(self.zwave_network.controller.remove_node.mock_calls) == 1 def test_cancel_command(self): """Test zwave cancel_command service.""" self.hass.services.call('zwave', 'cancel_command', {}) self.hass.block_till_done() assert self.zwave_network.controller.cancel_command.called assert len(self.zwave_network.controller .cancel_command.mock_calls) == 1 def test_heal_network(self): """Test zwave heal_network service.""" self.hass.services.call('zwave', 'heal_network', {}) self.hass.block_till_done() assert self.zwave_network.heal.called assert len(self.zwave_network.heal.mock_calls) == 1 def test_soft_reset(self): """Test zwave soft_reset service.""" self.hass.services.call('zwave', 'soft_reset', {}) self.hass.block_till_done() assert self.zwave_network.controller.soft_reset.called assert len(self.zwave_network.controller.soft_reset.mock_calls) == 1 def test_test_network(self): """Test zwave test_network service.""" self.hass.services.call('zwave', 'test_network', {}) self.hass.block_till_done() assert self.zwave_network.test.called assert len(self.zwave_network.test.mock_calls) == 1 def test_stop_network(self): """Test zwave stop_network service.""" with patch.object(self.hass.bus, 'fire') as mock_fire: self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() assert self.zwave_network.stop.called assert len(self.zwave_network.stop.mock_calls) == 1 assert mock_fire.called assert len(mock_fire.mock_calls) == 1 assert mock_fire.mock_calls[0][1][0] == const.EVENT_NETWORK_STOP def test_rename_node(self): """Test zwave rename_node service.""" self.zwave_network.nodes = {11: MagicMock()} self.hass.services.call('zwave', 'rename_node', { const.ATTR_NODE_ID: 11, const.ATTR_NAME: 'test_name', }) self.hass.block_till_done() assert self.zwave_network.nodes[11].name == 'test_name' def test_rename_value(self): """Test zwave rename_value service.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, label="Old Label") node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.label == "Old Label" self.hass.services.call('zwave', 'rename_value', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_NAME: "New Label", }) self.hass.block_till_done() assert value.label == "New Label" def test_set_poll_intensity_enable(self): """Test zwave set_poll_intensity service, successful set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 2 assert enable_poll.mock_calls[0][1][0] == 4 def test_set_poll_intensity_enable_failed(self): """Test zwave set_poll_intensity service, failed set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) value.enable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 1 def test_set_poll_intensity_disable(self): """Test zwave set_poll_intensity service, successful disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 2 def test_set_poll_intensity_disable_failed(self): """Test zwave set_poll_intensity service, failed disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) value.disable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 1 def test_remove_failed_node(self): """Test zwave remove_failed_node service.""" self.hass.services.call('zwave', 'remove_failed_node', { const.ATTR_NODE_ID: 12, }) self.hass.block_till_done() remove_failed_node = self.zwave_network.controller.remove_failed_node assert remove_failed_node.called assert len(remove_failed_node.mock_calls) == 1 assert remove_failed_node.mock_calls[0][1][0] == 12 def test_replace_failed_node(self): """Test zwave replace_failed_node service.""" self.hass.services.call('zwave', 'replace_failed_node', { const.ATTR_NODE_ID: 13, }) self.hass.block_till_done() replace_failed_node = self.zwave_network.controller.replace_failed_node assert replace_failed_node.called assert len(replace_failed_node.mock_calls) == 1 assert replace_failed_node.mock_calls[0][1][0] == 13 def test_set_config_parameter(self): """Test zwave set_config_parameter service.""" value_byte = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BYTE, ) value_list = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['item1', 'item2', 'item3'], ) value_button = MockValue( index=14, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BUTTON, ) value_list_int = MockValue( index=15, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['1', '2', '3'], ) value_bool = MockValue( index=16, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BOOL, ) node = MockNode(node_id=14) node.get_values.return_value = { 12: value_byte, 13: value_list, 14: value_button, 15: value_list_int, 16: value_bool } self.zwave_network.nodes = {14: node} # Byte self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 12, const.ATTR_CONFIG_VALUE: 7, }) self.hass.block_till_done() assert value_byte.data == 7 # List self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, const.ATTR_CONFIG_VALUE: 'item3', }) self.hass.block_till_done() assert value_list.data == 'item3' # Button self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 14, const.ATTR_CONFIG_VALUE: True, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called assert self.zwave_network.manager.releaseButton.called # List of Ints self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 15, const.ATTR_CONFIG_VALUE: 3, }) self.hass.block_till_done() assert value_list_int.data == '3' # Boolean Truthy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'True', }) self.hass.block_till_done() assert value_bool.data == 1 # Boolean Falsy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'False', }) self.hass.block_till_done() assert value_bool.data == 0 # Different Parameter Size self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 19, const.ATTR_CONFIG_VALUE: 0x01020304, const.ATTR_CONFIG_SIZE: 4 }) self.hass.block_till_done() assert node.set_config_param.called assert len(node.set_config_param.mock_calls) == 1 assert node.set_config_param.mock_calls[0][1][0] == 19 assert node.set_config_param.mock_calls[0][1][1] == 0x01020304 assert node.set_config_param.mock_calls[0][1][2] == 4 node.set_config_param.reset_mock() def test_print_config_parameter(self): """Test zwave print_config_parameter service.""" value1 = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, data=1234, ) value2 = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, data=2345, ) node = MockNode(node_id=14) node.values = {12: value1, 13: value2} self.zwave_network.nodes = {14: node} with patch.object(zwave, '_LOGGER') as mock_logger: self.hass.services.call('zwave', 'print_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, }) self.hass.block_till_done() assert mock_logger.info.called assert len(mock_logger.info.mock_calls) == 1 assert mock_logger.info.mock_calls[0][1][1] == 13 assert mock_logger.info.mock_calls[0][1][2] == 14 assert mock_logger.info.mock_calls[0][1][3] == 2345 def test_print_node(self): """Test zwave print_node_parameter service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} with self.assertLogs(level='DEBUG') as mock_logger: self.hass.services.call('zwave', 'print_node', { const.ATTR_NODE_ID: 14 }) self.hass.block_till_done() assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 15, }) self.hass.block_till_done() assert value.data == 15 node.can_wake_up_value = False self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 20, }) self.hass.block_till_done() assert value.data == 15 def test_reset_node_meters(self): """Test zwave reset_node_meters service.""" value = MockValue( instance=1, index=8, data=99.5, command_class=const.COMMAND_CLASS_METER, ) reset_value = MockValue( instance=1, index=33, command_class=const.COMMAND_CLASS_METER, ) node = MockNode(node_id=14) node.values = {8: value, 33: reset_value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, const.ATTR_INSTANCE: 2, }) self.hass.block_till_done() assert not self.zwave_network.manager.pressButton.called assert not self.zwave_network.manager.releaseButton.called self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called value_id, = self.zwave_network.manager.pressButton.mock_calls.pop(0)[1] assert value_id == reset_value.value_id assert self.zwave_network.manager.releaseButton.called value_id, = ( self.zwave_network.manager.releaseButton.mock_calls.pop(0)[1]) assert value_id == reset_value.value_id def test_add_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'add', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.add_association.called assert len(group.add_association.mock_calls) == 1 assert group.add_association.mock_calls[0][1][0] == 24 assert group.add_association.mock_calls[0][1][1] == 5 def test_remove_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'remove', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.remove_association.called assert len(group.remove_association.mock_calls) == 1 assert group.remove_association.mock_calls[0][1][0] == 24 assert group.remove_association.mock_calls[0][1][1] == 5 def test_refresh_entity(self): """Test zwave refresh_entity service.""" node = MockNode() value = MockValue(data=False, node=node, command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50, node=node, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = get_device(node=node, values=values, node_config={}) device.hass = self.hass device.entity_id = 'binary_sensor.mock_entity_id' self.hass.add_job(device.async_added_to_hass()) self.hass.block_till_done() self.hass.services.call('zwave', 'refresh_entity', { ATTR_ENTITY_ID: 'binary_sensor.mock_entity_id', }) self.hass.block_till_done() assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 assert sorted([node.refresh_value.mock_calls[0][1][0], node.refresh_value.mock_calls[1][1][0]]) == \ sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert node.refresh_info.called assert len(node.refresh_info.mock_calls) == 1 def test_set_node_value(self): """Test zwave set_node_value service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=4 ) node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR]) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12, const.ATTR_CONFIG_VALUE: 2, }) self.hass.block_till_done() assert self.zwave_network.nodes[14].values[12].data == 2 def test_refresh_node_value(self): """Test zwave refresh_node_value service.""" node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR], network=self.zwave_network) value = MockValue( node=node, index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=2 ) value.refresh = MagicMock() node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12 }) self.hass.block_till_done() assert value.refresh.called def test_heal_node(self): """Test zwave heal_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'heal_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.heal.called assert len(node.heal.mock_calls) == 1 def test_test_node(self): """Test the zwave test_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'test_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.test.called assert len(node.test.mock_calls) == 1
jabesq/home-assistant
tests/components/zwave/test_init.py
homeassistant/components/googlehome/sensor.py
"""Support for Alexa skill service end point.""" import copy from datetime import datetime import logging import uuid from homeassistant.components import http from homeassistant.core import callback from homeassistant.helpers import template from .const import ( ATTR_MAIN_TEXT, ATTR_REDIRECTION_URL, ATTR_STREAM_URL, ATTR_TITLE_TEXT, ATTR_UID, ATTR_UPDATE_DATE, CONF_AUDIO, CONF_DISPLAY_URL, CONF_TEXT, CONF_TITLE, CONF_UID, DATE_FORMAT) _LOGGER = logging.getLogger(__name__) FLASH_BRIEFINGS_API_ENDPOINT = '/api/alexa/flash_briefings/{briefing_id}' @callback def async_setup(hass, flash_briefing_config): """Activate Alexa component.""" hass.http.register_view( AlexaFlashBriefingView(hass, flash_briefing_config)) class AlexaFlashBriefingView(http.HomeAssistantView): """Handle Alexa Flash Briefing skill requests.""" url = FLASH_BRIEFINGS_API_ENDPOINT name = 'api:alexa:flash_briefings' def __init__(self, hass, flash_briefings): """Initialize Alexa view.""" super().__init__() self.flash_briefings = copy.deepcopy(flash_briefings) template.attach(hass, self.flash_briefings) @callback def get(self, request, briefing_id): """Handle Alexa Flash Briefing request.""" _LOGGER.debug("Received Alexa flash briefing request for: %s", briefing_id) if self.flash_briefings.get(briefing_id) is None: err = "No configured Alexa flash briefing was found for: %s" _LOGGER.error(err, briefing_id) return b'', 404 briefing = [] for item in self.flash_briefings.get(briefing_id, []): output = {} if item.get(CONF_TITLE) is not None: if isinstance(item.get(CONF_TITLE), template.Template): output[ATTR_TITLE_TEXT] = item[CONF_TITLE].async_render() else: output[ATTR_TITLE_TEXT] = item.get(CONF_TITLE) if item.get(CONF_TEXT) is not None: if isinstance(item.get(CONF_TEXT), template.Template): output[ATTR_MAIN_TEXT] = item[CONF_TEXT].async_render() else: output[ATTR_MAIN_TEXT] = item.get(CONF_TEXT) uid = item.get(CONF_UID) if uid is None: uid = str(uuid.uuid4()) output[ATTR_UID] = uid if item.get(CONF_AUDIO) is not None: if isinstance(item.get(CONF_AUDIO), template.Template): output[ATTR_STREAM_URL] = item[CONF_AUDIO].async_render() else: output[ATTR_STREAM_URL] = item.get(CONF_AUDIO) if item.get(CONF_DISPLAY_URL) is not None: if isinstance(item.get(CONF_DISPLAY_URL), template.Template): output[ATTR_REDIRECTION_URL] = \ item[CONF_DISPLAY_URL].async_render() else: output[ATTR_REDIRECTION_URL] = item.get(CONF_DISPLAY_URL) output[ATTR_UPDATE_DATE] = datetime.now().strftime(DATE_FORMAT) briefing.append(output) return self.json(briefing)
"""Tests for the Z-Wave init.""" import asyncio from collections import OrderedDict from datetime import datetime import unittest from unittest.mock import MagicMock, patch import pytest from pytz import utc import voluptuous as vol from homeassistant.bootstrap import async_setup_component from homeassistant.components import zwave from homeassistant.components.zwave import ( CONF_DEVICE_CONFIG_GLOB, CONFIG_SCHEMA, DATA_NETWORK, const) from homeassistant.components.zwave.binary_sensor import get_device from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.device_registry import ( async_get_registry as get_dev_reg) from homeassistant.setup import setup_component from tests.common import ( async_fire_time_changed, get_test_home_assistant, mock_coro, mock_registry) from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue async def test_valid_device_config(hass, mock_openzwave): """Test valid device config.""" device_config = { 'light.kitchen': { 'ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert result async def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = { 'light.kitchen': { 'some_ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert not result def test_config_access_error(): """Test threading error accessing config values.""" node = MagicMock() def side_effect(): raise RuntimeError node.values.values.side_effect = side_effect result = zwave.get_config_value(node, 1) assert result is None async def test_network_options(hass, mock_openzwave): """Test network options.""" result = await async_setup_component(hass, 'zwave', { 'zwave': { 'usb_path': 'mock_usb_path', 'config_path': 'mock_config_path', }}) await hass.async_block_till_done() assert result network = hass.data[zwave.DATA_NETWORK] assert network.options.device == 'mock_usb_path' assert network.options.config_path == 'mock_config_path' async def test_network_key_validation(hass, mock_openzwave): """Test network key validation.""" test_values = [ ('0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,' '0x0E,0x0F,0x10'), ] for value in test_values: result = zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) assert result['zwave']['network_key'] == value async def test_erronous_network_key_fails_validation(hass, mock_openzwave): """Test failing erronous network key validation.""" test_values = [ ('0x 01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0X01,0X02,0X03,0X04,0X05,0X06,0X07,0X08,0X09,0X0A,0X0B,0X0C,0X0D,' '0X0E,0X0F,0X10'), 'invalid', '1234567', 1234567 ] for value in test_values: with pytest.raises(vol.Invalid): zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) async def test_auto_heal_midnight(hass, mock_openzwave): """Test network auto-heal at midnight.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': True, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert network.heal.called assert len(network.heal.mock_calls) == 1 async def test_auto_heal_disabled(hass, mock_openzwave): """Test network auto-heal disabled.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': False, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert not network.heal.called async def test_setup_platform(hass, mock_openzwave): """Test invalid device config.""" mock_device = MagicMock() hass.data[DATA_NETWORK] = MagicMock() hass.data[zwave.DATA_DEVICES] = {456: mock_device} async_add_entities = MagicMock() result = await zwave.async_setup_platform( hass, None, async_add_entities, None) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 123}) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 456}) assert result assert async_add_entities.called assert len(async_add_entities.mock_calls) == 1 assert async_add_entities.mock_calls[0][1][0] == [mock_device] async def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): """Test device entity base class.""" node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.value_added() device.update_properties() await hass.async_block_till_done() assert not device.should_poll assert device.unique_id == "10-11" assert device.name == 'Mock Node Sensor' assert device.device_state_attributes[zwave.ATTR_POWER] == 50.123 async def test_node_removed(hass, mock_openzwave): """Test node removed in base class.""" # Create a mock node & node entity node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.entity_id = 'zwave.mock_node' device.value_added() device.update_properties() await hass.async_block_till_done() # Save it to the entity registry registry = mock_registry(hass) registry.async_get_or_create('zwave', 'zwave', device.unique_id) device.entity_id = registry.async_get_entity_id( 'zwave', 'zwave', device.unique_id) # Create dummy entity registry entries for other integrations hue_entity = registry.async_get_or_create('light', 'hue', 1234) zha_entity = registry.async_get_or_create('sensor', 'zha', 5678) # Verify our Z-Wave entity is registered assert registry.async_is_registered(device.entity_id) # Remove it entity_id = device.entity_id await device.node_removed() # Verify registry entry for our Z-Wave node is gone assert not registry.async_is_registered(entity_id) # Verify registry entries for our other entities remain assert registry.async_is_registered(hue_entity.entity_id) assert registry.async_is_registered(zha_entity.entity_id) async def test_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node').state == 'unknown' async def test_unparsed_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode( node_id=14, manufacturer_name=None, name=None, is_ready=False) sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert len(sleeps) == const.NODE_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1:] == \ (14, const.NODE_READY_WAIT_SECS) assert hass.states.get('zwave.unknown_node_14').state == 'unknown' async def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': { 'device_config': { 'zwave.mock_node': { 'ignored': True, }}}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None async def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' async def test_value_entities(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = {} def mock_connect(receiver, signal, *args, **kwargs): mock_receivers[signal] = receiver with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert mock_receivers hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_ALL_NODES_QUERIED]) node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) zwave_network.nodes = {node.node_id: node} value = MockValue( data=False, node=node, index=12, instance=1, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values = {'primary': value, value.value_id: value} value2 = MockValue( data=False, node=node, index=12, instance=2, label="Mock Value B", command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values[value2.value_id] = value2 hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_NODE_ADDED], node) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value2) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' assert hass.states.get( 'binary_sensor.mock_node_mock_value_b').state == 'off' ent_reg = await async_get_registry(hass) dev_reg = await get_dev_reg(hass) entry = ent_reg.async_get('zwave.mock_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) node_dev_id = entry.device_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) assert entry.name is None assert entry.device_id == node_dev_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value2.object_id) assert entry.name is None assert entry.device_id != node_dev_id device_id_b = entry.device_id device = dev_reg.async_get(node_dev_id) assert device is not None assert device.name == node.name old_device = device device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming without updating await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_NAME: "Demo Node", }) await hass.async_block_till_done() assert node.name == "Demo Node" entry = ent_reg.async_get('zwave.mock_node') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Node", }) await hass.async_block_till_done() assert node.name == "New Node" entry = ent_reg.async_get('zwave.new_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) entry = ent_reg.async_get('binary_sensor.new_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) await hass.services.async_call('zwave', 'rename_value', { const.ATTR_NODE_ID: node.node_id, const.ATTR_VALUE_ID: value.object_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Label", }) await hass.async_block_till_done() entry = ent_reg.async_get('binary_sensor.new_node_new_label') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) async def test_value_discovery_existing_entity(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_THERMOSTAT) setpoint = MockValue( data=22.0, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, setpoint) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] is None def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): temperature = MockValue( data=23.5, node=node, index=1, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, temperature) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] == 23.5 async def test_power_schemes(hass, mock_openzwave): """Test power attribute.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SWITCH_BINARY) switch = MockValue( data=True, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SWITCH_BINARY, genre=const.GENRE_USER, type=const.TYPE_BOOL) hass.async_add_job(mock_receivers[0], node, switch) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').state == 'on' assert 'power_consumption' not in hass.states.get( 'switch.mock_node_mock_value').attributes def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): power = MockValue( data=23.5, node=node, index=const.INDEX_SENSOR_MULTILEVEL_POWER, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL) hass.async_add_job(mock_receivers[0], node, power) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').attributes[ 'power_consumption'] == 23.5 async def test_network_ready(hass, mock_openzwave): """Test Node network ready event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete_some_dead(hass, mock_openzwave): """Test Node network complete some dead event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE_SOME_DEAD, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 class TestZWaveDeviceEntityValues(unittest.TestCase): """Tests for the ZWaveDeviceEntityValues helper.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() self.registry = mock_registry(self.hass) setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.node = MockNode() self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: ['mock_primary_class'], }, 'secondary': { const.DISC_COMMAND_CLASS: ['mock_secondary_class'], }, 'optional': { const.DISC_COMMAND_CLASS: ['mock_optional_class'], const.DISC_OPTIONAL: True, }}} self.primary = MockValue( command_class='mock_primary_class', node=self.node, value_id=1000) self.secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.duplicate_secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.optional = MockValue( command_class='mock_optional_class', node=self.node) self.no_match_value = MockValue( command_class='mock_bad_class', node=self.node) self.entity_id = 'mock_component.mock_node_mock_value' self.zwave_config = {'zwave': {}} self.device_config = {self.entity_id: {}} def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) assert values.primary is self.primary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) self.hass.block_till_done() assert values.secondary is self.secondary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config discovery.async_load_platform.reset_mock() values.check_value(self.optional) values.check_value(self.duplicate_secondary) values.check_value(self.no_match_value) self.hass.block_till_done() assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called assert len(values._entity.value_added.mock_calls) == 1 assert values._entity.value_changed.called assert len(values._entity.value_changed.mock_calls) == 1 @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, self.optional.value_id: self.optional, self.no_match_value.value_id: self.no_match_value, } values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert values.primary is self.primary assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config assert not self.primary.enable_poll.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_node_schema_mismatch(self, discovery, import_module): """Test node schema mismatch.""" self.node.generic = 'no_match' self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.mock_schema[const.DISC_GENERIC_DEVICE_CLASS] = ['generic_match'] values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.manufacturer_id = '010f' self.node.product_type = '0b00' self.primary.command_class = const.COMMAND_CLASS_SENSOR_ALARM self.entity_id = 'binary_sensor.mock_node_mock_value' self.device_config = {self.entity_id: {}} self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} with patch.object(zwave, 'async_dispatcher_send') as \ mock_dispatch_send: values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert mock_dispatch_send.called assert len(mock_dispatch_send.mock_calls) == 1 args = mock_dispatch_send.mock_calls[0][1] assert args[1] == 'zwave_new_binary_sensor' @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_ignore(self, discovery, import_module): """Test ignore workaround.""" self.node.manufacturer_id = '010f' self.node.product_type = '0301' self.primary.command_class = const.COMMAND_CLASS_SWITCH_BINARY self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore(self, discovery, import_module): """Test ignore config.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_IGNORED: True }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore_with_registry(self, discovery, import_module): """Test ignore config. The case when the device is in entity registry. """ self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {'mock_component.registry_id': { zwave.CONF_IGNORED: True }} with patch.object(self.registry, 'async_schedule_save'): self.registry.async_get_or_create( 'mock_component', zwave.DOMAIN, '567-1000', suggested_object_id='registry_id') zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_platform_ignore(self, discovery, import_module): """Test platform ignore device.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } platform = MagicMock() import_module.return_value = platform platform.get_device.return_value = None zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_config_polling_intensity(self, discovery, import_module): """Test polling intensity.""" mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_POLLING_INTENSITY: 123, }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert discovery.async_load_platform.called assert self.primary.enable_poll.called assert len(self.primary.enable_poll.mock_calls) == 1 assert self.primary.enable_poll.mock_calls[0][1][0] == 123 class TestZwave(unittest.TestCase): """Test zwave init.""" def test_device_config_glob_is_ordered(self): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): """Tests for zwave services.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() # Initialize zwave setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.zwave_network = self.hass.data[DATA_NETWORK] self.zwave_network.state = MockNetwork.STATE_READY self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.block_till_done() def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() self.hass.stop() def test_add_node(self): """Test zwave add_node service.""" self.hass.services.call('zwave', 'add_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller .add_node.mock_calls) == 1 assert len(self.zwave_network.controller .add_node.mock_calls[0][1]) == 0 def test_add_node_secure(self): """Test zwave add_node_secure service.""" self.hass.services.call('zwave', 'add_node_secure', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller.add_node.mock_calls) == 1 assert (self.zwave_network.controller .add_node.mock_calls[0][1][0] is True) def test_remove_node(self): """Test zwave remove_node service.""" self.hass.services.call('zwave', 'remove_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.remove_node.called assert len(self.zwave_network.controller.remove_node.mock_calls) == 1 def test_cancel_command(self): """Test zwave cancel_command service.""" self.hass.services.call('zwave', 'cancel_command', {}) self.hass.block_till_done() assert self.zwave_network.controller.cancel_command.called assert len(self.zwave_network.controller .cancel_command.mock_calls) == 1 def test_heal_network(self): """Test zwave heal_network service.""" self.hass.services.call('zwave', 'heal_network', {}) self.hass.block_till_done() assert self.zwave_network.heal.called assert len(self.zwave_network.heal.mock_calls) == 1 def test_soft_reset(self): """Test zwave soft_reset service.""" self.hass.services.call('zwave', 'soft_reset', {}) self.hass.block_till_done() assert self.zwave_network.controller.soft_reset.called assert len(self.zwave_network.controller.soft_reset.mock_calls) == 1 def test_test_network(self): """Test zwave test_network service.""" self.hass.services.call('zwave', 'test_network', {}) self.hass.block_till_done() assert self.zwave_network.test.called assert len(self.zwave_network.test.mock_calls) == 1 def test_stop_network(self): """Test zwave stop_network service.""" with patch.object(self.hass.bus, 'fire') as mock_fire: self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() assert self.zwave_network.stop.called assert len(self.zwave_network.stop.mock_calls) == 1 assert mock_fire.called assert len(mock_fire.mock_calls) == 1 assert mock_fire.mock_calls[0][1][0] == const.EVENT_NETWORK_STOP def test_rename_node(self): """Test zwave rename_node service.""" self.zwave_network.nodes = {11: MagicMock()} self.hass.services.call('zwave', 'rename_node', { const.ATTR_NODE_ID: 11, const.ATTR_NAME: 'test_name', }) self.hass.block_till_done() assert self.zwave_network.nodes[11].name == 'test_name' def test_rename_value(self): """Test zwave rename_value service.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, label="Old Label") node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.label == "Old Label" self.hass.services.call('zwave', 'rename_value', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_NAME: "New Label", }) self.hass.block_till_done() assert value.label == "New Label" def test_set_poll_intensity_enable(self): """Test zwave set_poll_intensity service, successful set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 2 assert enable_poll.mock_calls[0][1][0] == 4 def test_set_poll_intensity_enable_failed(self): """Test zwave set_poll_intensity service, failed set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) value.enable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 1 def test_set_poll_intensity_disable(self): """Test zwave set_poll_intensity service, successful disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 2 def test_set_poll_intensity_disable_failed(self): """Test zwave set_poll_intensity service, failed disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) value.disable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 1 def test_remove_failed_node(self): """Test zwave remove_failed_node service.""" self.hass.services.call('zwave', 'remove_failed_node', { const.ATTR_NODE_ID: 12, }) self.hass.block_till_done() remove_failed_node = self.zwave_network.controller.remove_failed_node assert remove_failed_node.called assert len(remove_failed_node.mock_calls) == 1 assert remove_failed_node.mock_calls[0][1][0] == 12 def test_replace_failed_node(self): """Test zwave replace_failed_node service.""" self.hass.services.call('zwave', 'replace_failed_node', { const.ATTR_NODE_ID: 13, }) self.hass.block_till_done() replace_failed_node = self.zwave_network.controller.replace_failed_node assert replace_failed_node.called assert len(replace_failed_node.mock_calls) == 1 assert replace_failed_node.mock_calls[0][1][0] == 13 def test_set_config_parameter(self): """Test zwave set_config_parameter service.""" value_byte = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BYTE, ) value_list = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['item1', 'item2', 'item3'], ) value_button = MockValue( index=14, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BUTTON, ) value_list_int = MockValue( index=15, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['1', '2', '3'], ) value_bool = MockValue( index=16, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BOOL, ) node = MockNode(node_id=14) node.get_values.return_value = { 12: value_byte, 13: value_list, 14: value_button, 15: value_list_int, 16: value_bool } self.zwave_network.nodes = {14: node} # Byte self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 12, const.ATTR_CONFIG_VALUE: 7, }) self.hass.block_till_done() assert value_byte.data == 7 # List self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, const.ATTR_CONFIG_VALUE: 'item3', }) self.hass.block_till_done() assert value_list.data == 'item3' # Button self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 14, const.ATTR_CONFIG_VALUE: True, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called assert self.zwave_network.manager.releaseButton.called # List of Ints self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 15, const.ATTR_CONFIG_VALUE: 3, }) self.hass.block_till_done() assert value_list_int.data == '3' # Boolean Truthy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'True', }) self.hass.block_till_done() assert value_bool.data == 1 # Boolean Falsy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'False', }) self.hass.block_till_done() assert value_bool.data == 0 # Different Parameter Size self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 19, const.ATTR_CONFIG_VALUE: 0x01020304, const.ATTR_CONFIG_SIZE: 4 }) self.hass.block_till_done() assert node.set_config_param.called assert len(node.set_config_param.mock_calls) == 1 assert node.set_config_param.mock_calls[0][1][0] == 19 assert node.set_config_param.mock_calls[0][1][1] == 0x01020304 assert node.set_config_param.mock_calls[0][1][2] == 4 node.set_config_param.reset_mock() def test_print_config_parameter(self): """Test zwave print_config_parameter service.""" value1 = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, data=1234, ) value2 = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, data=2345, ) node = MockNode(node_id=14) node.values = {12: value1, 13: value2} self.zwave_network.nodes = {14: node} with patch.object(zwave, '_LOGGER') as mock_logger: self.hass.services.call('zwave', 'print_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, }) self.hass.block_till_done() assert mock_logger.info.called assert len(mock_logger.info.mock_calls) == 1 assert mock_logger.info.mock_calls[0][1][1] == 13 assert mock_logger.info.mock_calls[0][1][2] == 14 assert mock_logger.info.mock_calls[0][1][3] == 2345 def test_print_node(self): """Test zwave print_node_parameter service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} with self.assertLogs(level='DEBUG') as mock_logger: self.hass.services.call('zwave', 'print_node', { const.ATTR_NODE_ID: 14 }) self.hass.block_till_done() assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 15, }) self.hass.block_till_done() assert value.data == 15 node.can_wake_up_value = False self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 20, }) self.hass.block_till_done() assert value.data == 15 def test_reset_node_meters(self): """Test zwave reset_node_meters service.""" value = MockValue( instance=1, index=8, data=99.5, command_class=const.COMMAND_CLASS_METER, ) reset_value = MockValue( instance=1, index=33, command_class=const.COMMAND_CLASS_METER, ) node = MockNode(node_id=14) node.values = {8: value, 33: reset_value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, const.ATTR_INSTANCE: 2, }) self.hass.block_till_done() assert not self.zwave_network.manager.pressButton.called assert not self.zwave_network.manager.releaseButton.called self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called value_id, = self.zwave_network.manager.pressButton.mock_calls.pop(0)[1] assert value_id == reset_value.value_id assert self.zwave_network.manager.releaseButton.called value_id, = ( self.zwave_network.manager.releaseButton.mock_calls.pop(0)[1]) assert value_id == reset_value.value_id def test_add_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'add', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.add_association.called assert len(group.add_association.mock_calls) == 1 assert group.add_association.mock_calls[0][1][0] == 24 assert group.add_association.mock_calls[0][1][1] == 5 def test_remove_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'remove', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.remove_association.called assert len(group.remove_association.mock_calls) == 1 assert group.remove_association.mock_calls[0][1][0] == 24 assert group.remove_association.mock_calls[0][1][1] == 5 def test_refresh_entity(self): """Test zwave refresh_entity service.""" node = MockNode() value = MockValue(data=False, node=node, command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50, node=node, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = get_device(node=node, values=values, node_config={}) device.hass = self.hass device.entity_id = 'binary_sensor.mock_entity_id' self.hass.add_job(device.async_added_to_hass()) self.hass.block_till_done() self.hass.services.call('zwave', 'refresh_entity', { ATTR_ENTITY_ID: 'binary_sensor.mock_entity_id', }) self.hass.block_till_done() assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 assert sorted([node.refresh_value.mock_calls[0][1][0], node.refresh_value.mock_calls[1][1][0]]) == \ sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert node.refresh_info.called assert len(node.refresh_info.mock_calls) == 1 def test_set_node_value(self): """Test zwave set_node_value service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=4 ) node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR]) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12, const.ATTR_CONFIG_VALUE: 2, }) self.hass.block_till_done() assert self.zwave_network.nodes[14].values[12].data == 2 def test_refresh_node_value(self): """Test zwave refresh_node_value service.""" node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR], network=self.zwave_network) value = MockValue( node=node, index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=2 ) value.refresh = MagicMock() node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12 }) self.hass.block_till_done() assert value.refresh.called def test_heal_node(self): """Test zwave heal_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'heal_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.heal.called assert len(node.heal.mock_calls) == 1 def test_test_node(self): """Test the zwave test_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'test_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.test.called assert len(node.test.mock_calls) == 1
jabesq/home-assistant
tests/components/zwave/test_init.py
homeassistant/components/alexa/flash_briefings.py
"""Get your own public IP address or that of any host.""" from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_NAME import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) CONF_HOSTNAME = 'hostname' CONF_IPV6 = 'ipv6' CONF_RESOLVER = 'resolver' CONF_RESOLVER_IPV6 = 'resolver_ipv6' DEFAULT_HOSTNAME = 'myip.opendns.com' DEFAULT_IPV6 = False DEFAULT_NAME = 'myip' DEFAULT_RESOLVER = '208.67.222.222' DEFAULT_RESOLVER_IPV6 = '2620:0:ccc::2' SCAN_INTERVAL = timedelta(seconds=120) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_NAME): cv.string, vol.Optional(CONF_HOSTNAME, default=DEFAULT_HOSTNAME): cv.string, vol.Optional(CONF_RESOLVER, default=DEFAULT_RESOLVER): cv.string, vol.Optional(CONF_RESOLVER_IPV6, default=DEFAULT_RESOLVER_IPV6): cv.string, vol.Optional(CONF_IPV6, default=DEFAULT_IPV6): cv.boolean, }) async def async_setup_platform( hass, config, async_add_devices, discovery_info=None): """Set up the DNS IP sensor.""" hostname = config.get(CONF_HOSTNAME) name = config.get(CONF_NAME) if not name: if hostname == DEFAULT_HOSTNAME: name = DEFAULT_NAME else: name = hostname ipv6 = config.get(CONF_IPV6) if ipv6: resolver = config.get(CONF_RESOLVER_IPV6) else: resolver = config.get(CONF_RESOLVER) async_add_devices([WanIpSensor( hass, name, hostname, resolver, ipv6)], True) class WanIpSensor(Entity): """Implementation of a DNS IP sensor.""" def __init__(self, hass, name, hostname, resolver, ipv6): """Initialize the DNS IP sensor.""" import aiodns self.hass = hass self._name = name self.hostname = hostname self.resolver = aiodns.DNSResolver() self.resolver.nameservers = [resolver] self.querytype = 'AAAA' if ipv6 else 'A' self._state = None @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the current DNS IP address for hostname.""" return self._state async def async_update(self): """Get the current DNS IP address for hostname.""" from aiodns.error import DNSError try: response = await self.resolver.query( self.hostname, self.querytype) except DNSError as err: _LOGGER.warning("Exception while resolving host: %s", err) response = None if response: self._state = response[0].host else: self._state = None
"""Tests for the Z-Wave init.""" import asyncio from collections import OrderedDict from datetime import datetime import unittest from unittest.mock import MagicMock, patch import pytest from pytz import utc import voluptuous as vol from homeassistant.bootstrap import async_setup_component from homeassistant.components import zwave from homeassistant.components.zwave import ( CONF_DEVICE_CONFIG_GLOB, CONFIG_SCHEMA, DATA_NETWORK, const) from homeassistant.components.zwave.binary_sensor import get_device from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.device_registry import ( async_get_registry as get_dev_reg) from homeassistant.setup import setup_component from tests.common import ( async_fire_time_changed, get_test_home_assistant, mock_coro, mock_registry) from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue async def test_valid_device_config(hass, mock_openzwave): """Test valid device config.""" device_config = { 'light.kitchen': { 'ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert result async def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = { 'light.kitchen': { 'some_ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert not result def test_config_access_error(): """Test threading error accessing config values.""" node = MagicMock() def side_effect(): raise RuntimeError node.values.values.side_effect = side_effect result = zwave.get_config_value(node, 1) assert result is None async def test_network_options(hass, mock_openzwave): """Test network options.""" result = await async_setup_component(hass, 'zwave', { 'zwave': { 'usb_path': 'mock_usb_path', 'config_path': 'mock_config_path', }}) await hass.async_block_till_done() assert result network = hass.data[zwave.DATA_NETWORK] assert network.options.device == 'mock_usb_path' assert network.options.config_path == 'mock_config_path' async def test_network_key_validation(hass, mock_openzwave): """Test network key validation.""" test_values = [ ('0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,' '0x0E,0x0F,0x10'), ] for value in test_values: result = zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) assert result['zwave']['network_key'] == value async def test_erronous_network_key_fails_validation(hass, mock_openzwave): """Test failing erronous network key validation.""" test_values = [ ('0x 01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0X01,0X02,0X03,0X04,0X05,0X06,0X07,0X08,0X09,0X0A,0X0B,0X0C,0X0D,' '0X0E,0X0F,0X10'), 'invalid', '1234567', 1234567 ] for value in test_values: with pytest.raises(vol.Invalid): zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) async def test_auto_heal_midnight(hass, mock_openzwave): """Test network auto-heal at midnight.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': True, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert network.heal.called assert len(network.heal.mock_calls) == 1 async def test_auto_heal_disabled(hass, mock_openzwave): """Test network auto-heal disabled.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': False, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert not network.heal.called async def test_setup_platform(hass, mock_openzwave): """Test invalid device config.""" mock_device = MagicMock() hass.data[DATA_NETWORK] = MagicMock() hass.data[zwave.DATA_DEVICES] = {456: mock_device} async_add_entities = MagicMock() result = await zwave.async_setup_platform( hass, None, async_add_entities, None) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 123}) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 456}) assert result assert async_add_entities.called assert len(async_add_entities.mock_calls) == 1 assert async_add_entities.mock_calls[0][1][0] == [mock_device] async def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): """Test device entity base class.""" node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.value_added() device.update_properties() await hass.async_block_till_done() assert not device.should_poll assert device.unique_id == "10-11" assert device.name == 'Mock Node Sensor' assert device.device_state_attributes[zwave.ATTR_POWER] == 50.123 async def test_node_removed(hass, mock_openzwave): """Test node removed in base class.""" # Create a mock node & node entity node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.entity_id = 'zwave.mock_node' device.value_added() device.update_properties() await hass.async_block_till_done() # Save it to the entity registry registry = mock_registry(hass) registry.async_get_or_create('zwave', 'zwave', device.unique_id) device.entity_id = registry.async_get_entity_id( 'zwave', 'zwave', device.unique_id) # Create dummy entity registry entries for other integrations hue_entity = registry.async_get_or_create('light', 'hue', 1234) zha_entity = registry.async_get_or_create('sensor', 'zha', 5678) # Verify our Z-Wave entity is registered assert registry.async_is_registered(device.entity_id) # Remove it entity_id = device.entity_id await device.node_removed() # Verify registry entry for our Z-Wave node is gone assert not registry.async_is_registered(entity_id) # Verify registry entries for our other entities remain assert registry.async_is_registered(hue_entity.entity_id) assert registry.async_is_registered(zha_entity.entity_id) async def test_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node').state == 'unknown' async def test_unparsed_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode( node_id=14, manufacturer_name=None, name=None, is_ready=False) sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert len(sleeps) == const.NODE_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1:] == \ (14, const.NODE_READY_WAIT_SECS) assert hass.states.get('zwave.unknown_node_14').state == 'unknown' async def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': { 'device_config': { 'zwave.mock_node': { 'ignored': True, }}}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None async def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' async def test_value_entities(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = {} def mock_connect(receiver, signal, *args, **kwargs): mock_receivers[signal] = receiver with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert mock_receivers hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_ALL_NODES_QUERIED]) node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) zwave_network.nodes = {node.node_id: node} value = MockValue( data=False, node=node, index=12, instance=1, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values = {'primary': value, value.value_id: value} value2 = MockValue( data=False, node=node, index=12, instance=2, label="Mock Value B", command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values[value2.value_id] = value2 hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_NODE_ADDED], node) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value2) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' assert hass.states.get( 'binary_sensor.mock_node_mock_value_b').state == 'off' ent_reg = await async_get_registry(hass) dev_reg = await get_dev_reg(hass) entry = ent_reg.async_get('zwave.mock_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) node_dev_id = entry.device_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) assert entry.name is None assert entry.device_id == node_dev_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value2.object_id) assert entry.name is None assert entry.device_id != node_dev_id device_id_b = entry.device_id device = dev_reg.async_get(node_dev_id) assert device is not None assert device.name == node.name old_device = device device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming without updating await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_NAME: "Demo Node", }) await hass.async_block_till_done() assert node.name == "Demo Node" entry = ent_reg.async_get('zwave.mock_node') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Node", }) await hass.async_block_till_done() assert node.name == "New Node" entry = ent_reg.async_get('zwave.new_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) entry = ent_reg.async_get('binary_sensor.new_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) await hass.services.async_call('zwave', 'rename_value', { const.ATTR_NODE_ID: node.node_id, const.ATTR_VALUE_ID: value.object_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Label", }) await hass.async_block_till_done() entry = ent_reg.async_get('binary_sensor.new_node_new_label') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) async def test_value_discovery_existing_entity(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_THERMOSTAT) setpoint = MockValue( data=22.0, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, setpoint) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] is None def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): temperature = MockValue( data=23.5, node=node, index=1, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, temperature) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] == 23.5 async def test_power_schemes(hass, mock_openzwave): """Test power attribute.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SWITCH_BINARY) switch = MockValue( data=True, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SWITCH_BINARY, genre=const.GENRE_USER, type=const.TYPE_BOOL) hass.async_add_job(mock_receivers[0], node, switch) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').state == 'on' assert 'power_consumption' not in hass.states.get( 'switch.mock_node_mock_value').attributes def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): power = MockValue( data=23.5, node=node, index=const.INDEX_SENSOR_MULTILEVEL_POWER, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL) hass.async_add_job(mock_receivers[0], node, power) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').attributes[ 'power_consumption'] == 23.5 async def test_network_ready(hass, mock_openzwave): """Test Node network ready event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete_some_dead(hass, mock_openzwave): """Test Node network complete some dead event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE_SOME_DEAD, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 class TestZWaveDeviceEntityValues(unittest.TestCase): """Tests for the ZWaveDeviceEntityValues helper.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() self.registry = mock_registry(self.hass) setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.node = MockNode() self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: ['mock_primary_class'], }, 'secondary': { const.DISC_COMMAND_CLASS: ['mock_secondary_class'], }, 'optional': { const.DISC_COMMAND_CLASS: ['mock_optional_class'], const.DISC_OPTIONAL: True, }}} self.primary = MockValue( command_class='mock_primary_class', node=self.node, value_id=1000) self.secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.duplicate_secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.optional = MockValue( command_class='mock_optional_class', node=self.node) self.no_match_value = MockValue( command_class='mock_bad_class', node=self.node) self.entity_id = 'mock_component.mock_node_mock_value' self.zwave_config = {'zwave': {}} self.device_config = {self.entity_id: {}} def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) assert values.primary is self.primary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) self.hass.block_till_done() assert values.secondary is self.secondary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config discovery.async_load_platform.reset_mock() values.check_value(self.optional) values.check_value(self.duplicate_secondary) values.check_value(self.no_match_value) self.hass.block_till_done() assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called assert len(values._entity.value_added.mock_calls) == 1 assert values._entity.value_changed.called assert len(values._entity.value_changed.mock_calls) == 1 @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, self.optional.value_id: self.optional, self.no_match_value.value_id: self.no_match_value, } values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert values.primary is self.primary assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config assert not self.primary.enable_poll.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_node_schema_mismatch(self, discovery, import_module): """Test node schema mismatch.""" self.node.generic = 'no_match' self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.mock_schema[const.DISC_GENERIC_DEVICE_CLASS] = ['generic_match'] values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.manufacturer_id = '010f' self.node.product_type = '0b00' self.primary.command_class = const.COMMAND_CLASS_SENSOR_ALARM self.entity_id = 'binary_sensor.mock_node_mock_value' self.device_config = {self.entity_id: {}} self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} with patch.object(zwave, 'async_dispatcher_send') as \ mock_dispatch_send: values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert mock_dispatch_send.called assert len(mock_dispatch_send.mock_calls) == 1 args = mock_dispatch_send.mock_calls[0][1] assert args[1] == 'zwave_new_binary_sensor' @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_ignore(self, discovery, import_module): """Test ignore workaround.""" self.node.manufacturer_id = '010f' self.node.product_type = '0301' self.primary.command_class = const.COMMAND_CLASS_SWITCH_BINARY self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore(self, discovery, import_module): """Test ignore config.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_IGNORED: True }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore_with_registry(self, discovery, import_module): """Test ignore config. The case when the device is in entity registry. """ self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {'mock_component.registry_id': { zwave.CONF_IGNORED: True }} with patch.object(self.registry, 'async_schedule_save'): self.registry.async_get_or_create( 'mock_component', zwave.DOMAIN, '567-1000', suggested_object_id='registry_id') zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_platform_ignore(self, discovery, import_module): """Test platform ignore device.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } platform = MagicMock() import_module.return_value = platform platform.get_device.return_value = None zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_config_polling_intensity(self, discovery, import_module): """Test polling intensity.""" mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_POLLING_INTENSITY: 123, }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert discovery.async_load_platform.called assert self.primary.enable_poll.called assert len(self.primary.enable_poll.mock_calls) == 1 assert self.primary.enable_poll.mock_calls[0][1][0] == 123 class TestZwave(unittest.TestCase): """Test zwave init.""" def test_device_config_glob_is_ordered(self): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): """Tests for zwave services.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() # Initialize zwave setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.zwave_network = self.hass.data[DATA_NETWORK] self.zwave_network.state = MockNetwork.STATE_READY self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.block_till_done() def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() self.hass.stop() def test_add_node(self): """Test zwave add_node service.""" self.hass.services.call('zwave', 'add_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller .add_node.mock_calls) == 1 assert len(self.zwave_network.controller .add_node.mock_calls[0][1]) == 0 def test_add_node_secure(self): """Test zwave add_node_secure service.""" self.hass.services.call('zwave', 'add_node_secure', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller.add_node.mock_calls) == 1 assert (self.zwave_network.controller .add_node.mock_calls[0][1][0] is True) def test_remove_node(self): """Test zwave remove_node service.""" self.hass.services.call('zwave', 'remove_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.remove_node.called assert len(self.zwave_network.controller.remove_node.mock_calls) == 1 def test_cancel_command(self): """Test zwave cancel_command service.""" self.hass.services.call('zwave', 'cancel_command', {}) self.hass.block_till_done() assert self.zwave_network.controller.cancel_command.called assert len(self.zwave_network.controller .cancel_command.mock_calls) == 1 def test_heal_network(self): """Test zwave heal_network service.""" self.hass.services.call('zwave', 'heal_network', {}) self.hass.block_till_done() assert self.zwave_network.heal.called assert len(self.zwave_network.heal.mock_calls) == 1 def test_soft_reset(self): """Test zwave soft_reset service.""" self.hass.services.call('zwave', 'soft_reset', {}) self.hass.block_till_done() assert self.zwave_network.controller.soft_reset.called assert len(self.zwave_network.controller.soft_reset.mock_calls) == 1 def test_test_network(self): """Test zwave test_network service.""" self.hass.services.call('zwave', 'test_network', {}) self.hass.block_till_done() assert self.zwave_network.test.called assert len(self.zwave_network.test.mock_calls) == 1 def test_stop_network(self): """Test zwave stop_network service.""" with patch.object(self.hass.bus, 'fire') as mock_fire: self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() assert self.zwave_network.stop.called assert len(self.zwave_network.stop.mock_calls) == 1 assert mock_fire.called assert len(mock_fire.mock_calls) == 1 assert mock_fire.mock_calls[0][1][0] == const.EVENT_NETWORK_STOP def test_rename_node(self): """Test zwave rename_node service.""" self.zwave_network.nodes = {11: MagicMock()} self.hass.services.call('zwave', 'rename_node', { const.ATTR_NODE_ID: 11, const.ATTR_NAME: 'test_name', }) self.hass.block_till_done() assert self.zwave_network.nodes[11].name == 'test_name' def test_rename_value(self): """Test zwave rename_value service.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, label="Old Label") node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.label == "Old Label" self.hass.services.call('zwave', 'rename_value', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_NAME: "New Label", }) self.hass.block_till_done() assert value.label == "New Label" def test_set_poll_intensity_enable(self): """Test zwave set_poll_intensity service, successful set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 2 assert enable_poll.mock_calls[0][1][0] == 4 def test_set_poll_intensity_enable_failed(self): """Test zwave set_poll_intensity service, failed set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) value.enable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 1 def test_set_poll_intensity_disable(self): """Test zwave set_poll_intensity service, successful disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 2 def test_set_poll_intensity_disable_failed(self): """Test zwave set_poll_intensity service, failed disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) value.disable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 1 def test_remove_failed_node(self): """Test zwave remove_failed_node service.""" self.hass.services.call('zwave', 'remove_failed_node', { const.ATTR_NODE_ID: 12, }) self.hass.block_till_done() remove_failed_node = self.zwave_network.controller.remove_failed_node assert remove_failed_node.called assert len(remove_failed_node.mock_calls) == 1 assert remove_failed_node.mock_calls[0][1][0] == 12 def test_replace_failed_node(self): """Test zwave replace_failed_node service.""" self.hass.services.call('zwave', 'replace_failed_node', { const.ATTR_NODE_ID: 13, }) self.hass.block_till_done() replace_failed_node = self.zwave_network.controller.replace_failed_node assert replace_failed_node.called assert len(replace_failed_node.mock_calls) == 1 assert replace_failed_node.mock_calls[0][1][0] == 13 def test_set_config_parameter(self): """Test zwave set_config_parameter service.""" value_byte = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BYTE, ) value_list = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['item1', 'item2', 'item3'], ) value_button = MockValue( index=14, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BUTTON, ) value_list_int = MockValue( index=15, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['1', '2', '3'], ) value_bool = MockValue( index=16, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BOOL, ) node = MockNode(node_id=14) node.get_values.return_value = { 12: value_byte, 13: value_list, 14: value_button, 15: value_list_int, 16: value_bool } self.zwave_network.nodes = {14: node} # Byte self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 12, const.ATTR_CONFIG_VALUE: 7, }) self.hass.block_till_done() assert value_byte.data == 7 # List self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, const.ATTR_CONFIG_VALUE: 'item3', }) self.hass.block_till_done() assert value_list.data == 'item3' # Button self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 14, const.ATTR_CONFIG_VALUE: True, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called assert self.zwave_network.manager.releaseButton.called # List of Ints self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 15, const.ATTR_CONFIG_VALUE: 3, }) self.hass.block_till_done() assert value_list_int.data == '3' # Boolean Truthy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'True', }) self.hass.block_till_done() assert value_bool.data == 1 # Boolean Falsy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'False', }) self.hass.block_till_done() assert value_bool.data == 0 # Different Parameter Size self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 19, const.ATTR_CONFIG_VALUE: 0x01020304, const.ATTR_CONFIG_SIZE: 4 }) self.hass.block_till_done() assert node.set_config_param.called assert len(node.set_config_param.mock_calls) == 1 assert node.set_config_param.mock_calls[0][1][0] == 19 assert node.set_config_param.mock_calls[0][1][1] == 0x01020304 assert node.set_config_param.mock_calls[0][1][2] == 4 node.set_config_param.reset_mock() def test_print_config_parameter(self): """Test zwave print_config_parameter service.""" value1 = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, data=1234, ) value2 = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, data=2345, ) node = MockNode(node_id=14) node.values = {12: value1, 13: value2} self.zwave_network.nodes = {14: node} with patch.object(zwave, '_LOGGER') as mock_logger: self.hass.services.call('zwave', 'print_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, }) self.hass.block_till_done() assert mock_logger.info.called assert len(mock_logger.info.mock_calls) == 1 assert mock_logger.info.mock_calls[0][1][1] == 13 assert mock_logger.info.mock_calls[0][1][2] == 14 assert mock_logger.info.mock_calls[0][1][3] == 2345 def test_print_node(self): """Test zwave print_node_parameter service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} with self.assertLogs(level='DEBUG') as mock_logger: self.hass.services.call('zwave', 'print_node', { const.ATTR_NODE_ID: 14 }) self.hass.block_till_done() assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 15, }) self.hass.block_till_done() assert value.data == 15 node.can_wake_up_value = False self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 20, }) self.hass.block_till_done() assert value.data == 15 def test_reset_node_meters(self): """Test zwave reset_node_meters service.""" value = MockValue( instance=1, index=8, data=99.5, command_class=const.COMMAND_CLASS_METER, ) reset_value = MockValue( instance=1, index=33, command_class=const.COMMAND_CLASS_METER, ) node = MockNode(node_id=14) node.values = {8: value, 33: reset_value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, const.ATTR_INSTANCE: 2, }) self.hass.block_till_done() assert not self.zwave_network.manager.pressButton.called assert not self.zwave_network.manager.releaseButton.called self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called value_id, = self.zwave_network.manager.pressButton.mock_calls.pop(0)[1] assert value_id == reset_value.value_id assert self.zwave_network.manager.releaseButton.called value_id, = ( self.zwave_network.manager.releaseButton.mock_calls.pop(0)[1]) assert value_id == reset_value.value_id def test_add_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'add', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.add_association.called assert len(group.add_association.mock_calls) == 1 assert group.add_association.mock_calls[0][1][0] == 24 assert group.add_association.mock_calls[0][1][1] == 5 def test_remove_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'remove', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.remove_association.called assert len(group.remove_association.mock_calls) == 1 assert group.remove_association.mock_calls[0][1][0] == 24 assert group.remove_association.mock_calls[0][1][1] == 5 def test_refresh_entity(self): """Test zwave refresh_entity service.""" node = MockNode() value = MockValue(data=False, node=node, command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50, node=node, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = get_device(node=node, values=values, node_config={}) device.hass = self.hass device.entity_id = 'binary_sensor.mock_entity_id' self.hass.add_job(device.async_added_to_hass()) self.hass.block_till_done() self.hass.services.call('zwave', 'refresh_entity', { ATTR_ENTITY_ID: 'binary_sensor.mock_entity_id', }) self.hass.block_till_done() assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 assert sorted([node.refresh_value.mock_calls[0][1][0], node.refresh_value.mock_calls[1][1][0]]) == \ sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert node.refresh_info.called assert len(node.refresh_info.mock_calls) == 1 def test_set_node_value(self): """Test zwave set_node_value service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=4 ) node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR]) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12, const.ATTR_CONFIG_VALUE: 2, }) self.hass.block_till_done() assert self.zwave_network.nodes[14].values[12].data == 2 def test_refresh_node_value(self): """Test zwave refresh_node_value service.""" node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR], network=self.zwave_network) value = MockValue( node=node, index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=2 ) value.refresh = MagicMock() node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12 }) self.hass.block_till_done() assert value.refresh.called def test_heal_node(self): """Test zwave heal_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'heal_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.heal.called assert len(node.heal.mock_calls) == 1 def test_test_node(self): """Test the zwave test_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'test_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.test.called assert len(node.test.mock_calls) == 1
jabesq/home-assistant
tests/components/zwave/test_init.py
homeassistant/components/dnsip/sensor.py
"""Support for the KIWI.KI lock platform.""" import logging import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.lock import (LockDevice, PLATFORM_SCHEMA) from homeassistant.const import ( CONF_PASSWORD, CONF_USERNAME, ATTR_ID, ATTR_LONGITUDE, ATTR_LATITUDE, STATE_LOCKED, STATE_UNLOCKED) from homeassistant.helpers.event import async_call_later from homeassistant.core import callback _LOGGER = logging.getLogger(__name__) ATTR_TYPE = 'hardware_type' ATTR_PERMISSION = 'permission' ATTR_CAN_INVITE = 'can_invite_others' UNLOCK_MAINTAIN_TIME = 5 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the KIWI lock platform.""" from kiwiki import KiwiClient, KiwiException try: kiwi = KiwiClient(config[CONF_USERNAME], config[CONF_PASSWORD]) except KiwiException as exc: _LOGGER.error(exc) return available_locks = kiwi.get_locks() if not available_locks: # No locks found; abort setup routine. _LOGGER.info("No KIWI locks found in your account.") return add_entities([KiwiLock(lock, kiwi) for lock in available_locks], True) class KiwiLock(LockDevice): """Representation of a Kiwi lock.""" def __init__(self, kiwi_lock, client): """Initialize the lock.""" self._sensor = kiwi_lock self._client = client self.lock_id = kiwi_lock['sensor_id'] self._state = STATE_LOCKED address = kiwi_lock.get('address') address.update({ ATTR_LATITUDE: address.pop('lat', None), ATTR_LONGITUDE: address.pop('lng', None) }) self._device_attrs = { ATTR_ID: self.lock_id, ATTR_TYPE: kiwi_lock.get('hardware_type'), ATTR_PERMISSION: kiwi_lock.get('highest_permission'), ATTR_CAN_INVITE: kiwi_lock.get('can_invite'), **address } @property def name(self): """Return the name of the lock.""" name = self._sensor.get('name') specifier = self._sensor['address'].get('specifier') return name or specifier @property def is_locked(self): """Return true if lock is locked.""" return self._state == STATE_LOCKED @property def device_state_attributes(self): """Return the device specific state attributes.""" return self._device_attrs @callback def clear_unlock_state(self, _): """Clear unlock state automatically.""" self._state = STATE_LOCKED self.async_schedule_update_ha_state() def unlock(self, **kwargs): """Unlock the device.""" from kiwiki import KiwiException try: self._client.open_door(self.lock_id) except KiwiException: _LOGGER.error("failed to open door") else: self._state = STATE_UNLOCKED self.hass.add_job( async_call_later, self.hass, UNLOCK_MAINTAIN_TIME, self.clear_unlock_state )
"""Tests for the Z-Wave init.""" import asyncio from collections import OrderedDict from datetime import datetime import unittest from unittest.mock import MagicMock, patch import pytest from pytz import utc import voluptuous as vol from homeassistant.bootstrap import async_setup_component from homeassistant.components import zwave from homeassistant.components.zwave import ( CONF_DEVICE_CONFIG_GLOB, CONFIG_SCHEMA, DATA_NETWORK, const) from homeassistant.components.zwave.binary_sensor import get_device from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.device_registry import ( async_get_registry as get_dev_reg) from homeassistant.setup import setup_component from tests.common import ( async_fire_time_changed, get_test_home_assistant, mock_coro, mock_registry) from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue async def test_valid_device_config(hass, mock_openzwave): """Test valid device config.""" device_config = { 'light.kitchen': { 'ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert result async def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = { 'light.kitchen': { 'some_ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert not result def test_config_access_error(): """Test threading error accessing config values.""" node = MagicMock() def side_effect(): raise RuntimeError node.values.values.side_effect = side_effect result = zwave.get_config_value(node, 1) assert result is None async def test_network_options(hass, mock_openzwave): """Test network options.""" result = await async_setup_component(hass, 'zwave', { 'zwave': { 'usb_path': 'mock_usb_path', 'config_path': 'mock_config_path', }}) await hass.async_block_till_done() assert result network = hass.data[zwave.DATA_NETWORK] assert network.options.device == 'mock_usb_path' assert network.options.config_path == 'mock_config_path' async def test_network_key_validation(hass, mock_openzwave): """Test network key validation.""" test_values = [ ('0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,' '0x0E,0x0F,0x10'), ] for value in test_values: result = zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) assert result['zwave']['network_key'] == value async def test_erronous_network_key_fails_validation(hass, mock_openzwave): """Test failing erronous network key validation.""" test_values = [ ('0x 01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0X01,0X02,0X03,0X04,0X05,0X06,0X07,0X08,0X09,0X0A,0X0B,0X0C,0X0D,' '0X0E,0X0F,0X10'), 'invalid', '1234567', 1234567 ] for value in test_values: with pytest.raises(vol.Invalid): zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) async def test_auto_heal_midnight(hass, mock_openzwave): """Test network auto-heal at midnight.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': True, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert network.heal.called assert len(network.heal.mock_calls) == 1 async def test_auto_heal_disabled(hass, mock_openzwave): """Test network auto-heal disabled.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': False, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert not network.heal.called async def test_setup_platform(hass, mock_openzwave): """Test invalid device config.""" mock_device = MagicMock() hass.data[DATA_NETWORK] = MagicMock() hass.data[zwave.DATA_DEVICES] = {456: mock_device} async_add_entities = MagicMock() result = await zwave.async_setup_platform( hass, None, async_add_entities, None) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 123}) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 456}) assert result assert async_add_entities.called assert len(async_add_entities.mock_calls) == 1 assert async_add_entities.mock_calls[0][1][0] == [mock_device] async def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): """Test device entity base class.""" node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.value_added() device.update_properties() await hass.async_block_till_done() assert not device.should_poll assert device.unique_id == "10-11" assert device.name == 'Mock Node Sensor' assert device.device_state_attributes[zwave.ATTR_POWER] == 50.123 async def test_node_removed(hass, mock_openzwave): """Test node removed in base class.""" # Create a mock node & node entity node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.entity_id = 'zwave.mock_node' device.value_added() device.update_properties() await hass.async_block_till_done() # Save it to the entity registry registry = mock_registry(hass) registry.async_get_or_create('zwave', 'zwave', device.unique_id) device.entity_id = registry.async_get_entity_id( 'zwave', 'zwave', device.unique_id) # Create dummy entity registry entries for other integrations hue_entity = registry.async_get_or_create('light', 'hue', 1234) zha_entity = registry.async_get_or_create('sensor', 'zha', 5678) # Verify our Z-Wave entity is registered assert registry.async_is_registered(device.entity_id) # Remove it entity_id = device.entity_id await device.node_removed() # Verify registry entry for our Z-Wave node is gone assert not registry.async_is_registered(entity_id) # Verify registry entries for our other entities remain assert registry.async_is_registered(hue_entity.entity_id) assert registry.async_is_registered(zha_entity.entity_id) async def test_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node').state == 'unknown' async def test_unparsed_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode( node_id=14, manufacturer_name=None, name=None, is_ready=False) sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert len(sleeps) == const.NODE_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1:] == \ (14, const.NODE_READY_WAIT_SECS) assert hass.states.get('zwave.unknown_node_14').state == 'unknown' async def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': { 'device_config': { 'zwave.mock_node': { 'ignored': True, }}}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None async def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' async def test_value_entities(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = {} def mock_connect(receiver, signal, *args, **kwargs): mock_receivers[signal] = receiver with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert mock_receivers hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_ALL_NODES_QUERIED]) node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) zwave_network.nodes = {node.node_id: node} value = MockValue( data=False, node=node, index=12, instance=1, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values = {'primary': value, value.value_id: value} value2 = MockValue( data=False, node=node, index=12, instance=2, label="Mock Value B", command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values[value2.value_id] = value2 hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_NODE_ADDED], node) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value2) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' assert hass.states.get( 'binary_sensor.mock_node_mock_value_b').state == 'off' ent_reg = await async_get_registry(hass) dev_reg = await get_dev_reg(hass) entry = ent_reg.async_get('zwave.mock_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) node_dev_id = entry.device_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) assert entry.name is None assert entry.device_id == node_dev_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value2.object_id) assert entry.name is None assert entry.device_id != node_dev_id device_id_b = entry.device_id device = dev_reg.async_get(node_dev_id) assert device is not None assert device.name == node.name old_device = device device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming without updating await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_NAME: "Demo Node", }) await hass.async_block_till_done() assert node.name == "Demo Node" entry = ent_reg.async_get('zwave.mock_node') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Node", }) await hass.async_block_till_done() assert node.name == "New Node" entry = ent_reg.async_get('zwave.new_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) entry = ent_reg.async_get('binary_sensor.new_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) await hass.services.async_call('zwave', 'rename_value', { const.ATTR_NODE_ID: node.node_id, const.ATTR_VALUE_ID: value.object_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Label", }) await hass.async_block_till_done() entry = ent_reg.async_get('binary_sensor.new_node_new_label') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) async def test_value_discovery_existing_entity(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_THERMOSTAT) setpoint = MockValue( data=22.0, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, setpoint) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] is None def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): temperature = MockValue( data=23.5, node=node, index=1, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, temperature) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] == 23.5 async def test_power_schemes(hass, mock_openzwave): """Test power attribute.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SWITCH_BINARY) switch = MockValue( data=True, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SWITCH_BINARY, genre=const.GENRE_USER, type=const.TYPE_BOOL) hass.async_add_job(mock_receivers[0], node, switch) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').state == 'on' assert 'power_consumption' not in hass.states.get( 'switch.mock_node_mock_value').attributes def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): power = MockValue( data=23.5, node=node, index=const.INDEX_SENSOR_MULTILEVEL_POWER, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL) hass.async_add_job(mock_receivers[0], node, power) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').attributes[ 'power_consumption'] == 23.5 async def test_network_ready(hass, mock_openzwave): """Test Node network ready event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete_some_dead(hass, mock_openzwave): """Test Node network complete some dead event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE_SOME_DEAD, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 class TestZWaveDeviceEntityValues(unittest.TestCase): """Tests for the ZWaveDeviceEntityValues helper.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() self.registry = mock_registry(self.hass) setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.node = MockNode() self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: ['mock_primary_class'], }, 'secondary': { const.DISC_COMMAND_CLASS: ['mock_secondary_class'], }, 'optional': { const.DISC_COMMAND_CLASS: ['mock_optional_class'], const.DISC_OPTIONAL: True, }}} self.primary = MockValue( command_class='mock_primary_class', node=self.node, value_id=1000) self.secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.duplicate_secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.optional = MockValue( command_class='mock_optional_class', node=self.node) self.no_match_value = MockValue( command_class='mock_bad_class', node=self.node) self.entity_id = 'mock_component.mock_node_mock_value' self.zwave_config = {'zwave': {}} self.device_config = {self.entity_id: {}} def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) assert values.primary is self.primary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) self.hass.block_till_done() assert values.secondary is self.secondary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config discovery.async_load_platform.reset_mock() values.check_value(self.optional) values.check_value(self.duplicate_secondary) values.check_value(self.no_match_value) self.hass.block_till_done() assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called assert len(values._entity.value_added.mock_calls) == 1 assert values._entity.value_changed.called assert len(values._entity.value_changed.mock_calls) == 1 @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, self.optional.value_id: self.optional, self.no_match_value.value_id: self.no_match_value, } values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert values.primary is self.primary assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config assert not self.primary.enable_poll.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_node_schema_mismatch(self, discovery, import_module): """Test node schema mismatch.""" self.node.generic = 'no_match' self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.mock_schema[const.DISC_GENERIC_DEVICE_CLASS] = ['generic_match'] values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.manufacturer_id = '010f' self.node.product_type = '0b00' self.primary.command_class = const.COMMAND_CLASS_SENSOR_ALARM self.entity_id = 'binary_sensor.mock_node_mock_value' self.device_config = {self.entity_id: {}} self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} with patch.object(zwave, 'async_dispatcher_send') as \ mock_dispatch_send: values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert mock_dispatch_send.called assert len(mock_dispatch_send.mock_calls) == 1 args = mock_dispatch_send.mock_calls[0][1] assert args[1] == 'zwave_new_binary_sensor' @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_ignore(self, discovery, import_module): """Test ignore workaround.""" self.node.manufacturer_id = '010f' self.node.product_type = '0301' self.primary.command_class = const.COMMAND_CLASS_SWITCH_BINARY self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore(self, discovery, import_module): """Test ignore config.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_IGNORED: True }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore_with_registry(self, discovery, import_module): """Test ignore config. The case when the device is in entity registry. """ self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {'mock_component.registry_id': { zwave.CONF_IGNORED: True }} with patch.object(self.registry, 'async_schedule_save'): self.registry.async_get_or_create( 'mock_component', zwave.DOMAIN, '567-1000', suggested_object_id='registry_id') zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_platform_ignore(self, discovery, import_module): """Test platform ignore device.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } platform = MagicMock() import_module.return_value = platform platform.get_device.return_value = None zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_config_polling_intensity(self, discovery, import_module): """Test polling intensity.""" mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_POLLING_INTENSITY: 123, }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert discovery.async_load_platform.called assert self.primary.enable_poll.called assert len(self.primary.enable_poll.mock_calls) == 1 assert self.primary.enable_poll.mock_calls[0][1][0] == 123 class TestZwave(unittest.TestCase): """Test zwave init.""" def test_device_config_glob_is_ordered(self): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): """Tests for zwave services.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() # Initialize zwave setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.zwave_network = self.hass.data[DATA_NETWORK] self.zwave_network.state = MockNetwork.STATE_READY self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.block_till_done() def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() self.hass.stop() def test_add_node(self): """Test zwave add_node service.""" self.hass.services.call('zwave', 'add_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller .add_node.mock_calls) == 1 assert len(self.zwave_network.controller .add_node.mock_calls[0][1]) == 0 def test_add_node_secure(self): """Test zwave add_node_secure service.""" self.hass.services.call('zwave', 'add_node_secure', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller.add_node.mock_calls) == 1 assert (self.zwave_network.controller .add_node.mock_calls[0][1][0] is True) def test_remove_node(self): """Test zwave remove_node service.""" self.hass.services.call('zwave', 'remove_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.remove_node.called assert len(self.zwave_network.controller.remove_node.mock_calls) == 1 def test_cancel_command(self): """Test zwave cancel_command service.""" self.hass.services.call('zwave', 'cancel_command', {}) self.hass.block_till_done() assert self.zwave_network.controller.cancel_command.called assert len(self.zwave_network.controller .cancel_command.mock_calls) == 1 def test_heal_network(self): """Test zwave heal_network service.""" self.hass.services.call('zwave', 'heal_network', {}) self.hass.block_till_done() assert self.zwave_network.heal.called assert len(self.zwave_network.heal.mock_calls) == 1 def test_soft_reset(self): """Test zwave soft_reset service.""" self.hass.services.call('zwave', 'soft_reset', {}) self.hass.block_till_done() assert self.zwave_network.controller.soft_reset.called assert len(self.zwave_network.controller.soft_reset.mock_calls) == 1 def test_test_network(self): """Test zwave test_network service.""" self.hass.services.call('zwave', 'test_network', {}) self.hass.block_till_done() assert self.zwave_network.test.called assert len(self.zwave_network.test.mock_calls) == 1 def test_stop_network(self): """Test zwave stop_network service.""" with patch.object(self.hass.bus, 'fire') as mock_fire: self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() assert self.zwave_network.stop.called assert len(self.zwave_network.stop.mock_calls) == 1 assert mock_fire.called assert len(mock_fire.mock_calls) == 1 assert mock_fire.mock_calls[0][1][0] == const.EVENT_NETWORK_STOP def test_rename_node(self): """Test zwave rename_node service.""" self.zwave_network.nodes = {11: MagicMock()} self.hass.services.call('zwave', 'rename_node', { const.ATTR_NODE_ID: 11, const.ATTR_NAME: 'test_name', }) self.hass.block_till_done() assert self.zwave_network.nodes[11].name == 'test_name' def test_rename_value(self): """Test zwave rename_value service.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, label="Old Label") node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.label == "Old Label" self.hass.services.call('zwave', 'rename_value', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_NAME: "New Label", }) self.hass.block_till_done() assert value.label == "New Label" def test_set_poll_intensity_enable(self): """Test zwave set_poll_intensity service, successful set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 2 assert enable_poll.mock_calls[0][1][0] == 4 def test_set_poll_intensity_enable_failed(self): """Test zwave set_poll_intensity service, failed set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) value.enable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 1 def test_set_poll_intensity_disable(self): """Test zwave set_poll_intensity service, successful disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 2 def test_set_poll_intensity_disable_failed(self): """Test zwave set_poll_intensity service, failed disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) value.disable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 1 def test_remove_failed_node(self): """Test zwave remove_failed_node service.""" self.hass.services.call('zwave', 'remove_failed_node', { const.ATTR_NODE_ID: 12, }) self.hass.block_till_done() remove_failed_node = self.zwave_network.controller.remove_failed_node assert remove_failed_node.called assert len(remove_failed_node.mock_calls) == 1 assert remove_failed_node.mock_calls[0][1][0] == 12 def test_replace_failed_node(self): """Test zwave replace_failed_node service.""" self.hass.services.call('zwave', 'replace_failed_node', { const.ATTR_NODE_ID: 13, }) self.hass.block_till_done() replace_failed_node = self.zwave_network.controller.replace_failed_node assert replace_failed_node.called assert len(replace_failed_node.mock_calls) == 1 assert replace_failed_node.mock_calls[0][1][0] == 13 def test_set_config_parameter(self): """Test zwave set_config_parameter service.""" value_byte = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BYTE, ) value_list = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['item1', 'item2', 'item3'], ) value_button = MockValue( index=14, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BUTTON, ) value_list_int = MockValue( index=15, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['1', '2', '3'], ) value_bool = MockValue( index=16, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BOOL, ) node = MockNode(node_id=14) node.get_values.return_value = { 12: value_byte, 13: value_list, 14: value_button, 15: value_list_int, 16: value_bool } self.zwave_network.nodes = {14: node} # Byte self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 12, const.ATTR_CONFIG_VALUE: 7, }) self.hass.block_till_done() assert value_byte.data == 7 # List self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, const.ATTR_CONFIG_VALUE: 'item3', }) self.hass.block_till_done() assert value_list.data == 'item3' # Button self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 14, const.ATTR_CONFIG_VALUE: True, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called assert self.zwave_network.manager.releaseButton.called # List of Ints self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 15, const.ATTR_CONFIG_VALUE: 3, }) self.hass.block_till_done() assert value_list_int.data == '3' # Boolean Truthy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'True', }) self.hass.block_till_done() assert value_bool.data == 1 # Boolean Falsy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'False', }) self.hass.block_till_done() assert value_bool.data == 0 # Different Parameter Size self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 19, const.ATTR_CONFIG_VALUE: 0x01020304, const.ATTR_CONFIG_SIZE: 4 }) self.hass.block_till_done() assert node.set_config_param.called assert len(node.set_config_param.mock_calls) == 1 assert node.set_config_param.mock_calls[0][1][0] == 19 assert node.set_config_param.mock_calls[0][1][1] == 0x01020304 assert node.set_config_param.mock_calls[0][1][2] == 4 node.set_config_param.reset_mock() def test_print_config_parameter(self): """Test zwave print_config_parameter service.""" value1 = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, data=1234, ) value2 = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, data=2345, ) node = MockNode(node_id=14) node.values = {12: value1, 13: value2} self.zwave_network.nodes = {14: node} with patch.object(zwave, '_LOGGER') as mock_logger: self.hass.services.call('zwave', 'print_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, }) self.hass.block_till_done() assert mock_logger.info.called assert len(mock_logger.info.mock_calls) == 1 assert mock_logger.info.mock_calls[0][1][1] == 13 assert mock_logger.info.mock_calls[0][1][2] == 14 assert mock_logger.info.mock_calls[0][1][3] == 2345 def test_print_node(self): """Test zwave print_node_parameter service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} with self.assertLogs(level='DEBUG') as mock_logger: self.hass.services.call('zwave', 'print_node', { const.ATTR_NODE_ID: 14 }) self.hass.block_till_done() assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 15, }) self.hass.block_till_done() assert value.data == 15 node.can_wake_up_value = False self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 20, }) self.hass.block_till_done() assert value.data == 15 def test_reset_node_meters(self): """Test zwave reset_node_meters service.""" value = MockValue( instance=1, index=8, data=99.5, command_class=const.COMMAND_CLASS_METER, ) reset_value = MockValue( instance=1, index=33, command_class=const.COMMAND_CLASS_METER, ) node = MockNode(node_id=14) node.values = {8: value, 33: reset_value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, const.ATTR_INSTANCE: 2, }) self.hass.block_till_done() assert not self.zwave_network.manager.pressButton.called assert not self.zwave_network.manager.releaseButton.called self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called value_id, = self.zwave_network.manager.pressButton.mock_calls.pop(0)[1] assert value_id == reset_value.value_id assert self.zwave_network.manager.releaseButton.called value_id, = ( self.zwave_network.manager.releaseButton.mock_calls.pop(0)[1]) assert value_id == reset_value.value_id def test_add_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'add', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.add_association.called assert len(group.add_association.mock_calls) == 1 assert group.add_association.mock_calls[0][1][0] == 24 assert group.add_association.mock_calls[0][1][1] == 5 def test_remove_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'remove', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.remove_association.called assert len(group.remove_association.mock_calls) == 1 assert group.remove_association.mock_calls[0][1][0] == 24 assert group.remove_association.mock_calls[0][1][1] == 5 def test_refresh_entity(self): """Test zwave refresh_entity service.""" node = MockNode() value = MockValue(data=False, node=node, command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50, node=node, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = get_device(node=node, values=values, node_config={}) device.hass = self.hass device.entity_id = 'binary_sensor.mock_entity_id' self.hass.add_job(device.async_added_to_hass()) self.hass.block_till_done() self.hass.services.call('zwave', 'refresh_entity', { ATTR_ENTITY_ID: 'binary_sensor.mock_entity_id', }) self.hass.block_till_done() assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 assert sorted([node.refresh_value.mock_calls[0][1][0], node.refresh_value.mock_calls[1][1][0]]) == \ sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert node.refresh_info.called assert len(node.refresh_info.mock_calls) == 1 def test_set_node_value(self): """Test zwave set_node_value service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=4 ) node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR]) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12, const.ATTR_CONFIG_VALUE: 2, }) self.hass.block_till_done() assert self.zwave_network.nodes[14].values[12].data == 2 def test_refresh_node_value(self): """Test zwave refresh_node_value service.""" node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR], network=self.zwave_network) value = MockValue( node=node, index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=2 ) value.refresh = MagicMock() node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12 }) self.hass.block_till_done() assert value.refresh.called def test_heal_node(self): """Test zwave heal_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'heal_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.heal.called assert len(node.heal.mock_calls) == 1 def test_test_node(self): """Test the zwave test_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'test_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.test.called assert len(node.test.mock_calls) == 1
jabesq/home-assistant
tests/components/zwave/test_init.py
homeassistant/components/kiwi/lock.py
"""Support for showing the date and the time.""" from datetime import timedelta import logging import voluptuous as vol from homeassistant.core import callback from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_DISPLAY_OPTIONS from homeassistant.helpers.entity import Entity import homeassistant.helpers.config_validation as cv import homeassistant.util.dt as dt_util from homeassistant.helpers.event import async_track_point_in_utc_time _LOGGER = logging.getLogger(__name__) TIME_STR_FORMAT = '%H:%M' OPTION_TYPES = { 'time': 'Time', 'date': 'Date', 'date_time': 'Date & Time', 'date_time_iso': 'Date & Time ISO', 'time_date': 'Time & Date', 'beat': 'Internet Time', 'time_utc': 'Time (UTC)', } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_DISPLAY_OPTIONS, default=['time']): vol.All(cv.ensure_list, [vol.In(OPTION_TYPES)]), }) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Time and Date sensor.""" if hass.config.time_zone is None: _LOGGER.error("Timezone is not set in Home Assistant configuration") return False devices = [] for variable in config[CONF_DISPLAY_OPTIONS]: device = TimeDateSensor(hass, variable) async_track_point_in_utc_time( hass, device.point_in_time_listener, device.get_next_interval()) devices.append(device) async_add_entities(devices, True) class TimeDateSensor(Entity): """Implementation of a Time and Date sensor.""" def __init__(self, hass, option_type): """Initialize the sensor.""" self._name = OPTION_TYPES[option_type] self.type = option_type self._state = None self.hass = hass self._update_internal_state(dt_util.utcnow()) @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._state @property def icon(self): """Icon to use in the frontend, if any.""" if 'date' in self.type and 'time' in self.type: return 'mdi:calendar-clock' if 'date' in self.type: return 'mdi:calendar' return 'mdi:clock' def get_next_interval(self, now=None): """Compute next time an update should occur.""" if now is None: now = dt_util.utcnow() if self.type == 'date': now = dt_util.start_of_local_day(dt_util.as_local(now)) return now + timedelta(seconds=86400) if self.type == 'beat': interval = 86.4 else: interval = 60 timestamp = int(dt_util.as_timestamp(now)) delta = interval - (timestamp % interval) return now + timedelta(seconds=delta) def _update_internal_state(self, time_date): time = dt_util.as_local(time_date).strftime(TIME_STR_FORMAT) time_utc = time_date.strftime(TIME_STR_FORMAT) date = dt_util.as_local(time_date).date().isoformat() # Calculate Swatch Internet Time. time_bmt = time_date + timedelta(hours=1) delta = timedelta( hours=time_bmt.hour, minutes=time_bmt.minute, seconds=time_bmt.second, microseconds=time_bmt.microsecond) beat = int((delta.seconds + delta.microseconds / 1000000.0) / 86.4) if self.type == 'time': self._state = time elif self.type == 'date': self._state = date elif self.type == 'date_time': self._state = '{}, {}'.format(date, time) elif self.type == 'time_date': self._state = '{}, {}'.format(time, date) elif self.type == 'time_utc': self._state = time_utc elif self.type == 'beat': self._state = '@{0:03d}'.format(beat) elif self.type == 'date_time_iso': self._state = dt_util.parse_datetime( '{} {}'.format(date, time)).isoformat() @callback def point_in_time_listener(self, time_date): """Get the latest data and update state.""" self._update_internal_state(time_date) self.async_schedule_update_ha_state() async_track_point_in_utc_time( self.hass, self.point_in_time_listener, self.get_next_interval())
"""Tests for the Z-Wave init.""" import asyncio from collections import OrderedDict from datetime import datetime import unittest from unittest.mock import MagicMock, patch import pytest from pytz import utc import voluptuous as vol from homeassistant.bootstrap import async_setup_component from homeassistant.components import zwave from homeassistant.components.zwave import ( CONF_DEVICE_CONFIG_GLOB, CONFIG_SCHEMA, DATA_NETWORK, const) from homeassistant.components.zwave.binary_sensor import get_device from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.device_registry import ( async_get_registry as get_dev_reg) from homeassistant.setup import setup_component from tests.common import ( async_fire_time_changed, get_test_home_assistant, mock_coro, mock_registry) from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue async def test_valid_device_config(hass, mock_openzwave): """Test valid device config.""" device_config = { 'light.kitchen': { 'ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert result async def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = { 'light.kitchen': { 'some_ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert not result def test_config_access_error(): """Test threading error accessing config values.""" node = MagicMock() def side_effect(): raise RuntimeError node.values.values.side_effect = side_effect result = zwave.get_config_value(node, 1) assert result is None async def test_network_options(hass, mock_openzwave): """Test network options.""" result = await async_setup_component(hass, 'zwave', { 'zwave': { 'usb_path': 'mock_usb_path', 'config_path': 'mock_config_path', }}) await hass.async_block_till_done() assert result network = hass.data[zwave.DATA_NETWORK] assert network.options.device == 'mock_usb_path' assert network.options.config_path == 'mock_config_path' async def test_network_key_validation(hass, mock_openzwave): """Test network key validation.""" test_values = [ ('0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,' '0x0E,0x0F,0x10'), ] for value in test_values: result = zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) assert result['zwave']['network_key'] == value async def test_erronous_network_key_fails_validation(hass, mock_openzwave): """Test failing erronous network key validation.""" test_values = [ ('0x 01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0X01,0X02,0X03,0X04,0X05,0X06,0X07,0X08,0X09,0X0A,0X0B,0X0C,0X0D,' '0X0E,0X0F,0X10'), 'invalid', '1234567', 1234567 ] for value in test_values: with pytest.raises(vol.Invalid): zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) async def test_auto_heal_midnight(hass, mock_openzwave): """Test network auto-heal at midnight.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': True, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert network.heal.called assert len(network.heal.mock_calls) == 1 async def test_auto_heal_disabled(hass, mock_openzwave): """Test network auto-heal disabled.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': False, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert not network.heal.called async def test_setup_platform(hass, mock_openzwave): """Test invalid device config.""" mock_device = MagicMock() hass.data[DATA_NETWORK] = MagicMock() hass.data[zwave.DATA_DEVICES] = {456: mock_device} async_add_entities = MagicMock() result = await zwave.async_setup_platform( hass, None, async_add_entities, None) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 123}) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 456}) assert result assert async_add_entities.called assert len(async_add_entities.mock_calls) == 1 assert async_add_entities.mock_calls[0][1][0] == [mock_device] async def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): """Test device entity base class.""" node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.value_added() device.update_properties() await hass.async_block_till_done() assert not device.should_poll assert device.unique_id == "10-11" assert device.name == 'Mock Node Sensor' assert device.device_state_attributes[zwave.ATTR_POWER] == 50.123 async def test_node_removed(hass, mock_openzwave): """Test node removed in base class.""" # Create a mock node & node entity node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.entity_id = 'zwave.mock_node' device.value_added() device.update_properties() await hass.async_block_till_done() # Save it to the entity registry registry = mock_registry(hass) registry.async_get_or_create('zwave', 'zwave', device.unique_id) device.entity_id = registry.async_get_entity_id( 'zwave', 'zwave', device.unique_id) # Create dummy entity registry entries for other integrations hue_entity = registry.async_get_or_create('light', 'hue', 1234) zha_entity = registry.async_get_or_create('sensor', 'zha', 5678) # Verify our Z-Wave entity is registered assert registry.async_is_registered(device.entity_id) # Remove it entity_id = device.entity_id await device.node_removed() # Verify registry entry for our Z-Wave node is gone assert not registry.async_is_registered(entity_id) # Verify registry entries for our other entities remain assert registry.async_is_registered(hue_entity.entity_id) assert registry.async_is_registered(zha_entity.entity_id) async def test_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node').state == 'unknown' async def test_unparsed_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode( node_id=14, manufacturer_name=None, name=None, is_ready=False) sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert len(sleeps) == const.NODE_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1:] == \ (14, const.NODE_READY_WAIT_SECS) assert hass.states.get('zwave.unknown_node_14').state == 'unknown' async def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': { 'device_config': { 'zwave.mock_node': { 'ignored': True, }}}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None async def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' async def test_value_entities(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = {} def mock_connect(receiver, signal, *args, **kwargs): mock_receivers[signal] = receiver with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert mock_receivers hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_ALL_NODES_QUERIED]) node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) zwave_network.nodes = {node.node_id: node} value = MockValue( data=False, node=node, index=12, instance=1, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values = {'primary': value, value.value_id: value} value2 = MockValue( data=False, node=node, index=12, instance=2, label="Mock Value B", command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values[value2.value_id] = value2 hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_NODE_ADDED], node) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value2) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' assert hass.states.get( 'binary_sensor.mock_node_mock_value_b').state == 'off' ent_reg = await async_get_registry(hass) dev_reg = await get_dev_reg(hass) entry = ent_reg.async_get('zwave.mock_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) node_dev_id = entry.device_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) assert entry.name is None assert entry.device_id == node_dev_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value2.object_id) assert entry.name is None assert entry.device_id != node_dev_id device_id_b = entry.device_id device = dev_reg.async_get(node_dev_id) assert device is not None assert device.name == node.name old_device = device device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming without updating await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_NAME: "Demo Node", }) await hass.async_block_till_done() assert node.name == "Demo Node" entry = ent_reg.async_get('zwave.mock_node') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Node", }) await hass.async_block_till_done() assert node.name == "New Node" entry = ent_reg.async_get('zwave.new_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) entry = ent_reg.async_get('binary_sensor.new_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) await hass.services.async_call('zwave', 'rename_value', { const.ATTR_NODE_ID: node.node_id, const.ATTR_VALUE_ID: value.object_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Label", }) await hass.async_block_till_done() entry = ent_reg.async_get('binary_sensor.new_node_new_label') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) async def test_value_discovery_existing_entity(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_THERMOSTAT) setpoint = MockValue( data=22.0, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, setpoint) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] is None def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): temperature = MockValue( data=23.5, node=node, index=1, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, temperature) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] == 23.5 async def test_power_schemes(hass, mock_openzwave): """Test power attribute.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SWITCH_BINARY) switch = MockValue( data=True, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SWITCH_BINARY, genre=const.GENRE_USER, type=const.TYPE_BOOL) hass.async_add_job(mock_receivers[0], node, switch) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').state == 'on' assert 'power_consumption' not in hass.states.get( 'switch.mock_node_mock_value').attributes def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): power = MockValue( data=23.5, node=node, index=const.INDEX_SENSOR_MULTILEVEL_POWER, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL) hass.async_add_job(mock_receivers[0], node, power) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').attributes[ 'power_consumption'] == 23.5 async def test_network_ready(hass, mock_openzwave): """Test Node network ready event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete_some_dead(hass, mock_openzwave): """Test Node network complete some dead event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE_SOME_DEAD, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 class TestZWaveDeviceEntityValues(unittest.TestCase): """Tests for the ZWaveDeviceEntityValues helper.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() self.registry = mock_registry(self.hass) setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.node = MockNode() self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: ['mock_primary_class'], }, 'secondary': { const.DISC_COMMAND_CLASS: ['mock_secondary_class'], }, 'optional': { const.DISC_COMMAND_CLASS: ['mock_optional_class'], const.DISC_OPTIONAL: True, }}} self.primary = MockValue( command_class='mock_primary_class', node=self.node, value_id=1000) self.secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.duplicate_secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.optional = MockValue( command_class='mock_optional_class', node=self.node) self.no_match_value = MockValue( command_class='mock_bad_class', node=self.node) self.entity_id = 'mock_component.mock_node_mock_value' self.zwave_config = {'zwave': {}} self.device_config = {self.entity_id: {}} def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) assert values.primary is self.primary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) self.hass.block_till_done() assert values.secondary is self.secondary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config discovery.async_load_platform.reset_mock() values.check_value(self.optional) values.check_value(self.duplicate_secondary) values.check_value(self.no_match_value) self.hass.block_till_done() assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called assert len(values._entity.value_added.mock_calls) == 1 assert values._entity.value_changed.called assert len(values._entity.value_changed.mock_calls) == 1 @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, self.optional.value_id: self.optional, self.no_match_value.value_id: self.no_match_value, } values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert values.primary is self.primary assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config assert not self.primary.enable_poll.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_node_schema_mismatch(self, discovery, import_module): """Test node schema mismatch.""" self.node.generic = 'no_match' self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.mock_schema[const.DISC_GENERIC_DEVICE_CLASS] = ['generic_match'] values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.manufacturer_id = '010f' self.node.product_type = '0b00' self.primary.command_class = const.COMMAND_CLASS_SENSOR_ALARM self.entity_id = 'binary_sensor.mock_node_mock_value' self.device_config = {self.entity_id: {}} self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} with patch.object(zwave, 'async_dispatcher_send') as \ mock_dispatch_send: values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert mock_dispatch_send.called assert len(mock_dispatch_send.mock_calls) == 1 args = mock_dispatch_send.mock_calls[0][1] assert args[1] == 'zwave_new_binary_sensor' @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_ignore(self, discovery, import_module): """Test ignore workaround.""" self.node.manufacturer_id = '010f' self.node.product_type = '0301' self.primary.command_class = const.COMMAND_CLASS_SWITCH_BINARY self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore(self, discovery, import_module): """Test ignore config.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_IGNORED: True }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore_with_registry(self, discovery, import_module): """Test ignore config. The case when the device is in entity registry. """ self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {'mock_component.registry_id': { zwave.CONF_IGNORED: True }} with patch.object(self.registry, 'async_schedule_save'): self.registry.async_get_or_create( 'mock_component', zwave.DOMAIN, '567-1000', suggested_object_id='registry_id') zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_platform_ignore(self, discovery, import_module): """Test platform ignore device.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } platform = MagicMock() import_module.return_value = platform platform.get_device.return_value = None zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_config_polling_intensity(self, discovery, import_module): """Test polling intensity.""" mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_POLLING_INTENSITY: 123, }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert discovery.async_load_platform.called assert self.primary.enable_poll.called assert len(self.primary.enable_poll.mock_calls) == 1 assert self.primary.enable_poll.mock_calls[0][1][0] == 123 class TestZwave(unittest.TestCase): """Test zwave init.""" def test_device_config_glob_is_ordered(self): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): """Tests for zwave services.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() # Initialize zwave setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.zwave_network = self.hass.data[DATA_NETWORK] self.zwave_network.state = MockNetwork.STATE_READY self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.block_till_done() def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() self.hass.stop() def test_add_node(self): """Test zwave add_node service.""" self.hass.services.call('zwave', 'add_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller .add_node.mock_calls) == 1 assert len(self.zwave_network.controller .add_node.mock_calls[0][1]) == 0 def test_add_node_secure(self): """Test zwave add_node_secure service.""" self.hass.services.call('zwave', 'add_node_secure', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller.add_node.mock_calls) == 1 assert (self.zwave_network.controller .add_node.mock_calls[0][1][0] is True) def test_remove_node(self): """Test zwave remove_node service.""" self.hass.services.call('zwave', 'remove_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.remove_node.called assert len(self.zwave_network.controller.remove_node.mock_calls) == 1 def test_cancel_command(self): """Test zwave cancel_command service.""" self.hass.services.call('zwave', 'cancel_command', {}) self.hass.block_till_done() assert self.zwave_network.controller.cancel_command.called assert len(self.zwave_network.controller .cancel_command.mock_calls) == 1 def test_heal_network(self): """Test zwave heal_network service.""" self.hass.services.call('zwave', 'heal_network', {}) self.hass.block_till_done() assert self.zwave_network.heal.called assert len(self.zwave_network.heal.mock_calls) == 1 def test_soft_reset(self): """Test zwave soft_reset service.""" self.hass.services.call('zwave', 'soft_reset', {}) self.hass.block_till_done() assert self.zwave_network.controller.soft_reset.called assert len(self.zwave_network.controller.soft_reset.mock_calls) == 1 def test_test_network(self): """Test zwave test_network service.""" self.hass.services.call('zwave', 'test_network', {}) self.hass.block_till_done() assert self.zwave_network.test.called assert len(self.zwave_network.test.mock_calls) == 1 def test_stop_network(self): """Test zwave stop_network service.""" with patch.object(self.hass.bus, 'fire') as mock_fire: self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() assert self.zwave_network.stop.called assert len(self.zwave_network.stop.mock_calls) == 1 assert mock_fire.called assert len(mock_fire.mock_calls) == 1 assert mock_fire.mock_calls[0][1][0] == const.EVENT_NETWORK_STOP def test_rename_node(self): """Test zwave rename_node service.""" self.zwave_network.nodes = {11: MagicMock()} self.hass.services.call('zwave', 'rename_node', { const.ATTR_NODE_ID: 11, const.ATTR_NAME: 'test_name', }) self.hass.block_till_done() assert self.zwave_network.nodes[11].name == 'test_name' def test_rename_value(self): """Test zwave rename_value service.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, label="Old Label") node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.label == "Old Label" self.hass.services.call('zwave', 'rename_value', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_NAME: "New Label", }) self.hass.block_till_done() assert value.label == "New Label" def test_set_poll_intensity_enable(self): """Test zwave set_poll_intensity service, successful set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 2 assert enable_poll.mock_calls[0][1][0] == 4 def test_set_poll_intensity_enable_failed(self): """Test zwave set_poll_intensity service, failed set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) value.enable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 1 def test_set_poll_intensity_disable(self): """Test zwave set_poll_intensity service, successful disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 2 def test_set_poll_intensity_disable_failed(self): """Test zwave set_poll_intensity service, failed disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) value.disable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 1 def test_remove_failed_node(self): """Test zwave remove_failed_node service.""" self.hass.services.call('zwave', 'remove_failed_node', { const.ATTR_NODE_ID: 12, }) self.hass.block_till_done() remove_failed_node = self.zwave_network.controller.remove_failed_node assert remove_failed_node.called assert len(remove_failed_node.mock_calls) == 1 assert remove_failed_node.mock_calls[0][1][0] == 12 def test_replace_failed_node(self): """Test zwave replace_failed_node service.""" self.hass.services.call('zwave', 'replace_failed_node', { const.ATTR_NODE_ID: 13, }) self.hass.block_till_done() replace_failed_node = self.zwave_network.controller.replace_failed_node assert replace_failed_node.called assert len(replace_failed_node.mock_calls) == 1 assert replace_failed_node.mock_calls[0][1][0] == 13 def test_set_config_parameter(self): """Test zwave set_config_parameter service.""" value_byte = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BYTE, ) value_list = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['item1', 'item2', 'item3'], ) value_button = MockValue( index=14, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BUTTON, ) value_list_int = MockValue( index=15, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['1', '2', '3'], ) value_bool = MockValue( index=16, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BOOL, ) node = MockNode(node_id=14) node.get_values.return_value = { 12: value_byte, 13: value_list, 14: value_button, 15: value_list_int, 16: value_bool } self.zwave_network.nodes = {14: node} # Byte self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 12, const.ATTR_CONFIG_VALUE: 7, }) self.hass.block_till_done() assert value_byte.data == 7 # List self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, const.ATTR_CONFIG_VALUE: 'item3', }) self.hass.block_till_done() assert value_list.data == 'item3' # Button self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 14, const.ATTR_CONFIG_VALUE: True, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called assert self.zwave_network.manager.releaseButton.called # List of Ints self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 15, const.ATTR_CONFIG_VALUE: 3, }) self.hass.block_till_done() assert value_list_int.data == '3' # Boolean Truthy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'True', }) self.hass.block_till_done() assert value_bool.data == 1 # Boolean Falsy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'False', }) self.hass.block_till_done() assert value_bool.data == 0 # Different Parameter Size self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 19, const.ATTR_CONFIG_VALUE: 0x01020304, const.ATTR_CONFIG_SIZE: 4 }) self.hass.block_till_done() assert node.set_config_param.called assert len(node.set_config_param.mock_calls) == 1 assert node.set_config_param.mock_calls[0][1][0] == 19 assert node.set_config_param.mock_calls[0][1][1] == 0x01020304 assert node.set_config_param.mock_calls[0][1][2] == 4 node.set_config_param.reset_mock() def test_print_config_parameter(self): """Test zwave print_config_parameter service.""" value1 = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, data=1234, ) value2 = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, data=2345, ) node = MockNode(node_id=14) node.values = {12: value1, 13: value2} self.zwave_network.nodes = {14: node} with patch.object(zwave, '_LOGGER') as mock_logger: self.hass.services.call('zwave', 'print_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, }) self.hass.block_till_done() assert mock_logger.info.called assert len(mock_logger.info.mock_calls) == 1 assert mock_logger.info.mock_calls[0][1][1] == 13 assert mock_logger.info.mock_calls[0][1][2] == 14 assert mock_logger.info.mock_calls[0][1][3] == 2345 def test_print_node(self): """Test zwave print_node_parameter service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} with self.assertLogs(level='DEBUG') as mock_logger: self.hass.services.call('zwave', 'print_node', { const.ATTR_NODE_ID: 14 }) self.hass.block_till_done() assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 15, }) self.hass.block_till_done() assert value.data == 15 node.can_wake_up_value = False self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 20, }) self.hass.block_till_done() assert value.data == 15 def test_reset_node_meters(self): """Test zwave reset_node_meters service.""" value = MockValue( instance=1, index=8, data=99.5, command_class=const.COMMAND_CLASS_METER, ) reset_value = MockValue( instance=1, index=33, command_class=const.COMMAND_CLASS_METER, ) node = MockNode(node_id=14) node.values = {8: value, 33: reset_value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, const.ATTR_INSTANCE: 2, }) self.hass.block_till_done() assert not self.zwave_network.manager.pressButton.called assert not self.zwave_network.manager.releaseButton.called self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called value_id, = self.zwave_network.manager.pressButton.mock_calls.pop(0)[1] assert value_id == reset_value.value_id assert self.zwave_network.manager.releaseButton.called value_id, = ( self.zwave_network.manager.releaseButton.mock_calls.pop(0)[1]) assert value_id == reset_value.value_id def test_add_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'add', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.add_association.called assert len(group.add_association.mock_calls) == 1 assert group.add_association.mock_calls[0][1][0] == 24 assert group.add_association.mock_calls[0][1][1] == 5 def test_remove_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'remove', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.remove_association.called assert len(group.remove_association.mock_calls) == 1 assert group.remove_association.mock_calls[0][1][0] == 24 assert group.remove_association.mock_calls[0][1][1] == 5 def test_refresh_entity(self): """Test zwave refresh_entity service.""" node = MockNode() value = MockValue(data=False, node=node, command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50, node=node, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = get_device(node=node, values=values, node_config={}) device.hass = self.hass device.entity_id = 'binary_sensor.mock_entity_id' self.hass.add_job(device.async_added_to_hass()) self.hass.block_till_done() self.hass.services.call('zwave', 'refresh_entity', { ATTR_ENTITY_ID: 'binary_sensor.mock_entity_id', }) self.hass.block_till_done() assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 assert sorted([node.refresh_value.mock_calls[0][1][0], node.refresh_value.mock_calls[1][1][0]]) == \ sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert node.refresh_info.called assert len(node.refresh_info.mock_calls) == 1 def test_set_node_value(self): """Test zwave set_node_value service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=4 ) node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR]) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12, const.ATTR_CONFIG_VALUE: 2, }) self.hass.block_till_done() assert self.zwave_network.nodes[14].values[12].data == 2 def test_refresh_node_value(self): """Test zwave refresh_node_value service.""" node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR], network=self.zwave_network) value = MockValue( node=node, index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=2 ) value.refresh = MagicMock() node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12 }) self.hass.block_till_done() assert value.refresh.called def test_heal_node(self): """Test zwave heal_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'heal_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.heal.called assert len(node.heal.mock_calls) == 1 def test_test_node(self): """Test the zwave test_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'test_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.test.called assert len(node.test.mock_calls) == 1
jabesq/home-assistant
tests/components/zwave/test_init.py
homeassistant/components/time_date/sensor.py
"""Support for statistics for sensor values.""" import logging import statistics from collections import deque import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_NAME, CONF_ENTITY_ID, EVENT_HOMEASSISTANT_START, STATE_UNKNOWN, ATTR_UNIT_OF_MEASUREMENT) from homeassistant.core import callback from homeassistant.helpers.entity import Entity from homeassistant.helpers.event import async_track_state_change from homeassistant.util import dt as dt_util from homeassistant.components.recorder.util import session_scope, execute _LOGGER = logging.getLogger(__name__) ATTR_AVERAGE_CHANGE = 'average_change' ATTR_CHANGE = 'change' ATTR_CHANGE_RATE = 'change_rate' ATTR_COUNT = 'count' ATTR_MAX_AGE = 'max_age' ATTR_MAX_VALUE = 'max_value' ATTR_MEAN = 'mean' ATTR_MEDIAN = 'median' ATTR_MIN_AGE = 'min_age' ATTR_MIN_VALUE = 'min_value' ATTR_SAMPLING_SIZE = 'sampling_size' ATTR_STANDARD_DEVIATION = 'standard_deviation' ATTR_TOTAL = 'total' ATTR_VARIANCE = 'variance' CONF_SAMPLING_SIZE = 'sampling_size' CONF_MAX_AGE = 'max_age' CONF_PRECISION = 'precision' DEFAULT_NAME = 'Stats' DEFAULT_SIZE = 20 DEFAULT_PRECISION = 2 ICON = 'mdi:calculator' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_ENTITY_ID): cv.entity_id, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_SAMPLING_SIZE, default=DEFAULT_SIZE): vol.All(vol.Coerce(int), vol.Range(min=1)), vol.Optional(CONF_MAX_AGE): cv.time_period, vol.Optional(CONF_PRECISION, default=DEFAULT_PRECISION): vol.Coerce(int) }) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Statistics sensor.""" entity_id = config.get(CONF_ENTITY_ID) name = config.get(CONF_NAME) sampling_size = config.get(CONF_SAMPLING_SIZE) max_age = config.get(CONF_MAX_AGE, None) precision = config.get(CONF_PRECISION) async_add_entities([StatisticsSensor(entity_id, name, sampling_size, max_age, precision)], True) return True class StatisticsSensor(Entity): """Representation of a Statistics sensor.""" def __init__(self, entity_id, name, sampling_size, max_age, precision): """Initialize the Statistics sensor.""" self._entity_id = entity_id self.is_binary = self._entity_id.split('.')[0] == 'binary_sensor' if not self.is_binary: self._name = '{} {}'.format(name, ATTR_MEAN) else: self._name = '{} {}'.format(name, ATTR_COUNT) self._sampling_size = sampling_size self._max_age = max_age self._precision = precision self._unit_of_measurement = None self.states = deque(maxlen=self._sampling_size) self.ages = deque(maxlen=self._sampling_size) self.count = 0 self.mean = self.median = self.stdev = self.variance = None self.total = self.min = self.max = None self.min_age = self.max_age = None self.change = self.average_change = self.change_rate = None async def async_added_to_hass(self): """Register callbacks.""" @callback def async_stats_sensor_state_listener(entity, old_state, new_state): """Handle the sensor state changes.""" self._unit_of_measurement = new_state.attributes.get( ATTR_UNIT_OF_MEASUREMENT) self._add_state_to_queue(new_state) self.async_schedule_update_ha_state(True) @callback def async_stats_sensor_startup(event): """Add listener and get recorded state.""" _LOGGER.debug("Startup for %s", self.entity_id) async_track_state_change( self.hass, self._entity_id, async_stats_sensor_state_listener) if 'recorder' in self.hass.config.components: # Only use the database if it's configured self.hass.async_create_task( self._async_initialize_from_database() ) self.hass.bus.async_listen_once( EVENT_HOMEASSISTANT_START, async_stats_sensor_startup) def _add_state_to_queue(self, new_state): """Add the state to the queue.""" if new_state.state == STATE_UNKNOWN: return try: if self.is_binary: self.states.append(new_state.state) else: self.states.append(float(new_state.state)) self.ages.append(new_state.last_updated) except ValueError: _LOGGER.error("%s: parsing error, expected number and received %s", self.entity_id, new_state.state) @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self.mean if not self.is_binary else self.count @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return self._unit_of_measurement if not self.is_binary else None @property def should_poll(self): """No polling needed.""" return False @property def device_state_attributes(self): """Return the state attributes of the sensor.""" if not self.is_binary: return { ATTR_SAMPLING_SIZE: self._sampling_size, ATTR_COUNT: self.count, ATTR_MEAN: self.mean, ATTR_MEDIAN: self.median, ATTR_STANDARD_DEVIATION: self.stdev, ATTR_VARIANCE: self.variance, ATTR_TOTAL: self.total, ATTR_MIN_VALUE: self.min, ATTR_MAX_VALUE: self.max, ATTR_MIN_AGE: self.min_age, ATTR_MAX_AGE: self.max_age, ATTR_CHANGE: self.change, ATTR_AVERAGE_CHANGE: self.average_change, ATTR_CHANGE_RATE: self.change_rate, } @property def icon(self): """Return the icon to use in the frontend, if any.""" return ICON def _purge_old(self): """Remove states which are older than self._max_age.""" now = dt_util.utcnow() _LOGGER.debug("%s: purging records older then %s(%s)", self.entity_id, dt_util.as_local(now - self._max_age), self._max_age) while self.ages and (now - self.ages[0]) > self._max_age: _LOGGER.debug("%s: purging record with datetime %s(%s)", self.entity_id, dt_util.as_local(self.ages[0]), (now - self.ages[0])) self.ages.popleft() self.states.popleft() async def async_update(self): """Get the latest data and updates the states.""" _LOGGER.debug("%s: updating statistics.", self.entity_id) if self._max_age is not None: self._purge_old() self.count = len(self.states) if not self.is_binary: try: # require only one data point self.mean = round(statistics.mean(self.states), self._precision) self.median = round(statistics.median(self.states), self._precision) except statistics.StatisticsError as err: _LOGGER.debug("%s: %s", self.entity_id, err) self.mean = self.median = STATE_UNKNOWN try: # require at least two data points self.stdev = round(statistics.stdev(self.states), self._precision) self.variance = round(statistics.variance(self.states), self._precision) except statistics.StatisticsError as err: _LOGGER.debug("%s: %s", self.entity_id, err) self.stdev = self.variance = STATE_UNKNOWN if self.states: self.total = round(sum(self.states), self._precision) self.min = round(min(self.states), self._precision) self.max = round(max(self.states), self._precision) self.min_age = self.ages[0] self.max_age = self.ages[-1] self.change = self.states[-1] - self.states[0] self.average_change = self.change self.change_rate = 0 if len(self.states) > 1: self.average_change /= len(self.states) - 1 time_diff = (self.max_age - self.min_age).total_seconds() if time_diff > 0: self.change_rate = self.average_change / time_diff self.change = round(self.change, self._precision) self.average_change = round(self.average_change, self._precision) self.change_rate = round(self.change_rate, self._precision) else: self.total = self.min = self.max = STATE_UNKNOWN self.min_age = self.max_age = dt_util.utcnow() self.change = self.average_change = STATE_UNKNOWN self.change_rate = STATE_UNKNOWN async def _async_initialize_from_database(self): """Initialize the list of states from the database. The query will get the list of states in DESCENDING order so that we can limit the result to self._sample_size. Afterwards reverse the list so that we get it in the right order again. If MaxAge is provided then query will restrict to entries younger then current datetime - MaxAge. """ from homeassistant.components.recorder.models import States _LOGGER.debug("%s: initializing values from the database", self.entity_id) with session_scope(hass=self.hass) as session: query = session.query(States)\ .filter(States.entity_id == self._entity_id.lower()) if self._max_age is not None: records_older_then = dt_util.utcnow() - self._max_age _LOGGER.debug("%s: retrieve records not older then %s", self.entity_id, records_older_then) query = query.filter(States.last_updated >= records_older_then) else: _LOGGER.debug("%s: retrieving all records.", self.entity_id) query = query\ .order_by(States.last_updated.desc())\ .limit(self._sampling_size) states = execute(query) for state in reversed(states): self._add_state_to_queue(state) self.async_schedule_update_ha_state(True) _LOGGER.debug("%s: initializing from database completed", self.entity_id)
"""Tests for the Z-Wave init.""" import asyncio from collections import OrderedDict from datetime import datetime import unittest from unittest.mock import MagicMock, patch import pytest from pytz import utc import voluptuous as vol from homeassistant.bootstrap import async_setup_component from homeassistant.components import zwave from homeassistant.components.zwave import ( CONF_DEVICE_CONFIG_GLOB, CONFIG_SCHEMA, DATA_NETWORK, const) from homeassistant.components.zwave.binary_sensor import get_device from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.device_registry import ( async_get_registry as get_dev_reg) from homeassistant.setup import setup_component from tests.common import ( async_fire_time_changed, get_test_home_assistant, mock_coro, mock_registry) from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue async def test_valid_device_config(hass, mock_openzwave): """Test valid device config.""" device_config = { 'light.kitchen': { 'ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert result async def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = { 'light.kitchen': { 'some_ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert not result def test_config_access_error(): """Test threading error accessing config values.""" node = MagicMock() def side_effect(): raise RuntimeError node.values.values.side_effect = side_effect result = zwave.get_config_value(node, 1) assert result is None async def test_network_options(hass, mock_openzwave): """Test network options.""" result = await async_setup_component(hass, 'zwave', { 'zwave': { 'usb_path': 'mock_usb_path', 'config_path': 'mock_config_path', }}) await hass.async_block_till_done() assert result network = hass.data[zwave.DATA_NETWORK] assert network.options.device == 'mock_usb_path' assert network.options.config_path == 'mock_config_path' async def test_network_key_validation(hass, mock_openzwave): """Test network key validation.""" test_values = [ ('0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,' '0x0E,0x0F,0x10'), ] for value in test_values: result = zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) assert result['zwave']['network_key'] == value async def test_erronous_network_key_fails_validation(hass, mock_openzwave): """Test failing erronous network key validation.""" test_values = [ ('0x 01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0X01,0X02,0X03,0X04,0X05,0X06,0X07,0X08,0X09,0X0A,0X0B,0X0C,0X0D,' '0X0E,0X0F,0X10'), 'invalid', '1234567', 1234567 ] for value in test_values: with pytest.raises(vol.Invalid): zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) async def test_auto_heal_midnight(hass, mock_openzwave): """Test network auto-heal at midnight.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': True, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert network.heal.called assert len(network.heal.mock_calls) == 1 async def test_auto_heal_disabled(hass, mock_openzwave): """Test network auto-heal disabled.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': False, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert not network.heal.called async def test_setup_platform(hass, mock_openzwave): """Test invalid device config.""" mock_device = MagicMock() hass.data[DATA_NETWORK] = MagicMock() hass.data[zwave.DATA_DEVICES] = {456: mock_device} async_add_entities = MagicMock() result = await zwave.async_setup_platform( hass, None, async_add_entities, None) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 123}) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 456}) assert result assert async_add_entities.called assert len(async_add_entities.mock_calls) == 1 assert async_add_entities.mock_calls[0][1][0] == [mock_device] async def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): """Test device entity base class.""" node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.value_added() device.update_properties() await hass.async_block_till_done() assert not device.should_poll assert device.unique_id == "10-11" assert device.name == 'Mock Node Sensor' assert device.device_state_attributes[zwave.ATTR_POWER] == 50.123 async def test_node_removed(hass, mock_openzwave): """Test node removed in base class.""" # Create a mock node & node entity node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.entity_id = 'zwave.mock_node' device.value_added() device.update_properties() await hass.async_block_till_done() # Save it to the entity registry registry = mock_registry(hass) registry.async_get_or_create('zwave', 'zwave', device.unique_id) device.entity_id = registry.async_get_entity_id( 'zwave', 'zwave', device.unique_id) # Create dummy entity registry entries for other integrations hue_entity = registry.async_get_or_create('light', 'hue', 1234) zha_entity = registry.async_get_or_create('sensor', 'zha', 5678) # Verify our Z-Wave entity is registered assert registry.async_is_registered(device.entity_id) # Remove it entity_id = device.entity_id await device.node_removed() # Verify registry entry for our Z-Wave node is gone assert not registry.async_is_registered(entity_id) # Verify registry entries for our other entities remain assert registry.async_is_registered(hue_entity.entity_id) assert registry.async_is_registered(zha_entity.entity_id) async def test_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node').state == 'unknown' async def test_unparsed_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode( node_id=14, manufacturer_name=None, name=None, is_ready=False) sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert len(sleeps) == const.NODE_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1:] == \ (14, const.NODE_READY_WAIT_SECS) assert hass.states.get('zwave.unknown_node_14').state == 'unknown' async def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': { 'device_config': { 'zwave.mock_node': { 'ignored': True, }}}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None async def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' async def test_value_entities(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = {} def mock_connect(receiver, signal, *args, **kwargs): mock_receivers[signal] = receiver with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert mock_receivers hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_ALL_NODES_QUERIED]) node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) zwave_network.nodes = {node.node_id: node} value = MockValue( data=False, node=node, index=12, instance=1, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values = {'primary': value, value.value_id: value} value2 = MockValue( data=False, node=node, index=12, instance=2, label="Mock Value B", command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values[value2.value_id] = value2 hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_NODE_ADDED], node) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value2) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' assert hass.states.get( 'binary_sensor.mock_node_mock_value_b').state == 'off' ent_reg = await async_get_registry(hass) dev_reg = await get_dev_reg(hass) entry = ent_reg.async_get('zwave.mock_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) node_dev_id = entry.device_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) assert entry.name is None assert entry.device_id == node_dev_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value2.object_id) assert entry.name is None assert entry.device_id != node_dev_id device_id_b = entry.device_id device = dev_reg.async_get(node_dev_id) assert device is not None assert device.name == node.name old_device = device device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming without updating await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_NAME: "Demo Node", }) await hass.async_block_till_done() assert node.name == "Demo Node" entry = ent_reg.async_get('zwave.mock_node') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Node", }) await hass.async_block_till_done() assert node.name == "New Node" entry = ent_reg.async_get('zwave.new_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) entry = ent_reg.async_get('binary_sensor.new_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) await hass.services.async_call('zwave', 'rename_value', { const.ATTR_NODE_ID: node.node_id, const.ATTR_VALUE_ID: value.object_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Label", }) await hass.async_block_till_done() entry = ent_reg.async_get('binary_sensor.new_node_new_label') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) async def test_value_discovery_existing_entity(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_THERMOSTAT) setpoint = MockValue( data=22.0, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, setpoint) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] is None def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): temperature = MockValue( data=23.5, node=node, index=1, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, temperature) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] == 23.5 async def test_power_schemes(hass, mock_openzwave): """Test power attribute.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SWITCH_BINARY) switch = MockValue( data=True, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SWITCH_BINARY, genre=const.GENRE_USER, type=const.TYPE_BOOL) hass.async_add_job(mock_receivers[0], node, switch) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').state == 'on' assert 'power_consumption' not in hass.states.get( 'switch.mock_node_mock_value').attributes def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): power = MockValue( data=23.5, node=node, index=const.INDEX_SENSOR_MULTILEVEL_POWER, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL) hass.async_add_job(mock_receivers[0], node, power) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').attributes[ 'power_consumption'] == 23.5 async def test_network_ready(hass, mock_openzwave): """Test Node network ready event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete_some_dead(hass, mock_openzwave): """Test Node network complete some dead event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE_SOME_DEAD, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 class TestZWaveDeviceEntityValues(unittest.TestCase): """Tests for the ZWaveDeviceEntityValues helper.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() self.registry = mock_registry(self.hass) setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.node = MockNode() self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: ['mock_primary_class'], }, 'secondary': { const.DISC_COMMAND_CLASS: ['mock_secondary_class'], }, 'optional': { const.DISC_COMMAND_CLASS: ['mock_optional_class'], const.DISC_OPTIONAL: True, }}} self.primary = MockValue( command_class='mock_primary_class', node=self.node, value_id=1000) self.secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.duplicate_secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.optional = MockValue( command_class='mock_optional_class', node=self.node) self.no_match_value = MockValue( command_class='mock_bad_class', node=self.node) self.entity_id = 'mock_component.mock_node_mock_value' self.zwave_config = {'zwave': {}} self.device_config = {self.entity_id: {}} def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) assert values.primary is self.primary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) self.hass.block_till_done() assert values.secondary is self.secondary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config discovery.async_load_platform.reset_mock() values.check_value(self.optional) values.check_value(self.duplicate_secondary) values.check_value(self.no_match_value) self.hass.block_till_done() assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called assert len(values._entity.value_added.mock_calls) == 1 assert values._entity.value_changed.called assert len(values._entity.value_changed.mock_calls) == 1 @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, self.optional.value_id: self.optional, self.no_match_value.value_id: self.no_match_value, } values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert values.primary is self.primary assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config assert not self.primary.enable_poll.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_node_schema_mismatch(self, discovery, import_module): """Test node schema mismatch.""" self.node.generic = 'no_match' self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.mock_schema[const.DISC_GENERIC_DEVICE_CLASS] = ['generic_match'] values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.manufacturer_id = '010f' self.node.product_type = '0b00' self.primary.command_class = const.COMMAND_CLASS_SENSOR_ALARM self.entity_id = 'binary_sensor.mock_node_mock_value' self.device_config = {self.entity_id: {}} self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} with patch.object(zwave, 'async_dispatcher_send') as \ mock_dispatch_send: values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert mock_dispatch_send.called assert len(mock_dispatch_send.mock_calls) == 1 args = mock_dispatch_send.mock_calls[0][1] assert args[1] == 'zwave_new_binary_sensor' @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_ignore(self, discovery, import_module): """Test ignore workaround.""" self.node.manufacturer_id = '010f' self.node.product_type = '0301' self.primary.command_class = const.COMMAND_CLASS_SWITCH_BINARY self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore(self, discovery, import_module): """Test ignore config.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_IGNORED: True }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore_with_registry(self, discovery, import_module): """Test ignore config. The case when the device is in entity registry. """ self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {'mock_component.registry_id': { zwave.CONF_IGNORED: True }} with patch.object(self.registry, 'async_schedule_save'): self.registry.async_get_or_create( 'mock_component', zwave.DOMAIN, '567-1000', suggested_object_id='registry_id') zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_platform_ignore(self, discovery, import_module): """Test platform ignore device.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } platform = MagicMock() import_module.return_value = platform platform.get_device.return_value = None zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_config_polling_intensity(self, discovery, import_module): """Test polling intensity.""" mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_POLLING_INTENSITY: 123, }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert discovery.async_load_platform.called assert self.primary.enable_poll.called assert len(self.primary.enable_poll.mock_calls) == 1 assert self.primary.enable_poll.mock_calls[0][1][0] == 123 class TestZwave(unittest.TestCase): """Test zwave init.""" def test_device_config_glob_is_ordered(self): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): """Tests for zwave services.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() # Initialize zwave setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.zwave_network = self.hass.data[DATA_NETWORK] self.zwave_network.state = MockNetwork.STATE_READY self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.block_till_done() def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() self.hass.stop() def test_add_node(self): """Test zwave add_node service.""" self.hass.services.call('zwave', 'add_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller .add_node.mock_calls) == 1 assert len(self.zwave_network.controller .add_node.mock_calls[0][1]) == 0 def test_add_node_secure(self): """Test zwave add_node_secure service.""" self.hass.services.call('zwave', 'add_node_secure', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller.add_node.mock_calls) == 1 assert (self.zwave_network.controller .add_node.mock_calls[0][1][0] is True) def test_remove_node(self): """Test zwave remove_node service.""" self.hass.services.call('zwave', 'remove_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.remove_node.called assert len(self.zwave_network.controller.remove_node.mock_calls) == 1 def test_cancel_command(self): """Test zwave cancel_command service.""" self.hass.services.call('zwave', 'cancel_command', {}) self.hass.block_till_done() assert self.zwave_network.controller.cancel_command.called assert len(self.zwave_network.controller .cancel_command.mock_calls) == 1 def test_heal_network(self): """Test zwave heal_network service.""" self.hass.services.call('zwave', 'heal_network', {}) self.hass.block_till_done() assert self.zwave_network.heal.called assert len(self.zwave_network.heal.mock_calls) == 1 def test_soft_reset(self): """Test zwave soft_reset service.""" self.hass.services.call('zwave', 'soft_reset', {}) self.hass.block_till_done() assert self.zwave_network.controller.soft_reset.called assert len(self.zwave_network.controller.soft_reset.mock_calls) == 1 def test_test_network(self): """Test zwave test_network service.""" self.hass.services.call('zwave', 'test_network', {}) self.hass.block_till_done() assert self.zwave_network.test.called assert len(self.zwave_network.test.mock_calls) == 1 def test_stop_network(self): """Test zwave stop_network service.""" with patch.object(self.hass.bus, 'fire') as mock_fire: self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() assert self.zwave_network.stop.called assert len(self.zwave_network.stop.mock_calls) == 1 assert mock_fire.called assert len(mock_fire.mock_calls) == 1 assert mock_fire.mock_calls[0][1][0] == const.EVENT_NETWORK_STOP def test_rename_node(self): """Test zwave rename_node service.""" self.zwave_network.nodes = {11: MagicMock()} self.hass.services.call('zwave', 'rename_node', { const.ATTR_NODE_ID: 11, const.ATTR_NAME: 'test_name', }) self.hass.block_till_done() assert self.zwave_network.nodes[11].name == 'test_name' def test_rename_value(self): """Test zwave rename_value service.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, label="Old Label") node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.label == "Old Label" self.hass.services.call('zwave', 'rename_value', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_NAME: "New Label", }) self.hass.block_till_done() assert value.label == "New Label" def test_set_poll_intensity_enable(self): """Test zwave set_poll_intensity service, successful set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 2 assert enable_poll.mock_calls[0][1][0] == 4 def test_set_poll_intensity_enable_failed(self): """Test zwave set_poll_intensity service, failed set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) value.enable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 1 def test_set_poll_intensity_disable(self): """Test zwave set_poll_intensity service, successful disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 2 def test_set_poll_intensity_disable_failed(self): """Test zwave set_poll_intensity service, failed disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) value.disable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 1 def test_remove_failed_node(self): """Test zwave remove_failed_node service.""" self.hass.services.call('zwave', 'remove_failed_node', { const.ATTR_NODE_ID: 12, }) self.hass.block_till_done() remove_failed_node = self.zwave_network.controller.remove_failed_node assert remove_failed_node.called assert len(remove_failed_node.mock_calls) == 1 assert remove_failed_node.mock_calls[0][1][0] == 12 def test_replace_failed_node(self): """Test zwave replace_failed_node service.""" self.hass.services.call('zwave', 'replace_failed_node', { const.ATTR_NODE_ID: 13, }) self.hass.block_till_done() replace_failed_node = self.zwave_network.controller.replace_failed_node assert replace_failed_node.called assert len(replace_failed_node.mock_calls) == 1 assert replace_failed_node.mock_calls[0][1][0] == 13 def test_set_config_parameter(self): """Test zwave set_config_parameter service.""" value_byte = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BYTE, ) value_list = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['item1', 'item2', 'item3'], ) value_button = MockValue( index=14, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BUTTON, ) value_list_int = MockValue( index=15, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['1', '2', '3'], ) value_bool = MockValue( index=16, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BOOL, ) node = MockNode(node_id=14) node.get_values.return_value = { 12: value_byte, 13: value_list, 14: value_button, 15: value_list_int, 16: value_bool } self.zwave_network.nodes = {14: node} # Byte self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 12, const.ATTR_CONFIG_VALUE: 7, }) self.hass.block_till_done() assert value_byte.data == 7 # List self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, const.ATTR_CONFIG_VALUE: 'item3', }) self.hass.block_till_done() assert value_list.data == 'item3' # Button self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 14, const.ATTR_CONFIG_VALUE: True, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called assert self.zwave_network.manager.releaseButton.called # List of Ints self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 15, const.ATTR_CONFIG_VALUE: 3, }) self.hass.block_till_done() assert value_list_int.data == '3' # Boolean Truthy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'True', }) self.hass.block_till_done() assert value_bool.data == 1 # Boolean Falsy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'False', }) self.hass.block_till_done() assert value_bool.data == 0 # Different Parameter Size self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 19, const.ATTR_CONFIG_VALUE: 0x01020304, const.ATTR_CONFIG_SIZE: 4 }) self.hass.block_till_done() assert node.set_config_param.called assert len(node.set_config_param.mock_calls) == 1 assert node.set_config_param.mock_calls[0][1][0] == 19 assert node.set_config_param.mock_calls[0][1][1] == 0x01020304 assert node.set_config_param.mock_calls[0][1][2] == 4 node.set_config_param.reset_mock() def test_print_config_parameter(self): """Test zwave print_config_parameter service.""" value1 = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, data=1234, ) value2 = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, data=2345, ) node = MockNode(node_id=14) node.values = {12: value1, 13: value2} self.zwave_network.nodes = {14: node} with patch.object(zwave, '_LOGGER') as mock_logger: self.hass.services.call('zwave', 'print_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, }) self.hass.block_till_done() assert mock_logger.info.called assert len(mock_logger.info.mock_calls) == 1 assert mock_logger.info.mock_calls[0][1][1] == 13 assert mock_logger.info.mock_calls[0][1][2] == 14 assert mock_logger.info.mock_calls[0][1][3] == 2345 def test_print_node(self): """Test zwave print_node_parameter service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} with self.assertLogs(level='DEBUG') as mock_logger: self.hass.services.call('zwave', 'print_node', { const.ATTR_NODE_ID: 14 }) self.hass.block_till_done() assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 15, }) self.hass.block_till_done() assert value.data == 15 node.can_wake_up_value = False self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 20, }) self.hass.block_till_done() assert value.data == 15 def test_reset_node_meters(self): """Test zwave reset_node_meters service.""" value = MockValue( instance=1, index=8, data=99.5, command_class=const.COMMAND_CLASS_METER, ) reset_value = MockValue( instance=1, index=33, command_class=const.COMMAND_CLASS_METER, ) node = MockNode(node_id=14) node.values = {8: value, 33: reset_value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, const.ATTR_INSTANCE: 2, }) self.hass.block_till_done() assert not self.zwave_network.manager.pressButton.called assert not self.zwave_network.manager.releaseButton.called self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called value_id, = self.zwave_network.manager.pressButton.mock_calls.pop(0)[1] assert value_id == reset_value.value_id assert self.zwave_network.manager.releaseButton.called value_id, = ( self.zwave_network.manager.releaseButton.mock_calls.pop(0)[1]) assert value_id == reset_value.value_id def test_add_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'add', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.add_association.called assert len(group.add_association.mock_calls) == 1 assert group.add_association.mock_calls[0][1][0] == 24 assert group.add_association.mock_calls[0][1][1] == 5 def test_remove_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'remove', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.remove_association.called assert len(group.remove_association.mock_calls) == 1 assert group.remove_association.mock_calls[0][1][0] == 24 assert group.remove_association.mock_calls[0][1][1] == 5 def test_refresh_entity(self): """Test zwave refresh_entity service.""" node = MockNode() value = MockValue(data=False, node=node, command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50, node=node, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = get_device(node=node, values=values, node_config={}) device.hass = self.hass device.entity_id = 'binary_sensor.mock_entity_id' self.hass.add_job(device.async_added_to_hass()) self.hass.block_till_done() self.hass.services.call('zwave', 'refresh_entity', { ATTR_ENTITY_ID: 'binary_sensor.mock_entity_id', }) self.hass.block_till_done() assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 assert sorted([node.refresh_value.mock_calls[0][1][0], node.refresh_value.mock_calls[1][1][0]]) == \ sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert node.refresh_info.called assert len(node.refresh_info.mock_calls) == 1 def test_set_node_value(self): """Test zwave set_node_value service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=4 ) node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR]) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12, const.ATTR_CONFIG_VALUE: 2, }) self.hass.block_till_done() assert self.zwave_network.nodes[14].values[12].data == 2 def test_refresh_node_value(self): """Test zwave refresh_node_value service.""" node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR], network=self.zwave_network) value = MockValue( node=node, index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=2 ) value.refresh = MagicMock() node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12 }) self.hass.block_till_done() assert value.refresh.called def test_heal_node(self): """Test zwave heal_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'heal_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.heal.called assert len(node.heal.mock_calls) == 1 def test_test_node(self): """Test the zwave test_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'test_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.test.called assert len(node.test.mock_calls) == 1
jabesq/home-assistant
tests/components/zwave/test_init.py
homeassistant/components/statistics/sensor.py
"""Binary sensor support for Wireless Sensor Tags.""" import logging import voluptuous as vol from homeassistant.components.binary_sensor import ( PLATFORM_SCHEMA, BinarySensorDevice) from homeassistant.const import CONF_MONITORED_CONDITIONS, STATE_OFF, STATE_ON from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_connect from . import ( DOMAIN as WIRELESSTAG_DOMAIN, SIGNAL_BINARY_EVENT_UPDATE, WirelessTagBaseSensor) _LOGGER = logging.getLogger(__name__) # On means in range, Off means out of range SENSOR_PRESENCE = 'presence' # On means motion detected, Off means clear SENSOR_MOTION = 'motion' # On means open, Off means closed SENSOR_DOOR = 'door' # On means temperature become too cold, Off means normal SENSOR_COLD = 'cold' # On means hot, Off means normal SENSOR_HEAT = 'heat' # On means too dry (humidity), Off means normal SENSOR_DRY = 'dry' # On means too wet (humidity), Off means normal SENSOR_WET = 'wet' # On means light detected, Off means no light SENSOR_LIGHT = 'light' # On means moisture detected (wet), Off means no moisture (dry) SENSOR_MOISTURE = 'moisture' # On means tag battery is low, Off means normal SENSOR_BATTERY = 'battery' # Sensor types: Name, device_class, push notification type representing 'on', # attr to check SENSOR_TYPES = { SENSOR_PRESENCE: 'Presence', SENSOR_MOTION: 'Motion', SENSOR_DOOR: 'Door', SENSOR_COLD: 'Cold', SENSOR_HEAT: 'Heat', SENSOR_DRY: 'Too dry', SENSOR_WET: 'Too wet', SENSOR_LIGHT: 'Light', SENSOR_MOISTURE: 'Leak', SENSOR_BATTERY: 'Low Battery' } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_MONITORED_CONDITIONS, default=[]): vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]), }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the platform for a WirelessTags.""" platform = hass.data.get(WIRELESSTAG_DOMAIN) sensors = [] tags = platform.tags for tag in tags.values(): allowed_sensor_types = tag.supported_binary_events_types for sensor_type in config.get(CONF_MONITORED_CONDITIONS): if sensor_type in allowed_sensor_types: sensors.append(WirelessTagBinarySensor(platform, tag, sensor_type)) add_entities(sensors, True) hass.add_job(platform.install_push_notifications, sensors) class WirelessTagBinarySensor(WirelessTagBaseSensor, BinarySensorDevice): """A binary sensor implementation for WirelessTags.""" def __init__(self, api, tag, sensor_type): """Initialize a binary sensor for a Wireless Sensor Tags.""" super().__init__(api, tag) self._sensor_type = sensor_type self._name = '{0} {1}'.format(self._tag.name, self.event.human_readable_name) async def async_added_to_hass(self): """Register callbacks.""" tag_id = self.tag_id event_type = self.device_class mac = self.tag_manager_mac async_dispatcher_connect( self.hass, SIGNAL_BINARY_EVENT_UPDATE.format(tag_id, event_type, mac), self._on_binary_event_callback) @property def is_on(self): """Return True if the binary sensor is on.""" return self._state == STATE_ON @property def device_class(self): """Return the class of the binary sensor.""" return self._sensor_type @property def event(self): """Binary event of tag.""" return self._tag.event[self._sensor_type] @property def principal_value(self): """Return value of tag. Subclasses need override based on type of sensor. """ return STATE_ON if self.event.is_state_on else STATE_OFF def updated_state_value(self): """Use raw princial value.""" return self.principal_value @callback def _on_binary_event_callback(self, event): """Update state from arrived push notification.""" # state should be 'on' or 'off' self._state = event.data.get('state') self.async_schedule_update_ha_state()
"""Tests for the Z-Wave init.""" import asyncio from collections import OrderedDict from datetime import datetime import unittest from unittest.mock import MagicMock, patch import pytest from pytz import utc import voluptuous as vol from homeassistant.bootstrap import async_setup_component from homeassistant.components import zwave from homeassistant.components.zwave import ( CONF_DEVICE_CONFIG_GLOB, CONFIG_SCHEMA, DATA_NETWORK, const) from homeassistant.components.zwave.binary_sensor import get_device from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.device_registry import ( async_get_registry as get_dev_reg) from homeassistant.setup import setup_component from tests.common import ( async_fire_time_changed, get_test_home_assistant, mock_coro, mock_registry) from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue async def test_valid_device_config(hass, mock_openzwave): """Test valid device config.""" device_config = { 'light.kitchen': { 'ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert result async def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = { 'light.kitchen': { 'some_ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert not result def test_config_access_error(): """Test threading error accessing config values.""" node = MagicMock() def side_effect(): raise RuntimeError node.values.values.side_effect = side_effect result = zwave.get_config_value(node, 1) assert result is None async def test_network_options(hass, mock_openzwave): """Test network options.""" result = await async_setup_component(hass, 'zwave', { 'zwave': { 'usb_path': 'mock_usb_path', 'config_path': 'mock_config_path', }}) await hass.async_block_till_done() assert result network = hass.data[zwave.DATA_NETWORK] assert network.options.device == 'mock_usb_path' assert network.options.config_path == 'mock_config_path' async def test_network_key_validation(hass, mock_openzwave): """Test network key validation.""" test_values = [ ('0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,' '0x0E,0x0F,0x10'), ] for value in test_values: result = zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) assert result['zwave']['network_key'] == value async def test_erronous_network_key_fails_validation(hass, mock_openzwave): """Test failing erronous network key validation.""" test_values = [ ('0x 01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0X01,0X02,0X03,0X04,0X05,0X06,0X07,0X08,0X09,0X0A,0X0B,0X0C,0X0D,' '0X0E,0X0F,0X10'), 'invalid', '1234567', 1234567 ] for value in test_values: with pytest.raises(vol.Invalid): zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) async def test_auto_heal_midnight(hass, mock_openzwave): """Test network auto-heal at midnight.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': True, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert network.heal.called assert len(network.heal.mock_calls) == 1 async def test_auto_heal_disabled(hass, mock_openzwave): """Test network auto-heal disabled.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': False, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert not network.heal.called async def test_setup_platform(hass, mock_openzwave): """Test invalid device config.""" mock_device = MagicMock() hass.data[DATA_NETWORK] = MagicMock() hass.data[zwave.DATA_DEVICES] = {456: mock_device} async_add_entities = MagicMock() result = await zwave.async_setup_platform( hass, None, async_add_entities, None) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 123}) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 456}) assert result assert async_add_entities.called assert len(async_add_entities.mock_calls) == 1 assert async_add_entities.mock_calls[0][1][0] == [mock_device] async def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): """Test device entity base class.""" node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.value_added() device.update_properties() await hass.async_block_till_done() assert not device.should_poll assert device.unique_id == "10-11" assert device.name == 'Mock Node Sensor' assert device.device_state_attributes[zwave.ATTR_POWER] == 50.123 async def test_node_removed(hass, mock_openzwave): """Test node removed in base class.""" # Create a mock node & node entity node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.entity_id = 'zwave.mock_node' device.value_added() device.update_properties() await hass.async_block_till_done() # Save it to the entity registry registry = mock_registry(hass) registry.async_get_or_create('zwave', 'zwave', device.unique_id) device.entity_id = registry.async_get_entity_id( 'zwave', 'zwave', device.unique_id) # Create dummy entity registry entries for other integrations hue_entity = registry.async_get_or_create('light', 'hue', 1234) zha_entity = registry.async_get_or_create('sensor', 'zha', 5678) # Verify our Z-Wave entity is registered assert registry.async_is_registered(device.entity_id) # Remove it entity_id = device.entity_id await device.node_removed() # Verify registry entry for our Z-Wave node is gone assert not registry.async_is_registered(entity_id) # Verify registry entries for our other entities remain assert registry.async_is_registered(hue_entity.entity_id) assert registry.async_is_registered(zha_entity.entity_id) async def test_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node').state == 'unknown' async def test_unparsed_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode( node_id=14, manufacturer_name=None, name=None, is_ready=False) sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert len(sleeps) == const.NODE_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1:] == \ (14, const.NODE_READY_WAIT_SECS) assert hass.states.get('zwave.unknown_node_14').state == 'unknown' async def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': { 'device_config': { 'zwave.mock_node': { 'ignored': True, }}}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None async def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' async def test_value_entities(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = {} def mock_connect(receiver, signal, *args, **kwargs): mock_receivers[signal] = receiver with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert mock_receivers hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_ALL_NODES_QUERIED]) node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) zwave_network.nodes = {node.node_id: node} value = MockValue( data=False, node=node, index=12, instance=1, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values = {'primary': value, value.value_id: value} value2 = MockValue( data=False, node=node, index=12, instance=2, label="Mock Value B", command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values[value2.value_id] = value2 hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_NODE_ADDED], node) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value2) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' assert hass.states.get( 'binary_sensor.mock_node_mock_value_b').state == 'off' ent_reg = await async_get_registry(hass) dev_reg = await get_dev_reg(hass) entry = ent_reg.async_get('zwave.mock_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) node_dev_id = entry.device_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) assert entry.name is None assert entry.device_id == node_dev_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value2.object_id) assert entry.name is None assert entry.device_id != node_dev_id device_id_b = entry.device_id device = dev_reg.async_get(node_dev_id) assert device is not None assert device.name == node.name old_device = device device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming without updating await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_NAME: "Demo Node", }) await hass.async_block_till_done() assert node.name == "Demo Node" entry = ent_reg.async_get('zwave.mock_node') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Node", }) await hass.async_block_till_done() assert node.name == "New Node" entry = ent_reg.async_get('zwave.new_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) entry = ent_reg.async_get('binary_sensor.new_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) await hass.services.async_call('zwave', 'rename_value', { const.ATTR_NODE_ID: node.node_id, const.ATTR_VALUE_ID: value.object_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Label", }) await hass.async_block_till_done() entry = ent_reg.async_get('binary_sensor.new_node_new_label') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) async def test_value_discovery_existing_entity(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_THERMOSTAT) setpoint = MockValue( data=22.0, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, setpoint) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] is None def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): temperature = MockValue( data=23.5, node=node, index=1, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, temperature) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] == 23.5 async def test_power_schemes(hass, mock_openzwave): """Test power attribute.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SWITCH_BINARY) switch = MockValue( data=True, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SWITCH_BINARY, genre=const.GENRE_USER, type=const.TYPE_BOOL) hass.async_add_job(mock_receivers[0], node, switch) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').state == 'on' assert 'power_consumption' not in hass.states.get( 'switch.mock_node_mock_value').attributes def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): power = MockValue( data=23.5, node=node, index=const.INDEX_SENSOR_MULTILEVEL_POWER, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL) hass.async_add_job(mock_receivers[0], node, power) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').attributes[ 'power_consumption'] == 23.5 async def test_network_ready(hass, mock_openzwave): """Test Node network ready event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete_some_dead(hass, mock_openzwave): """Test Node network complete some dead event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE_SOME_DEAD, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 class TestZWaveDeviceEntityValues(unittest.TestCase): """Tests for the ZWaveDeviceEntityValues helper.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() self.registry = mock_registry(self.hass) setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.node = MockNode() self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: ['mock_primary_class'], }, 'secondary': { const.DISC_COMMAND_CLASS: ['mock_secondary_class'], }, 'optional': { const.DISC_COMMAND_CLASS: ['mock_optional_class'], const.DISC_OPTIONAL: True, }}} self.primary = MockValue( command_class='mock_primary_class', node=self.node, value_id=1000) self.secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.duplicate_secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.optional = MockValue( command_class='mock_optional_class', node=self.node) self.no_match_value = MockValue( command_class='mock_bad_class', node=self.node) self.entity_id = 'mock_component.mock_node_mock_value' self.zwave_config = {'zwave': {}} self.device_config = {self.entity_id: {}} def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) assert values.primary is self.primary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) self.hass.block_till_done() assert values.secondary is self.secondary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config discovery.async_load_platform.reset_mock() values.check_value(self.optional) values.check_value(self.duplicate_secondary) values.check_value(self.no_match_value) self.hass.block_till_done() assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called assert len(values._entity.value_added.mock_calls) == 1 assert values._entity.value_changed.called assert len(values._entity.value_changed.mock_calls) == 1 @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, self.optional.value_id: self.optional, self.no_match_value.value_id: self.no_match_value, } values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert values.primary is self.primary assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config assert not self.primary.enable_poll.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_node_schema_mismatch(self, discovery, import_module): """Test node schema mismatch.""" self.node.generic = 'no_match' self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.mock_schema[const.DISC_GENERIC_DEVICE_CLASS] = ['generic_match'] values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.manufacturer_id = '010f' self.node.product_type = '0b00' self.primary.command_class = const.COMMAND_CLASS_SENSOR_ALARM self.entity_id = 'binary_sensor.mock_node_mock_value' self.device_config = {self.entity_id: {}} self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} with patch.object(zwave, 'async_dispatcher_send') as \ mock_dispatch_send: values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert mock_dispatch_send.called assert len(mock_dispatch_send.mock_calls) == 1 args = mock_dispatch_send.mock_calls[0][1] assert args[1] == 'zwave_new_binary_sensor' @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_ignore(self, discovery, import_module): """Test ignore workaround.""" self.node.manufacturer_id = '010f' self.node.product_type = '0301' self.primary.command_class = const.COMMAND_CLASS_SWITCH_BINARY self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore(self, discovery, import_module): """Test ignore config.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_IGNORED: True }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore_with_registry(self, discovery, import_module): """Test ignore config. The case when the device is in entity registry. """ self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {'mock_component.registry_id': { zwave.CONF_IGNORED: True }} with patch.object(self.registry, 'async_schedule_save'): self.registry.async_get_or_create( 'mock_component', zwave.DOMAIN, '567-1000', suggested_object_id='registry_id') zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_platform_ignore(self, discovery, import_module): """Test platform ignore device.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } platform = MagicMock() import_module.return_value = platform platform.get_device.return_value = None zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_config_polling_intensity(self, discovery, import_module): """Test polling intensity.""" mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_POLLING_INTENSITY: 123, }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert discovery.async_load_platform.called assert self.primary.enable_poll.called assert len(self.primary.enable_poll.mock_calls) == 1 assert self.primary.enable_poll.mock_calls[0][1][0] == 123 class TestZwave(unittest.TestCase): """Test zwave init.""" def test_device_config_glob_is_ordered(self): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): """Tests for zwave services.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() # Initialize zwave setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.zwave_network = self.hass.data[DATA_NETWORK] self.zwave_network.state = MockNetwork.STATE_READY self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.block_till_done() def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() self.hass.stop() def test_add_node(self): """Test zwave add_node service.""" self.hass.services.call('zwave', 'add_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller .add_node.mock_calls) == 1 assert len(self.zwave_network.controller .add_node.mock_calls[0][1]) == 0 def test_add_node_secure(self): """Test zwave add_node_secure service.""" self.hass.services.call('zwave', 'add_node_secure', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller.add_node.mock_calls) == 1 assert (self.zwave_network.controller .add_node.mock_calls[0][1][0] is True) def test_remove_node(self): """Test zwave remove_node service.""" self.hass.services.call('zwave', 'remove_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.remove_node.called assert len(self.zwave_network.controller.remove_node.mock_calls) == 1 def test_cancel_command(self): """Test zwave cancel_command service.""" self.hass.services.call('zwave', 'cancel_command', {}) self.hass.block_till_done() assert self.zwave_network.controller.cancel_command.called assert len(self.zwave_network.controller .cancel_command.mock_calls) == 1 def test_heal_network(self): """Test zwave heal_network service.""" self.hass.services.call('zwave', 'heal_network', {}) self.hass.block_till_done() assert self.zwave_network.heal.called assert len(self.zwave_network.heal.mock_calls) == 1 def test_soft_reset(self): """Test zwave soft_reset service.""" self.hass.services.call('zwave', 'soft_reset', {}) self.hass.block_till_done() assert self.zwave_network.controller.soft_reset.called assert len(self.zwave_network.controller.soft_reset.mock_calls) == 1 def test_test_network(self): """Test zwave test_network service.""" self.hass.services.call('zwave', 'test_network', {}) self.hass.block_till_done() assert self.zwave_network.test.called assert len(self.zwave_network.test.mock_calls) == 1 def test_stop_network(self): """Test zwave stop_network service.""" with patch.object(self.hass.bus, 'fire') as mock_fire: self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() assert self.zwave_network.stop.called assert len(self.zwave_network.stop.mock_calls) == 1 assert mock_fire.called assert len(mock_fire.mock_calls) == 1 assert mock_fire.mock_calls[0][1][0] == const.EVENT_NETWORK_STOP def test_rename_node(self): """Test zwave rename_node service.""" self.zwave_network.nodes = {11: MagicMock()} self.hass.services.call('zwave', 'rename_node', { const.ATTR_NODE_ID: 11, const.ATTR_NAME: 'test_name', }) self.hass.block_till_done() assert self.zwave_network.nodes[11].name == 'test_name' def test_rename_value(self): """Test zwave rename_value service.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, label="Old Label") node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.label == "Old Label" self.hass.services.call('zwave', 'rename_value', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_NAME: "New Label", }) self.hass.block_till_done() assert value.label == "New Label" def test_set_poll_intensity_enable(self): """Test zwave set_poll_intensity service, successful set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 2 assert enable_poll.mock_calls[0][1][0] == 4 def test_set_poll_intensity_enable_failed(self): """Test zwave set_poll_intensity service, failed set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) value.enable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 1 def test_set_poll_intensity_disable(self): """Test zwave set_poll_intensity service, successful disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 2 def test_set_poll_intensity_disable_failed(self): """Test zwave set_poll_intensity service, failed disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) value.disable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 1 def test_remove_failed_node(self): """Test zwave remove_failed_node service.""" self.hass.services.call('zwave', 'remove_failed_node', { const.ATTR_NODE_ID: 12, }) self.hass.block_till_done() remove_failed_node = self.zwave_network.controller.remove_failed_node assert remove_failed_node.called assert len(remove_failed_node.mock_calls) == 1 assert remove_failed_node.mock_calls[0][1][0] == 12 def test_replace_failed_node(self): """Test zwave replace_failed_node service.""" self.hass.services.call('zwave', 'replace_failed_node', { const.ATTR_NODE_ID: 13, }) self.hass.block_till_done() replace_failed_node = self.zwave_network.controller.replace_failed_node assert replace_failed_node.called assert len(replace_failed_node.mock_calls) == 1 assert replace_failed_node.mock_calls[0][1][0] == 13 def test_set_config_parameter(self): """Test zwave set_config_parameter service.""" value_byte = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BYTE, ) value_list = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['item1', 'item2', 'item3'], ) value_button = MockValue( index=14, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BUTTON, ) value_list_int = MockValue( index=15, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['1', '2', '3'], ) value_bool = MockValue( index=16, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BOOL, ) node = MockNode(node_id=14) node.get_values.return_value = { 12: value_byte, 13: value_list, 14: value_button, 15: value_list_int, 16: value_bool } self.zwave_network.nodes = {14: node} # Byte self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 12, const.ATTR_CONFIG_VALUE: 7, }) self.hass.block_till_done() assert value_byte.data == 7 # List self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, const.ATTR_CONFIG_VALUE: 'item3', }) self.hass.block_till_done() assert value_list.data == 'item3' # Button self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 14, const.ATTR_CONFIG_VALUE: True, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called assert self.zwave_network.manager.releaseButton.called # List of Ints self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 15, const.ATTR_CONFIG_VALUE: 3, }) self.hass.block_till_done() assert value_list_int.data == '3' # Boolean Truthy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'True', }) self.hass.block_till_done() assert value_bool.data == 1 # Boolean Falsy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'False', }) self.hass.block_till_done() assert value_bool.data == 0 # Different Parameter Size self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 19, const.ATTR_CONFIG_VALUE: 0x01020304, const.ATTR_CONFIG_SIZE: 4 }) self.hass.block_till_done() assert node.set_config_param.called assert len(node.set_config_param.mock_calls) == 1 assert node.set_config_param.mock_calls[0][1][0] == 19 assert node.set_config_param.mock_calls[0][1][1] == 0x01020304 assert node.set_config_param.mock_calls[0][1][2] == 4 node.set_config_param.reset_mock() def test_print_config_parameter(self): """Test zwave print_config_parameter service.""" value1 = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, data=1234, ) value2 = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, data=2345, ) node = MockNode(node_id=14) node.values = {12: value1, 13: value2} self.zwave_network.nodes = {14: node} with patch.object(zwave, '_LOGGER') as mock_logger: self.hass.services.call('zwave', 'print_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, }) self.hass.block_till_done() assert mock_logger.info.called assert len(mock_logger.info.mock_calls) == 1 assert mock_logger.info.mock_calls[0][1][1] == 13 assert mock_logger.info.mock_calls[0][1][2] == 14 assert mock_logger.info.mock_calls[0][1][3] == 2345 def test_print_node(self): """Test zwave print_node_parameter service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} with self.assertLogs(level='DEBUG') as mock_logger: self.hass.services.call('zwave', 'print_node', { const.ATTR_NODE_ID: 14 }) self.hass.block_till_done() assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 15, }) self.hass.block_till_done() assert value.data == 15 node.can_wake_up_value = False self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 20, }) self.hass.block_till_done() assert value.data == 15 def test_reset_node_meters(self): """Test zwave reset_node_meters service.""" value = MockValue( instance=1, index=8, data=99.5, command_class=const.COMMAND_CLASS_METER, ) reset_value = MockValue( instance=1, index=33, command_class=const.COMMAND_CLASS_METER, ) node = MockNode(node_id=14) node.values = {8: value, 33: reset_value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, const.ATTR_INSTANCE: 2, }) self.hass.block_till_done() assert not self.zwave_network.manager.pressButton.called assert not self.zwave_network.manager.releaseButton.called self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called value_id, = self.zwave_network.manager.pressButton.mock_calls.pop(0)[1] assert value_id == reset_value.value_id assert self.zwave_network.manager.releaseButton.called value_id, = ( self.zwave_network.manager.releaseButton.mock_calls.pop(0)[1]) assert value_id == reset_value.value_id def test_add_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'add', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.add_association.called assert len(group.add_association.mock_calls) == 1 assert group.add_association.mock_calls[0][1][0] == 24 assert group.add_association.mock_calls[0][1][1] == 5 def test_remove_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'remove', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.remove_association.called assert len(group.remove_association.mock_calls) == 1 assert group.remove_association.mock_calls[0][1][0] == 24 assert group.remove_association.mock_calls[0][1][1] == 5 def test_refresh_entity(self): """Test zwave refresh_entity service.""" node = MockNode() value = MockValue(data=False, node=node, command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50, node=node, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = get_device(node=node, values=values, node_config={}) device.hass = self.hass device.entity_id = 'binary_sensor.mock_entity_id' self.hass.add_job(device.async_added_to_hass()) self.hass.block_till_done() self.hass.services.call('zwave', 'refresh_entity', { ATTR_ENTITY_ID: 'binary_sensor.mock_entity_id', }) self.hass.block_till_done() assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 assert sorted([node.refresh_value.mock_calls[0][1][0], node.refresh_value.mock_calls[1][1][0]]) == \ sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert node.refresh_info.called assert len(node.refresh_info.mock_calls) == 1 def test_set_node_value(self): """Test zwave set_node_value service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=4 ) node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR]) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12, const.ATTR_CONFIG_VALUE: 2, }) self.hass.block_till_done() assert self.zwave_network.nodes[14].values[12].data == 2 def test_refresh_node_value(self): """Test zwave refresh_node_value service.""" node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR], network=self.zwave_network) value = MockValue( node=node, index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=2 ) value.refresh = MagicMock() node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12 }) self.hass.block_till_done() assert value.refresh.called def test_heal_node(self): """Test zwave heal_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'heal_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.heal.called assert len(node.heal.mock_calls) == 1 def test_test_node(self): """Test the zwave test_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'test_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.test.called assert len(node.test.mock_calls) == 1
jabesq/home-assistant
tests/components/zwave/test_init.py
homeassistant/components/wirelesstag/binary_sensor.py
# coding: utf-8 """Constants for the LCN component.""" from itertools import product from homeassistant.const import TEMP_CELSIUS, TEMP_FAHRENHEIT DOMAIN = 'lcn' DATA_LCN = 'lcn' DEFAULT_NAME = 'pchk' CONF_CONNECTIONS = 'connections' CONF_SK_NUM_TRIES = 'sk_num_tries' CONF_OUTPUT = 'output' CONF_DIM_MODE = 'dim_mode' CONF_DIMMABLE = 'dimmable' CONF_TRANSITION = 'transition' CONF_MOTOR = 'motor' CONF_LOCKABLE = 'lockable' CONF_VARIABLE = 'variable' CONF_VALUE = 'value' CONF_RELVARREF = 'value_reference' CONF_SOURCE = 'source' CONF_SETPOINT = 'setpoint' CONF_LED = 'led' CONF_KEYS = 'keys' CONF_TIME = 'time' CONF_TIME_UNIT = 'time_unit' CONF_TABLE = 'table' CONF_ROW = 'row' CONF_TEXT = 'text' CONF_PCK = 'pck' CONF_CLIMATES = 'climates' CONF_MAX_TEMP = 'max_temp' CONF_MIN_TEMP = 'min_temp' CONF_SCENES = 'scenes' CONF_REGISTER = 'register' CONF_SCENE = 'scene' CONF_OUTPUTS = 'outputs' DIM_MODES = ['STEPS50', 'STEPS200'] OUTPUT_PORTS = ['OUTPUT1', 'OUTPUT2', 'OUTPUT3', 'OUTPUT4'] RELAY_PORTS = ['RELAY1', 'RELAY2', 'RELAY3', 'RELAY4', 'RELAY5', 'RELAY6', 'RELAY7', 'RELAY8', 'MOTORONOFF1', 'MOTORUPDOWN1', 'MOTORONOFF2', 'MOTORUPDOWN2', 'MOTORONOFF3', 'MOTORUPDOWN3', 'MOTORONOFF4', 'MOTORUPDOWN4'] MOTOR_PORTS = ['MOTOR1', 'MOTOR2', 'MOTOR3', 'MOTOR4'] LED_PORTS = ['LED1', 'LED2', 'LED3', 'LED4', 'LED5', 'LED6', 'LED7', 'LED8', 'LED9', 'LED10', 'LED11', 'LED12'] LED_STATUS = ['OFF', 'ON', 'BLINK', 'FLICKER'] LOGICOP_PORTS = ['LOGICOP1', 'LOGICOP2', 'LOGICOP3', 'LOGICOP4'] BINSENSOR_PORTS = ['BINSENSOR1', 'BINSENSOR2', 'BINSENSOR3', 'BINSENSOR4', 'BINSENSOR5', 'BINSENSOR6', 'BINSENSOR7', 'BINSENSOR8'] KEYS = ['{:s}{:d}'.format(t[0], t[1]) for t in product(['A', 'B', 'C', 'D'], range(1, 9))] VARIABLES = ['VAR1ORTVAR', 'VAR2ORR1VAR', 'VAR3ORR2VAR', 'TVAR', 'R1VAR', 'R2VAR', 'VAR1', 'VAR2', 'VAR3', 'VAR4', 'VAR5', 'VAR6', 'VAR7', 'VAR8', 'VAR9', 'VAR10', 'VAR11', 'VAR12'] SETPOINTS = ['R1VARSETPOINT', 'R2VARSETPOINT'] THRESHOLDS = ['THRS1', 'THRS2', 'THRS3', 'THRS4', 'THRS5', 'THRS2_1', 'THRS2_2', 'THRS2_3', 'THRS2_4', 'THRS3_1', 'THRS3_2', 'THRS3_3', 'THRS3_4', 'THRS4_1', 'THRS4_2', 'THRS4_3', 'THRS4_4'] S0_INPUTS = ['S0INPUT1', 'S0INPUT2', 'S0INPUT3', 'S0INPUT4'] VAR_UNITS = ['', 'LCN', 'NATIVE', TEMP_CELSIUS, '°K', TEMP_FAHRENHEIT, 'LUX_T', 'LX_T', 'LUX_I', 'LUX', 'LX', 'M/S', 'METERPERSECOND', '%', 'PERCENT', 'PPM', 'VOLT', 'V', 'AMPERE', 'AMP', 'A', 'DEGREE', '°'] RELVARREF = ['CURRENT', 'PROG'] SENDKEYCOMMANDS = ['HIT', 'MAKE', 'BREAK', 'DONTSEND'] TIME_UNITS = ['SECONDS', 'SECOND', 'SEC', 'S', 'MINUTES', 'MINUTE', 'MIN', 'M', 'HOURS', 'HOUR', 'H', 'DAYS', 'DAY', 'D']
"""Tests for the Z-Wave init.""" import asyncio from collections import OrderedDict from datetime import datetime import unittest from unittest.mock import MagicMock, patch import pytest from pytz import utc import voluptuous as vol from homeassistant.bootstrap import async_setup_component from homeassistant.components import zwave from homeassistant.components.zwave import ( CONF_DEVICE_CONFIG_GLOB, CONFIG_SCHEMA, DATA_NETWORK, const) from homeassistant.components.zwave.binary_sensor import get_device from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.device_registry import ( async_get_registry as get_dev_reg) from homeassistant.setup import setup_component from tests.common import ( async_fire_time_changed, get_test_home_assistant, mock_coro, mock_registry) from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue async def test_valid_device_config(hass, mock_openzwave): """Test valid device config.""" device_config = { 'light.kitchen': { 'ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert result async def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = { 'light.kitchen': { 'some_ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert not result def test_config_access_error(): """Test threading error accessing config values.""" node = MagicMock() def side_effect(): raise RuntimeError node.values.values.side_effect = side_effect result = zwave.get_config_value(node, 1) assert result is None async def test_network_options(hass, mock_openzwave): """Test network options.""" result = await async_setup_component(hass, 'zwave', { 'zwave': { 'usb_path': 'mock_usb_path', 'config_path': 'mock_config_path', }}) await hass.async_block_till_done() assert result network = hass.data[zwave.DATA_NETWORK] assert network.options.device == 'mock_usb_path' assert network.options.config_path == 'mock_config_path' async def test_network_key_validation(hass, mock_openzwave): """Test network key validation.""" test_values = [ ('0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,' '0x0E,0x0F,0x10'), ] for value in test_values: result = zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) assert result['zwave']['network_key'] == value async def test_erronous_network_key_fails_validation(hass, mock_openzwave): """Test failing erronous network key validation.""" test_values = [ ('0x 01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0X01,0X02,0X03,0X04,0X05,0X06,0X07,0X08,0X09,0X0A,0X0B,0X0C,0X0D,' '0X0E,0X0F,0X10'), 'invalid', '1234567', 1234567 ] for value in test_values: with pytest.raises(vol.Invalid): zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) async def test_auto_heal_midnight(hass, mock_openzwave): """Test network auto-heal at midnight.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': True, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert network.heal.called assert len(network.heal.mock_calls) == 1 async def test_auto_heal_disabled(hass, mock_openzwave): """Test network auto-heal disabled.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': False, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert not network.heal.called async def test_setup_platform(hass, mock_openzwave): """Test invalid device config.""" mock_device = MagicMock() hass.data[DATA_NETWORK] = MagicMock() hass.data[zwave.DATA_DEVICES] = {456: mock_device} async_add_entities = MagicMock() result = await zwave.async_setup_platform( hass, None, async_add_entities, None) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 123}) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 456}) assert result assert async_add_entities.called assert len(async_add_entities.mock_calls) == 1 assert async_add_entities.mock_calls[0][1][0] == [mock_device] async def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): """Test device entity base class.""" node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.value_added() device.update_properties() await hass.async_block_till_done() assert not device.should_poll assert device.unique_id == "10-11" assert device.name == 'Mock Node Sensor' assert device.device_state_attributes[zwave.ATTR_POWER] == 50.123 async def test_node_removed(hass, mock_openzwave): """Test node removed in base class.""" # Create a mock node & node entity node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.entity_id = 'zwave.mock_node' device.value_added() device.update_properties() await hass.async_block_till_done() # Save it to the entity registry registry = mock_registry(hass) registry.async_get_or_create('zwave', 'zwave', device.unique_id) device.entity_id = registry.async_get_entity_id( 'zwave', 'zwave', device.unique_id) # Create dummy entity registry entries for other integrations hue_entity = registry.async_get_or_create('light', 'hue', 1234) zha_entity = registry.async_get_or_create('sensor', 'zha', 5678) # Verify our Z-Wave entity is registered assert registry.async_is_registered(device.entity_id) # Remove it entity_id = device.entity_id await device.node_removed() # Verify registry entry for our Z-Wave node is gone assert not registry.async_is_registered(entity_id) # Verify registry entries for our other entities remain assert registry.async_is_registered(hue_entity.entity_id) assert registry.async_is_registered(zha_entity.entity_id) async def test_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node').state == 'unknown' async def test_unparsed_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode( node_id=14, manufacturer_name=None, name=None, is_ready=False) sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert len(sleeps) == const.NODE_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1:] == \ (14, const.NODE_READY_WAIT_SECS) assert hass.states.get('zwave.unknown_node_14').state == 'unknown' async def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': { 'device_config': { 'zwave.mock_node': { 'ignored': True, }}}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None async def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' async def test_value_entities(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = {} def mock_connect(receiver, signal, *args, **kwargs): mock_receivers[signal] = receiver with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert mock_receivers hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_ALL_NODES_QUERIED]) node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) zwave_network.nodes = {node.node_id: node} value = MockValue( data=False, node=node, index=12, instance=1, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values = {'primary': value, value.value_id: value} value2 = MockValue( data=False, node=node, index=12, instance=2, label="Mock Value B", command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values[value2.value_id] = value2 hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_NODE_ADDED], node) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value2) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' assert hass.states.get( 'binary_sensor.mock_node_mock_value_b').state == 'off' ent_reg = await async_get_registry(hass) dev_reg = await get_dev_reg(hass) entry = ent_reg.async_get('zwave.mock_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) node_dev_id = entry.device_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) assert entry.name is None assert entry.device_id == node_dev_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value2.object_id) assert entry.name is None assert entry.device_id != node_dev_id device_id_b = entry.device_id device = dev_reg.async_get(node_dev_id) assert device is not None assert device.name == node.name old_device = device device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming without updating await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_NAME: "Demo Node", }) await hass.async_block_till_done() assert node.name == "Demo Node" entry = ent_reg.async_get('zwave.mock_node') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Node", }) await hass.async_block_till_done() assert node.name == "New Node" entry = ent_reg.async_get('zwave.new_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) entry = ent_reg.async_get('binary_sensor.new_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) await hass.services.async_call('zwave', 'rename_value', { const.ATTR_NODE_ID: node.node_id, const.ATTR_VALUE_ID: value.object_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Label", }) await hass.async_block_till_done() entry = ent_reg.async_get('binary_sensor.new_node_new_label') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) async def test_value_discovery_existing_entity(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_THERMOSTAT) setpoint = MockValue( data=22.0, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, setpoint) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] is None def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): temperature = MockValue( data=23.5, node=node, index=1, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, temperature) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] == 23.5 async def test_power_schemes(hass, mock_openzwave): """Test power attribute.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SWITCH_BINARY) switch = MockValue( data=True, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SWITCH_BINARY, genre=const.GENRE_USER, type=const.TYPE_BOOL) hass.async_add_job(mock_receivers[0], node, switch) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').state == 'on' assert 'power_consumption' not in hass.states.get( 'switch.mock_node_mock_value').attributes def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): power = MockValue( data=23.5, node=node, index=const.INDEX_SENSOR_MULTILEVEL_POWER, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL) hass.async_add_job(mock_receivers[0], node, power) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').attributes[ 'power_consumption'] == 23.5 async def test_network_ready(hass, mock_openzwave): """Test Node network ready event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete_some_dead(hass, mock_openzwave): """Test Node network complete some dead event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE_SOME_DEAD, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 class TestZWaveDeviceEntityValues(unittest.TestCase): """Tests for the ZWaveDeviceEntityValues helper.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() self.registry = mock_registry(self.hass) setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.node = MockNode() self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: ['mock_primary_class'], }, 'secondary': { const.DISC_COMMAND_CLASS: ['mock_secondary_class'], }, 'optional': { const.DISC_COMMAND_CLASS: ['mock_optional_class'], const.DISC_OPTIONAL: True, }}} self.primary = MockValue( command_class='mock_primary_class', node=self.node, value_id=1000) self.secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.duplicate_secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.optional = MockValue( command_class='mock_optional_class', node=self.node) self.no_match_value = MockValue( command_class='mock_bad_class', node=self.node) self.entity_id = 'mock_component.mock_node_mock_value' self.zwave_config = {'zwave': {}} self.device_config = {self.entity_id: {}} def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) assert values.primary is self.primary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) self.hass.block_till_done() assert values.secondary is self.secondary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config discovery.async_load_platform.reset_mock() values.check_value(self.optional) values.check_value(self.duplicate_secondary) values.check_value(self.no_match_value) self.hass.block_till_done() assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called assert len(values._entity.value_added.mock_calls) == 1 assert values._entity.value_changed.called assert len(values._entity.value_changed.mock_calls) == 1 @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, self.optional.value_id: self.optional, self.no_match_value.value_id: self.no_match_value, } values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert values.primary is self.primary assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config assert not self.primary.enable_poll.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_node_schema_mismatch(self, discovery, import_module): """Test node schema mismatch.""" self.node.generic = 'no_match' self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.mock_schema[const.DISC_GENERIC_DEVICE_CLASS] = ['generic_match'] values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.manufacturer_id = '010f' self.node.product_type = '0b00' self.primary.command_class = const.COMMAND_CLASS_SENSOR_ALARM self.entity_id = 'binary_sensor.mock_node_mock_value' self.device_config = {self.entity_id: {}} self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} with patch.object(zwave, 'async_dispatcher_send') as \ mock_dispatch_send: values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert mock_dispatch_send.called assert len(mock_dispatch_send.mock_calls) == 1 args = mock_dispatch_send.mock_calls[0][1] assert args[1] == 'zwave_new_binary_sensor' @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_ignore(self, discovery, import_module): """Test ignore workaround.""" self.node.manufacturer_id = '010f' self.node.product_type = '0301' self.primary.command_class = const.COMMAND_CLASS_SWITCH_BINARY self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore(self, discovery, import_module): """Test ignore config.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_IGNORED: True }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore_with_registry(self, discovery, import_module): """Test ignore config. The case when the device is in entity registry. """ self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {'mock_component.registry_id': { zwave.CONF_IGNORED: True }} with patch.object(self.registry, 'async_schedule_save'): self.registry.async_get_or_create( 'mock_component', zwave.DOMAIN, '567-1000', suggested_object_id='registry_id') zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_platform_ignore(self, discovery, import_module): """Test platform ignore device.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } platform = MagicMock() import_module.return_value = platform platform.get_device.return_value = None zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_config_polling_intensity(self, discovery, import_module): """Test polling intensity.""" mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_POLLING_INTENSITY: 123, }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert discovery.async_load_platform.called assert self.primary.enable_poll.called assert len(self.primary.enable_poll.mock_calls) == 1 assert self.primary.enable_poll.mock_calls[0][1][0] == 123 class TestZwave(unittest.TestCase): """Test zwave init.""" def test_device_config_glob_is_ordered(self): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): """Tests for zwave services.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() # Initialize zwave setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.zwave_network = self.hass.data[DATA_NETWORK] self.zwave_network.state = MockNetwork.STATE_READY self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.block_till_done() def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() self.hass.stop() def test_add_node(self): """Test zwave add_node service.""" self.hass.services.call('zwave', 'add_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller .add_node.mock_calls) == 1 assert len(self.zwave_network.controller .add_node.mock_calls[0][1]) == 0 def test_add_node_secure(self): """Test zwave add_node_secure service.""" self.hass.services.call('zwave', 'add_node_secure', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller.add_node.mock_calls) == 1 assert (self.zwave_network.controller .add_node.mock_calls[0][1][0] is True) def test_remove_node(self): """Test zwave remove_node service.""" self.hass.services.call('zwave', 'remove_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.remove_node.called assert len(self.zwave_network.controller.remove_node.mock_calls) == 1 def test_cancel_command(self): """Test zwave cancel_command service.""" self.hass.services.call('zwave', 'cancel_command', {}) self.hass.block_till_done() assert self.zwave_network.controller.cancel_command.called assert len(self.zwave_network.controller .cancel_command.mock_calls) == 1 def test_heal_network(self): """Test zwave heal_network service.""" self.hass.services.call('zwave', 'heal_network', {}) self.hass.block_till_done() assert self.zwave_network.heal.called assert len(self.zwave_network.heal.mock_calls) == 1 def test_soft_reset(self): """Test zwave soft_reset service.""" self.hass.services.call('zwave', 'soft_reset', {}) self.hass.block_till_done() assert self.zwave_network.controller.soft_reset.called assert len(self.zwave_network.controller.soft_reset.mock_calls) == 1 def test_test_network(self): """Test zwave test_network service.""" self.hass.services.call('zwave', 'test_network', {}) self.hass.block_till_done() assert self.zwave_network.test.called assert len(self.zwave_network.test.mock_calls) == 1 def test_stop_network(self): """Test zwave stop_network service.""" with patch.object(self.hass.bus, 'fire') as mock_fire: self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() assert self.zwave_network.stop.called assert len(self.zwave_network.stop.mock_calls) == 1 assert mock_fire.called assert len(mock_fire.mock_calls) == 1 assert mock_fire.mock_calls[0][1][0] == const.EVENT_NETWORK_STOP def test_rename_node(self): """Test zwave rename_node service.""" self.zwave_network.nodes = {11: MagicMock()} self.hass.services.call('zwave', 'rename_node', { const.ATTR_NODE_ID: 11, const.ATTR_NAME: 'test_name', }) self.hass.block_till_done() assert self.zwave_network.nodes[11].name == 'test_name' def test_rename_value(self): """Test zwave rename_value service.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, label="Old Label") node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.label == "Old Label" self.hass.services.call('zwave', 'rename_value', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_NAME: "New Label", }) self.hass.block_till_done() assert value.label == "New Label" def test_set_poll_intensity_enable(self): """Test zwave set_poll_intensity service, successful set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 2 assert enable_poll.mock_calls[0][1][0] == 4 def test_set_poll_intensity_enable_failed(self): """Test zwave set_poll_intensity service, failed set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) value.enable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 1 def test_set_poll_intensity_disable(self): """Test zwave set_poll_intensity service, successful disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 2 def test_set_poll_intensity_disable_failed(self): """Test zwave set_poll_intensity service, failed disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) value.disable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 1 def test_remove_failed_node(self): """Test zwave remove_failed_node service.""" self.hass.services.call('zwave', 'remove_failed_node', { const.ATTR_NODE_ID: 12, }) self.hass.block_till_done() remove_failed_node = self.zwave_network.controller.remove_failed_node assert remove_failed_node.called assert len(remove_failed_node.mock_calls) == 1 assert remove_failed_node.mock_calls[0][1][0] == 12 def test_replace_failed_node(self): """Test zwave replace_failed_node service.""" self.hass.services.call('zwave', 'replace_failed_node', { const.ATTR_NODE_ID: 13, }) self.hass.block_till_done() replace_failed_node = self.zwave_network.controller.replace_failed_node assert replace_failed_node.called assert len(replace_failed_node.mock_calls) == 1 assert replace_failed_node.mock_calls[0][1][0] == 13 def test_set_config_parameter(self): """Test zwave set_config_parameter service.""" value_byte = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BYTE, ) value_list = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['item1', 'item2', 'item3'], ) value_button = MockValue( index=14, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BUTTON, ) value_list_int = MockValue( index=15, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['1', '2', '3'], ) value_bool = MockValue( index=16, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BOOL, ) node = MockNode(node_id=14) node.get_values.return_value = { 12: value_byte, 13: value_list, 14: value_button, 15: value_list_int, 16: value_bool } self.zwave_network.nodes = {14: node} # Byte self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 12, const.ATTR_CONFIG_VALUE: 7, }) self.hass.block_till_done() assert value_byte.data == 7 # List self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, const.ATTR_CONFIG_VALUE: 'item3', }) self.hass.block_till_done() assert value_list.data == 'item3' # Button self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 14, const.ATTR_CONFIG_VALUE: True, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called assert self.zwave_network.manager.releaseButton.called # List of Ints self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 15, const.ATTR_CONFIG_VALUE: 3, }) self.hass.block_till_done() assert value_list_int.data == '3' # Boolean Truthy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'True', }) self.hass.block_till_done() assert value_bool.data == 1 # Boolean Falsy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'False', }) self.hass.block_till_done() assert value_bool.data == 0 # Different Parameter Size self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 19, const.ATTR_CONFIG_VALUE: 0x01020304, const.ATTR_CONFIG_SIZE: 4 }) self.hass.block_till_done() assert node.set_config_param.called assert len(node.set_config_param.mock_calls) == 1 assert node.set_config_param.mock_calls[0][1][0] == 19 assert node.set_config_param.mock_calls[0][1][1] == 0x01020304 assert node.set_config_param.mock_calls[0][1][2] == 4 node.set_config_param.reset_mock() def test_print_config_parameter(self): """Test zwave print_config_parameter service.""" value1 = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, data=1234, ) value2 = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, data=2345, ) node = MockNode(node_id=14) node.values = {12: value1, 13: value2} self.zwave_network.nodes = {14: node} with patch.object(zwave, '_LOGGER') as mock_logger: self.hass.services.call('zwave', 'print_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, }) self.hass.block_till_done() assert mock_logger.info.called assert len(mock_logger.info.mock_calls) == 1 assert mock_logger.info.mock_calls[0][1][1] == 13 assert mock_logger.info.mock_calls[0][1][2] == 14 assert mock_logger.info.mock_calls[0][1][3] == 2345 def test_print_node(self): """Test zwave print_node_parameter service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} with self.assertLogs(level='DEBUG') as mock_logger: self.hass.services.call('zwave', 'print_node', { const.ATTR_NODE_ID: 14 }) self.hass.block_till_done() assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 15, }) self.hass.block_till_done() assert value.data == 15 node.can_wake_up_value = False self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 20, }) self.hass.block_till_done() assert value.data == 15 def test_reset_node_meters(self): """Test zwave reset_node_meters service.""" value = MockValue( instance=1, index=8, data=99.5, command_class=const.COMMAND_CLASS_METER, ) reset_value = MockValue( instance=1, index=33, command_class=const.COMMAND_CLASS_METER, ) node = MockNode(node_id=14) node.values = {8: value, 33: reset_value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, const.ATTR_INSTANCE: 2, }) self.hass.block_till_done() assert not self.zwave_network.manager.pressButton.called assert not self.zwave_network.manager.releaseButton.called self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called value_id, = self.zwave_network.manager.pressButton.mock_calls.pop(0)[1] assert value_id == reset_value.value_id assert self.zwave_network.manager.releaseButton.called value_id, = ( self.zwave_network.manager.releaseButton.mock_calls.pop(0)[1]) assert value_id == reset_value.value_id def test_add_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'add', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.add_association.called assert len(group.add_association.mock_calls) == 1 assert group.add_association.mock_calls[0][1][0] == 24 assert group.add_association.mock_calls[0][1][1] == 5 def test_remove_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'remove', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.remove_association.called assert len(group.remove_association.mock_calls) == 1 assert group.remove_association.mock_calls[0][1][0] == 24 assert group.remove_association.mock_calls[0][1][1] == 5 def test_refresh_entity(self): """Test zwave refresh_entity service.""" node = MockNode() value = MockValue(data=False, node=node, command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50, node=node, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = get_device(node=node, values=values, node_config={}) device.hass = self.hass device.entity_id = 'binary_sensor.mock_entity_id' self.hass.add_job(device.async_added_to_hass()) self.hass.block_till_done() self.hass.services.call('zwave', 'refresh_entity', { ATTR_ENTITY_ID: 'binary_sensor.mock_entity_id', }) self.hass.block_till_done() assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 assert sorted([node.refresh_value.mock_calls[0][1][0], node.refresh_value.mock_calls[1][1][0]]) == \ sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert node.refresh_info.called assert len(node.refresh_info.mock_calls) == 1 def test_set_node_value(self): """Test zwave set_node_value service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=4 ) node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR]) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12, const.ATTR_CONFIG_VALUE: 2, }) self.hass.block_till_done() assert self.zwave_network.nodes[14].values[12].data == 2 def test_refresh_node_value(self): """Test zwave refresh_node_value service.""" node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR], network=self.zwave_network) value = MockValue( node=node, index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=2 ) value.refresh = MagicMock() node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12 }) self.hass.block_till_done() assert value.refresh.called def test_heal_node(self): """Test zwave heal_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'heal_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.heal.called assert len(node.heal.mock_calls) == 1 def test_test_node(self): """Test the zwave test_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'test_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.test.called assert len(node.test.mock_calls) == 1
jabesq/home-assistant
tests/components/zwave/test_init.py
homeassistant/components/lcn/const.py
"""Support for OASA Telematics from telematics.oasa.gr.""" import logging from datetime import timedelta from operator import itemgetter import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_NAME, ATTR_ATTRIBUTION, DEVICE_CLASS_TIMESTAMP) from homeassistant.helpers.entity import Entity from homeassistant.util import dt as dt_util _LOGGER = logging.getLogger(__name__) ATTR_STOP_ID = 'stop_id' ATTR_STOP_NAME = 'stop_name' ATTR_ROUTE_ID = 'route_id' ATTR_ROUTE_NAME = 'route_name' ATTR_NEXT_ARRIVAL = 'next_arrival' ATTR_SECOND_NEXT_ARRIVAL = 'second_next_arrival' ATTR_NEXT_DEPARTURE = 'next_departure' ATTRIBUTION = "Data retrieved from telematics.oasa.gr" CONF_STOP_ID = 'stop_id' CONF_ROUTE_ID = 'route_id' DEFAULT_NAME = 'OASA Telematics' ICON = 'mdi:bus' SCAN_INTERVAL = timedelta(seconds=60) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_STOP_ID): cv.string, vol.Required(CONF_ROUTE_ID): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the OASA Telematics sensor.""" name = config[CONF_NAME] stop_id = config[CONF_STOP_ID] route_id = config.get(CONF_ROUTE_ID) data = OASATelematicsData(stop_id, route_id) add_entities([OASATelematicsSensor( data, stop_id, route_id, name)], True) class OASATelematicsSensor(Entity): """Implementation of the OASA Telematics sensor.""" def __init__(self, data, stop_id, route_id, name): """Initialize the sensor.""" self.data = data self._name = name self._stop_id = stop_id self._route_id = route_id self._name_data = self._times = self._state = None @property def name(self): """Return the name of the sensor.""" return self._name @property def device_class(self): """Return the class of this sensor.""" return DEVICE_CLASS_TIMESTAMP @property def state(self): """Return the state of the sensor.""" return self._state @property def device_state_attributes(self): """Return the state attributes.""" params = {} if self._times is not None: next_arrival_data = self._times[0] if ATTR_NEXT_ARRIVAL in next_arrival_data: next_arrival = next_arrival_data[ATTR_NEXT_ARRIVAL] params.update({ ATTR_NEXT_ARRIVAL: next_arrival.isoformat() }) if len(self._times) > 1: second_next_arrival_time = self._times[1][ATTR_NEXT_ARRIVAL] if second_next_arrival_time is not None: second_arrival = second_next_arrival_time params.update({ ATTR_SECOND_NEXT_ARRIVAL: second_arrival.isoformat() }) params.update({ ATTR_ROUTE_ID: self._times[0][ATTR_ROUTE_ID], ATTR_STOP_ID: self._stop_id, ATTR_ATTRIBUTION: ATTRIBUTION, }) params.update({ ATTR_ROUTE_NAME: self._name_data[ATTR_ROUTE_NAME], ATTR_STOP_NAME: self._name_data[ATTR_STOP_NAME] }) return {k: v for k, v in params.items() if v} @property def icon(self): """Icon to use in the frontend, if any.""" return ICON def update(self): """Get the latest data from OASA API and update the states.""" self.data.update() self._times = self.data.info self._name_data = self.data.name_data next_arrival_data = self._times[0] if ATTR_NEXT_ARRIVAL in next_arrival_data: self._state = next_arrival_data[ATTR_NEXT_ARRIVAL].isoformat() class OASATelematicsData(): """The class for handling data retrieval.""" def __init__(self, stop_id, route_id): """Initialize the data object.""" import oasatelematics self.stop_id = stop_id self.route_id = route_id self.info = self.empty_result() self.oasa_api = oasatelematics self.name_data = {ATTR_ROUTE_NAME: self.get_route_name(), ATTR_STOP_NAME: self.get_stop_name()} def empty_result(self): """Object returned when no arrivals are found.""" return [{ATTR_ROUTE_ID: self.route_id}] def get_route_name(self): """Get the route name from the API.""" try: route = self.oasa_api.getRouteName(self.route_id) if route: return route[0].get('route_departure_eng') except TypeError: _LOGGER.error("Cannot get route name from OASA API") return None def get_stop_name(self): """Get the stop name from the API.""" try: name_data = self.oasa_api.getStopNameAndXY(self.stop_id) if name_data: return name_data[0].get('stop_descr_matrix_eng') except TypeError: _LOGGER.error("Cannot get stop name from OASA API") return None def update(self): """Get the latest arrival data from telematics.oasa.gr API.""" self.info = [] results = self.oasa_api.getStopArrivals(self.stop_id) if not results: self.info = self.empty_result() return # Parse results results = [r for r in results if r.get('route_code') in self.route_id] current_time = dt_util.utcnow() for result in results: btime2 = result.get('btime2') if btime2 is not None: arrival_min = int(btime2) timestamp = current_time + timedelta(minutes=arrival_min) arrival_data = {ATTR_NEXT_ARRIVAL: timestamp, ATTR_ROUTE_ID: self.route_id} self.info.append(arrival_data) if not self.info: _LOGGER.debug("No arrivals with given parameters") self.info = self.empty_result() return # Sort the data by time sort = sorted(self.info, key=itemgetter(ATTR_NEXT_ARRIVAL)) self.info = sort
"""Tests for the Z-Wave init.""" import asyncio from collections import OrderedDict from datetime import datetime import unittest from unittest.mock import MagicMock, patch import pytest from pytz import utc import voluptuous as vol from homeassistant.bootstrap import async_setup_component from homeassistant.components import zwave from homeassistant.components.zwave import ( CONF_DEVICE_CONFIG_GLOB, CONFIG_SCHEMA, DATA_NETWORK, const) from homeassistant.components.zwave.binary_sensor import get_device from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.device_registry import ( async_get_registry as get_dev_reg) from homeassistant.setup import setup_component from tests.common import ( async_fire_time_changed, get_test_home_assistant, mock_coro, mock_registry) from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue async def test_valid_device_config(hass, mock_openzwave): """Test valid device config.""" device_config = { 'light.kitchen': { 'ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert result async def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = { 'light.kitchen': { 'some_ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert not result def test_config_access_error(): """Test threading error accessing config values.""" node = MagicMock() def side_effect(): raise RuntimeError node.values.values.side_effect = side_effect result = zwave.get_config_value(node, 1) assert result is None async def test_network_options(hass, mock_openzwave): """Test network options.""" result = await async_setup_component(hass, 'zwave', { 'zwave': { 'usb_path': 'mock_usb_path', 'config_path': 'mock_config_path', }}) await hass.async_block_till_done() assert result network = hass.data[zwave.DATA_NETWORK] assert network.options.device == 'mock_usb_path' assert network.options.config_path == 'mock_config_path' async def test_network_key_validation(hass, mock_openzwave): """Test network key validation.""" test_values = [ ('0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,' '0x0E,0x0F,0x10'), ] for value in test_values: result = zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) assert result['zwave']['network_key'] == value async def test_erronous_network_key_fails_validation(hass, mock_openzwave): """Test failing erronous network key validation.""" test_values = [ ('0x 01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0X01,0X02,0X03,0X04,0X05,0X06,0X07,0X08,0X09,0X0A,0X0B,0X0C,0X0D,' '0X0E,0X0F,0X10'), 'invalid', '1234567', 1234567 ] for value in test_values: with pytest.raises(vol.Invalid): zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) async def test_auto_heal_midnight(hass, mock_openzwave): """Test network auto-heal at midnight.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': True, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert network.heal.called assert len(network.heal.mock_calls) == 1 async def test_auto_heal_disabled(hass, mock_openzwave): """Test network auto-heal disabled.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': False, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert not network.heal.called async def test_setup_platform(hass, mock_openzwave): """Test invalid device config.""" mock_device = MagicMock() hass.data[DATA_NETWORK] = MagicMock() hass.data[zwave.DATA_DEVICES] = {456: mock_device} async_add_entities = MagicMock() result = await zwave.async_setup_platform( hass, None, async_add_entities, None) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 123}) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 456}) assert result assert async_add_entities.called assert len(async_add_entities.mock_calls) == 1 assert async_add_entities.mock_calls[0][1][0] == [mock_device] async def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): """Test device entity base class.""" node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.value_added() device.update_properties() await hass.async_block_till_done() assert not device.should_poll assert device.unique_id == "10-11" assert device.name == 'Mock Node Sensor' assert device.device_state_attributes[zwave.ATTR_POWER] == 50.123 async def test_node_removed(hass, mock_openzwave): """Test node removed in base class.""" # Create a mock node & node entity node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.entity_id = 'zwave.mock_node' device.value_added() device.update_properties() await hass.async_block_till_done() # Save it to the entity registry registry = mock_registry(hass) registry.async_get_or_create('zwave', 'zwave', device.unique_id) device.entity_id = registry.async_get_entity_id( 'zwave', 'zwave', device.unique_id) # Create dummy entity registry entries for other integrations hue_entity = registry.async_get_or_create('light', 'hue', 1234) zha_entity = registry.async_get_or_create('sensor', 'zha', 5678) # Verify our Z-Wave entity is registered assert registry.async_is_registered(device.entity_id) # Remove it entity_id = device.entity_id await device.node_removed() # Verify registry entry for our Z-Wave node is gone assert not registry.async_is_registered(entity_id) # Verify registry entries for our other entities remain assert registry.async_is_registered(hue_entity.entity_id) assert registry.async_is_registered(zha_entity.entity_id) async def test_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node').state == 'unknown' async def test_unparsed_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode( node_id=14, manufacturer_name=None, name=None, is_ready=False) sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert len(sleeps) == const.NODE_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1:] == \ (14, const.NODE_READY_WAIT_SECS) assert hass.states.get('zwave.unknown_node_14').state == 'unknown' async def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': { 'device_config': { 'zwave.mock_node': { 'ignored': True, }}}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None async def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' async def test_value_entities(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = {} def mock_connect(receiver, signal, *args, **kwargs): mock_receivers[signal] = receiver with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert mock_receivers hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_ALL_NODES_QUERIED]) node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) zwave_network.nodes = {node.node_id: node} value = MockValue( data=False, node=node, index=12, instance=1, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values = {'primary': value, value.value_id: value} value2 = MockValue( data=False, node=node, index=12, instance=2, label="Mock Value B", command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values[value2.value_id] = value2 hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_NODE_ADDED], node) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value2) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' assert hass.states.get( 'binary_sensor.mock_node_mock_value_b').state == 'off' ent_reg = await async_get_registry(hass) dev_reg = await get_dev_reg(hass) entry = ent_reg.async_get('zwave.mock_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) node_dev_id = entry.device_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) assert entry.name is None assert entry.device_id == node_dev_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value2.object_id) assert entry.name is None assert entry.device_id != node_dev_id device_id_b = entry.device_id device = dev_reg.async_get(node_dev_id) assert device is not None assert device.name == node.name old_device = device device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming without updating await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_NAME: "Demo Node", }) await hass.async_block_till_done() assert node.name == "Demo Node" entry = ent_reg.async_get('zwave.mock_node') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Node", }) await hass.async_block_till_done() assert node.name == "New Node" entry = ent_reg.async_get('zwave.new_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) entry = ent_reg.async_get('binary_sensor.new_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) await hass.services.async_call('zwave', 'rename_value', { const.ATTR_NODE_ID: node.node_id, const.ATTR_VALUE_ID: value.object_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Label", }) await hass.async_block_till_done() entry = ent_reg.async_get('binary_sensor.new_node_new_label') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) async def test_value_discovery_existing_entity(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_THERMOSTAT) setpoint = MockValue( data=22.0, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, setpoint) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] is None def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): temperature = MockValue( data=23.5, node=node, index=1, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, temperature) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] == 23.5 async def test_power_schemes(hass, mock_openzwave): """Test power attribute.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SWITCH_BINARY) switch = MockValue( data=True, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SWITCH_BINARY, genre=const.GENRE_USER, type=const.TYPE_BOOL) hass.async_add_job(mock_receivers[0], node, switch) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').state == 'on' assert 'power_consumption' not in hass.states.get( 'switch.mock_node_mock_value').attributes def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): power = MockValue( data=23.5, node=node, index=const.INDEX_SENSOR_MULTILEVEL_POWER, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL) hass.async_add_job(mock_receivers[0], node, power) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').attributes[ 'power_consumption'] == 23.5 async def test_network_ready(hass, mock_openzwave): """Test Node network ready event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete_some_dead(hass, mock_openzwave): """Test Node network complete some dead event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE_SOME_DEAD, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 class TestZWaveDeviceEntityValues(unittest.TestCase): """Tests for the ZWaveDeviceEntityValues helper.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() self.registry = mock_registry(self.hass) setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.node = MockNode() self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: ['mock_primary_class'], }, 'secondary': { const.DISC_COMMAND_CLASS: ['mock_secondary_class'], }, 'optional': { const.DISC_COMMAND_CLASS: ['mock_optional_class'], const.DISC_OPTIONAL: True, }}} self.primary = MockValue( command_class='mock_primary_class', node=self.node, value_id=1000) self.secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.duplicate_secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.optional = MockValue( command_class='mock_optional_class', node=self.node) self.no_match_value = MockValue( command_class='mock_bad_class', node=self.node) self.entity_id = 'mock_component.mock_node_mock_value' self.zwave_config = {'zwave': {}} self.device_config = {self.entity_id: {}} def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) assert values.primary is self.primary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) self.hass.block_till_done() assert values.secondary is self.secondary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config discovery.async_load_platform.reset_mock() values.check_value(self.optional) values.check_value(self.duplicate_secondary) values.check_value(self.no_match_value) self.hass.block_till_done() assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called assert len(values._entity.value_added.mock_calls) == 1 assert values._entity.value_changed.called assert len(values._entity.value_changed.mock_calls) == 1 @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, self.optional.value_id: self.optional, self.no_match_value.value_id: self.no_match_value, } values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert values.primary is self.primary assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config assert not self.primary.enable_poll.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_node_schema_mismatch(self, discovery, import_module): """Test node schema mismatch.""" self.node.generic = 'no_match' self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.mock_schema[const.DISC_GENERIC_DEVICE_CLASS] = ['generic_match'] values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.manufacturer_id = '010f' self.node.product_type = '0b00' self.primary.command_class = const.COMMAND_CLASS_SENSOR_ALARM self.entity_id = 'binary_sensor.mock_node_mock_value' self.device_config = {self.entity_id: {}} self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} with patch.object(zwave, 'async_dispatcher_send') as \ mock_dispatch_send: values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert mock_dispatch_send.called assert len(mock_dispatch_send.mock_calls) == 1 args = mock_dispatch_send.mock_calls[0][1] assert args[1] == 'zwave_new_binary_sensor' @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_ignore(self, discovery, import_module): """Test ignore workaround.""" self.node.manufacturer_id = '010f' self.node.product_type = '0301' self.primary.command_class = const.COMMAND_CLASS_SWITCH_BINARY self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore(self, discovery, import_module): """Test ignore config.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_IGNORED: True }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore_with_registry(self, discovery, import_module): """Test ignore config. The case when the device is in entity registry. """ self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {'mock_component.registry_id': { zwave.CONF_IGNORED: True }} with patch.object(self.registry, 'async_schedule_save'): self.registry.async_get_or_create( 'mock_component', zwave.DOMAIN, '567-1000', suggested_object_id='registry_id') zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_platform_ignore(self, discovery, import_module): """Test platform ignore device.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } platform = MagicMock() import_module.return_value = platform platform.get_device.return_value = None zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_config_polling_intensity(self, discovery, import_module): """Test polling intensity.""" mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_POLLING_INTENSITY: 123, }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert discovery.async_load_platform.called assert self.primary.enable_poll.called assert len(self.primary.enable_poll.mock_calls) == 1 assert self.primary.enable_poll.mock_calls[0][1][0] == 123 class TestZwave(unittest.TestCase): """Test zwave init.""" def test_device_config_glob_is_ordered(self): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): """Tests for zwave services.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() # Initialize zwave setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.zwave_network = self.hass.data[DATA_NETWORK] self.zwave_network.state = MockNetwork.STATE_READY self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.block_till_done() def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() self.hass.stop() def test_add_node(self): """Test zwave add_node service.""" self.hass.services.call('zwave', 'add_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller .add_node.mock_calls) == 1 assert len(self.zwave_network.controller .add_node.mock_calls[0][1]) == 0 def test_add_node_secure(self): """Test zwave add_node_secure service.""" self.hass.services.call('zwave', 'add_node_secure', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller.add_node.mock_calls) == 1 assert (self.zwave_network.controller .add_node.mock_calls[0][1][0] is True) def test_remove_node(self): """Test zwave remove_node service.""" self.hass.services.call('zwave', 'remove_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.remove_node.called assert len(self.zwave_network.controller.remove_node.mock_calls) == 1 def test_cancel_command(self): """Test zwave cancel_command service.""" self.hass.services.call('zwave', 'cancel_command', {}) self.hass.block_till_done() assert self.zwave_network.controller.cancel_command.called assert len(self.zwave_network.controller .cancel_command.mock_calls) == 1 def test_heal_network(self): """Test zwave heal_network service.""" self.hass.services.call('zwave', 'heal_network', {}) self.hass.block_till_done() assert self.zwave_network.heal.called assert len(self.zwave_network.heal.mock_calls) == 1 def test_soft_reset(self): """Test zwave soft_reset service.""" self.hass.services.call('zwave', 'soft_reset', {}) self.hass.block_till_done() assert self.zwave_network.controller.soft_reset.called assert len(self.zwave_network.controller.soft_reset.mock_calls) == 1 def test_test_network(self): """Test zwave test_network service.""" self.hass.services.call('zwave', 'test_network', {}) self.hass.block_till_done() assert self.zwave_network.test.called assert len(self.zwave_network.test.mock_calls) == 1 def test_stop_network(self): """Test zwave stop_network service.""" with patch.object(self.hass.bus, 'fire') as mock_fire: self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() assert self.zwave_network.stop.called assert len(self.zwave_network.stop.mock_calls) == 1 assert mock_fire.called assert len(mock_fire.mock_calls) == 1 assert mock_fire.mock_calls[0][1][0] == const.EVENT_NETWORK_STOP def test_rename_node(self): """Test zwave rename_node service.""" self.zwave_network.nodes = {11: MagicMock()} self.hass.services.call('zwave', 'rename_node', { const.ATTR_NODE_ID: 11, const.ATTR_NAME: 'test_name', }) self.hass.block_till_done() assert self.zwave_network.nodes[11].name == 'test_name' def test_rename_value(self): """Test zwave rename_value service.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, label="Old Label") node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.label == "Old Label" self.hass.services.call('zwave', 'rename_value', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_NAME: "New Label", }) self.hass.block_till_done() assert value.label == "New Label" def test_set_poll_intensity_enable(self): """Test zwave set_poll_intensity service, successful set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 2 assert enable_poll.mock_calls[0][1][0] == 4 def test_set_poll_intensity_enable_failed(self): """Test zwave set_poll_intensity service, failed set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) value.enable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 1 def test_set_poll_intensity_disable(self): """Test zwave set_poll_intensity service, successful disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 2 def test_set_poll_intensity_disable_failed(self): """Test zwave set_poll_intensity service, failed disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) value.disable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 1 def test_remove_failed_node(self): """Test zwave remove_failed_node service.""" self.hass.services.call('zwave', 'remove_failed_node', { const.ATTR_NODE_ID: 12, }) self.hass.block_till_done() remove_failed_node = self.zwave_network.controller.remove_failed_node assert remove_failed_node.called assert len(remove_failed_node.mock_calls) == 1 assert remove_failed_node.mock_calls[0][1][0] == 12 def test_replace_failed_node(self): """Test zwave replace_failed_node service.""" self.hass.services.call('zwave', 'replace_failed_node', { const.ATTR_NODE_ID: 13, }) self.hass.block_till_done() replace_failed_node = self.zwave_network.controller.replace_failed_node assert replace_failed_node.called assert len(replace_failed_node.mock_calls) == 1 assert replace_failed_node.mock_calls[0][1][0] == 13 def test_set_config_parameter(self): """Test zwave set_config_parameter service.""" value_byte = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BYTE, ) value_list = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['item1', 'item2', 'item3'], ) value_button = MockValue( index=14, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BUTTON, ) value_list_int = MockValue( index=15, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['1', '2', '3'], ) value_bool = MockValue( index=16, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BOOL, ) node = MockNode(node_id=14) node.get_values.return_value = { 12: value_byte, 13: value_list, 14: value_button, 15: value_list_int, 16: value_bool } self.zwave_network.nodes = {14: node} # Byte self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 12, const.ATTR_CONFIG_VALUE: 7, }) self.hass.block_till_done() assert value_byte.data == 7 # List self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, const.ATTR_CONFIG_VALUE: 'item3', }) self.hass.block_till_done() assert value_list.data == 'item3' # Button self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 14, const.ATTR_CONFIG_VALUE: True, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called assert self.zwave_network.manager.releaseButton.called # List of Ints self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 15, const.ATTR_CONFIG_VALUE: 3, }) self.hass.block_till_done() assert value_list_int.data == '3' # Boolean Truthy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'True', }) self.hass.block_till_done() assert value_bool.data == 1 # Boolean Falsy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'False', }) self.hass.block_till_done() assert value_bool.data == 0 # Different Parameter Size self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 19, const.ATTR_CONFIG_VALUE: 0x01020304, const.ATTR_CONFIG_SIZE: 4 }) self.hass.block_till_done() assert node.set_config_param.called assert len(node.set_config_param.mock_calls) == 1 assert node.set_config_param.mock_calls[0][1][0] == 19 assert node.set_config_param.mock_calls[0][1][1] == 0x01020304 assert node.set_config_param.mock_calls[0][1][2] == 4 node.set_config_param.reset_mock() def test_print_config_parameter(self): """Test zwave print_config_parameter service.""" value1 = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, data=1234, ) value2 = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, data=2345, ) node = MockNode(node_id=14) node.values = {12: value1, 13: value2} self.zwave_network.nodes = {14: node} with patch.object(zwave, '_LOGGER') as mock_logger: self.hass.services.call('zwave', 'print_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, }) self.hass.block_till_done() assert mock_logger.info.called assert len(mock_logger.info.mock_calls) == 1 assert mock_logger.info.mock_calls[0][1][1] == 13 assert mock_logger.info.mock_calls[0][1][2] == 14 assert mock_logger.info.mock_calls[0][1][3] == 2345 def test_print_node(self): """Test zwave print_node_parameter service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} with self.assertLogs(level='DEBUG') as mock_logger: self.hass.services.call('zwave', 'print_node', { const.ATTR_NODE_ID: 14 }) self.hass.block_till_done() assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 15, }) self.hass.block_till_done() assert value.data == 15 node.can_wake_up_value = False self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 20, }) self.hass.block_till_done() assert value.data == 15 def test_reset_node_meters(self): """Test zwave reset_node_meters service.""" value = MockValue( instance=1, index=8, data=99.5, command_class=const.COMMAND_CLASS_METER, ) reset_value = MockValue( instance=1, index=33, command_class=const.COMMAND_CLASS_METER, ) node = MockNode(node_id=14) node.values = {8: value, 33: reset_value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, const.ATTR_INSTANCE: 2, }) self.hass.block_till_done() assert not self.zwave_network.manager.pressButton.called assert not self.zwave_network.manager.releaseButton.called self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called value_id, = self.zwave_network.manager.pressButton.mock_calls.pop(0)[1] assert value_id == reset_value.value_id assert self.zwave_network.manager.releaseButton.called value_id, = ( self.zwave_network.manager.releaseButton.mock_calls.pop(0)[1]) assert value_id == reset_value.value_id def test_add_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'add', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.add_association.called assert len(group.add_association.mock_calls) == 1 assert group.add_association.mock_calls[0][1][0] == 24 assert group.add_association.mock_calls[0][1][1] == 5 def test_remove_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'remove', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.remove_association.called assert len(group.remove_association.mock_calls) == 1 assert group.remove_association.mock_calls[0][1][0] == 24 assert group.remove_association.mock_calls[0][1][1] == 5 def test_refresh_entity(self): """Test zwave refresh_entity service.""" node = MockNode() value = MockValue(data=False, node=node, command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50, node=node, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = get_device(node=node, values=values, node_config={}) device.hass = self.hass device.entity_id = 'binary_sensor.mock_entity_id' self.hass.add_job(device.async_added_to_hass()) self.hass.block_till_done() self.hass.services.call('zwave', 'refresh_entity', { ATTR_ENTITY_ID: 'binary_sensor.mock_entity_id', }) self.hass.block_till_done() assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 assert sorted([node.refresh_value.mock_calls[0][1][0], node.refresh_value.mock_calls[1][1][0]]) == \ sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert node.refresh_info.called assert len(node.refresh_info.mock_calls) == 1 def test_set_node_value(self): """Test zwave set_node_value service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=4 ) node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR]) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12, const.ATTR_CONFIG_VALUE: 2, }) self.hass.block_till_done() assert self.zwave_network.nodes[14].values[12].data == 2 def test_refresh_node_value(self): """Test zwave refresh_node_value service.""" node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR], network=self.zwave_network) value = MockValue( node=node, index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=2 ) value.refresh = MagicMock() node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12 }) self.hass.block_till_done() assert value.refresh.called def test_heal_node(self): """Test zwave heal_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'heal_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.heal.called assert len(node.heal.mock_calls) == 1 def test_test_node(self): """Test the zwave test_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'test_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.test.called assert len(node.test.mock_calls) == 1
jabesq/home-assistant
tests/components/zwave/test_init.py
homeassistant/components/oasa_telematics/sensor.py
"""Support turning on/off motion detection on Hikvision cameras.""" import logging import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_NAME, CONF_HOST, CONF_PASSWORD, CONF_USERNAME, CONF_PORT, STATE_OFF, STATE_ON) from homeassistant.helpers.entity import ToggleEntity import homeassistant.helpers.config_validation as cv # This is the last working version, please test before updating _LOGGING = logging.getLogger(__name__) DEFAULT_NAME = 'Hikvision Camera Motion Detection' DEFAULT_PASSWORD = '12345' DEFAULT_PORT = 80 DEFAULT_USERNAME = 'admin' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD, default=DEFAULT_PASSWORD): cv.string, vol.Optional(CONF_PORT): cv.port, vol.Optional(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up Hikvision camera.""" import hikvision.api from hikvision.error import HikvisionError, MissingParamError host = config.get(CONF_HOST) port = config.get(CONF_PORT) name = config.get(CONF_NAME) username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) try: hikvision_cam = hikvision.api.CreateDevice( host, port=port, username=username, password=password, is_https=False) except MissingParamError as param_err: _LOGGING.error("Missing required param: %s", param_err) return False except HikvisionError as conn_err: _LOGGING.error("Unable to connect: %s", conn_err) return False add_entities([HikvisionMotionSwitch(name, hikvision_cam)]) class HikvisionMotionSwitch(ToggleEntity): """Representation of a switch to toggle on/off motion detection.""" def __init__(self, name, hikvision_cam): """Initialize the switch.""" self._name = name self._hikvision_cam = hikvision_cam self._state = STATE_OFF @property def should_poll(self): """Poll for status regularly.""" return True @property def name(self): """Return the name of the device if any.""" return self._name @property def state(self): """Return the state of the device if any.""" return self._state @property def is_on(self): """Return true if device is on.""" return self._state == STATE_ON def turn_on(self, **kwargs): """Turn the device on.""" _LOGGING.info("Turning on Motion Detection ") self._hikvision_cam.enable_motion_detection() def turn_off(self, **kwargs): """Turn the device off.""" _LOGGING.info("Turning off Motion Detection ") self._hikvision_cam.disable_motion_detection() def update(self): """Update Motion Detection state.""" enabled = self._hikvision_cam.is_motion_detection_enabled() _LOGGING.info("enabled: %s", enabled) self._state = STATE_ON if enabled else STATE_OFF
"""Tests for the Z-Wave init.""" import asyncio from collections import OrderedDict from datetime import datetime import unittest from unittest.mock import MagicMock, patch import pytest from pytz import utc import voluptuous as vol from homeassistant.bootstrap import async_setup_component from homeassistant.components import zwave from homeassistant.components.zwave import ( CONF_DEVICE_CONFIG_GLOB, CONFIG_SCHEMA, DATA_NETWORK, const) from homeassistant.components.zwave.binary_sensor import get_device from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.device_registry import ( async_get_registry as get_dev_reg) from homeassistant.setup import setup_component from tests.common import ( async_fire_time_changed, get_test_home_assistant, mock_coro, mock_registry) from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue async def test_valid_device_config(hass, mock_openzwave): """Test valid device config.""" device_config = { 'light.kitchen': { 'ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert result async def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = { 'light.kitchen': { 'some_ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert not result def test_config_access_error(): """Test threading error accessing config values.""" node = MagicMock() def side_effect(): raise RuntimeError node.values.values.side_effect = side_effect result = zwave.get_config_value(node, 1) assert result is None async def test_network_options(hass, mock_openzwave): """Test network options.""" result = await async_setup_component(hass, 'zwave', { 'zwave': { 'usb_path': 'mock_usb_path', 'config_path': 'mock_config_path', }}) await hass.async_block_till_done() assert result network = hass.data[zwave.DATA_NETWORK] assert network.options.device == 'mock_usb_path' assert network.options.config_path == 'mock_config_path' async def test_network_key_validation(hass, mock_openzwave): """Test network key validation.""" test_values = [ ('0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,' '0x0E,0x0F,0x10'), ] for value in test_values: result = zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) assert result['zwave']['network_key'] == value async def test_erronous_network_key_fails_validation(hass, mock_openzwave): """Test failing erronous network key validation.""" test_values = [ ('0x 01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0X01,0X02,0X03,0X04,0X05,0X06,0X07,0X08,0X09,0X0A,0X0B,0X0C,0X0D,' '0X0E,0X0F,0X10'), 'invalid', '1234567', 1234567 ] for value in test_values: with pytest.raises(vol.Invalid): zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) async def test_auto_heal_midnight(hass, mock_openzwave): """Test network auto-heal at midnight.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': True, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert network.heal.called assert len(network.heal.mock_calls) == 1 async def test_auto_heal_disabled(hass, mock_openzwave): """Test network auto-heal disabled.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': False, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert not network.heal.called async def test_setup_platform(hass, mock_openzwave): """Test invalid device config.""" mock_device = MagicMock() hass.data[DATA_NETWORK] = MagicMock() hass.data[zwave.DATA_DEVICES] = {456: mock_device} async_add_entities = MagicMock() result = await zwave.async_setup_platform( hass, None, async_add_entities, None) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 123}) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 456}) assert result assert async_add_entities.called assert len(async_add_entities.mock_calls) == 1 assert async_add_entities.mock_calls[0][1][0] == [mock_device] async def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): """Test device entity base class.""" node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.value_added() device.update_properties() await hass.async_block_till_done() assert not device.should_poll assert device.unique_id == "10-11" assert device.name == 'Mock Node Sensor' assert device.device_state_attributes[zwave.ATTR_POWER] == 50.123 async def test_node_removed(hass, mock_openzwave): """Test node removed in base class.""" # Create a mock node & node entity node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.entity_id = 'zwave.mock_node' device.value_added() device.update_properties() await hass.async_block_till_done() # Save it to the entity registry registry = mock_registry(hass) registry.async_get_or_create('zwave', 'zwave', device.unique_id) device.entity_id = registry.async_get_entity_id( 'zwave', 'zwave', device.unique_id) # Create dummy entity registry entries for other integrations hue_entity = registry.async_get_or_create('light', 'hue', 1234) zha_entity = registry.async_get_or_create('sensor', 'zha', 5678) # Verify our Z-Wave entity is registered assert registry.async_is_registered(device.entity_id) # Remove it entity_id = device.entity_id await device.node_removed() # Verify registry entry for our Z-Wave node is gone assert not registry.async_is_registered(entity_id) # Verify registry entries for our other entities remain assert registry.async_is_registered(hue_entity.entity_id) assert registry.async_is_registered(zha_entity.entity_id) async def test_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node').state == 'unknown' async def test_unparsed_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode( node_id=14, manufacturer_name=None, name=None, is_ready=False) sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert len(sleeps) == const.NODE_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1:] == \ (14, const.NODE_READY_WAIT_SECS) assert hass.states.get('zwave.unknown_node_14').state == 'unknown' async def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': { 'device_config': { 'zwave.mock_node': { 'ignored': True, }}}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None async def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' async def test_value_entities(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = {} def mock_connect(receiver, signal, *args, **kwargs): mock_receivers[signal] = receiver with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert mock_receivers hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_ALL_NODES_QUERIED]) node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) zwave_network.nodes = {node.node_id: node} value = MockValue( data=False, node=node, index=12, instance=1, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values = {'primary': value, value.value_id: value} value2 = MockValue( data=False, node=node, index=12, instance=2, label="Mock Value B", command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values[value2.value_id] = value2 hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_NODE_ADDED], node) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value2) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' assert hass.states.get( 'binary_sensor.mock_node_mock_value_b').state == 'off' ent_reg = await async_get_registry(hass) dev_reg = await get_dev_reg(hass) entry = ent_reg.async_get('zwave.mock_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) node_dev_id = entry.device_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) assert entry.name is None assert entry.device_id == node_dev_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value2.object_id) assert entry.name is None assert entry.device_id != node_dev_id device_id_b = entry.device_id device = dev_reg.async_get(node_dev_id) assert device is not None assert device.name == node.name old_device = device device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming without updating await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_NAME: "Demo Node", }) await hass.async_block_till_done() assert node.name == "Demo Node" entry = ent_reg.async_get('zwave.mock_node') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Node", }) await hass.async_block_till_done() assert node.name == "New Node" entry = ent_reg.async_get('zwave.new_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) entry = ent_reg.async_get('binary_sensor.new_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) await hass.services.async_call('zwave', 'rename_value', { const.ATTR_NODE_ID: node.node_id, const.ATTR_VALUE_ID: value.object_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Label", }) await hass.async_block_till_done() entry = ent_reg.async_get('binary_sensor.new_node_new_label') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) async def test_value_discovery_existing_entity(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_THERMOSTAT) setpoint = MockValue( data=22.0, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, setpoint) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] is None def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): temperature = MockValue( data=23.5, node=node, index=1, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, temperature) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] == 23.5 async def test_power_schemes(hass, mock_openzwave): """Test power attribute.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SWITCH_BINARY) switch = MockValue( data=True, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SWITCH_BINARY, genre=const.GENRE_USER, type=const.TYPE_BOOL) hass.async_add_job(mock_receivers[0], node, switch) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').state == 'on' assert 'power_consumption' not in hass.states.get( 'switch.mock_node_mock_value').attributes def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): power = MockValue( data=23.5, node=node, index=const.INDEX_SENSOR_MULTILEVEL_POWER, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL) hass.async_add_job(mock_receivers[0], node, power) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').attributes[ 'power_consumption'] == 23.5 async def test_network_ready(hass, mock_openzwave): """Test Node network ready event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete_some_dead(hass, mock_openzwave): """Test Node network complete some dead event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE_SOME_DEAD, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 class TestZWaveDeviceEntityValues(unittest.TestCase): """Tests for the ZWaveDeviceEntityValues helper.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() self.registry = mock_registry(self.hass) setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.node = MockNode() self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: ['mock_primary_class'], }, 'secondary': { const.DISC_COMMAND_CLASS: ['mock_secondary_class'], }, 'optional': { const.DISC_COMMAND_CLASS: ['mock_optional_class'], const.DISC_OPTIONAL: True, }}} self.primary = MockValue( command_class='mock_primary_class', node=self.node, value_id=1000) self.secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.duplicate_secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.optional = MockValue( command_class='mock_optional_class', node=self.node) self.no_match_value = MockValue( command_class='mock_bad_class', node=self.node) self.entity_id = 'mock_component.mock_node_mock_value' self.zwave_config = {'zwave': {}} self.device_config = {self.entity_id: {}} def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) assert values.primary is self.primary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) self.hass.block_till_done() assert values.secondary is self.secondary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config discovery.async_load_platform.reset_mock() values.check_value(self.optional) values.check_value(self.duplicate_secondary) values.check_value(self.no_match_value) self.hass.block_till_done() assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called assert len(values._entity.value_added.mock_calls) == 1 assert values._entity.value_changed.called assert len(values._entity.value_changed.mock_calls) == 1 @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, self.optional.value_id: self.optional, self.no_match_value.value_id: self.no_match_value, } values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert values.primary is self.primary assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config assert not self.primary.enable_poll.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_node_schema_mismatch(self, discovery, import_module): """Test node schema mismatch.""" self.node.generic = 'no_match' self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.mock_schema[const.DISC_GENERIC_DEVICE_CLASS] = ['generic_match'] values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.manufacturer_id = '010f' self.node.product_type = '0b00' self.primary.command_class = const.COMMAND_CLASS_SENSOR_ALARM self.entity_id = 'binary_sensor.mock_node_mock_value' self.device_config = {self.entity_id: {}} self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} with patch.object(zwave, 'async_dispatcher_send') as \ mock_dispatch_send: values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert mock_dispatch_send.called assert len(mock_dispatch_send.mock_calls) == 1 args = mock_dispatch_send.mock_calls[0][1] assert args[1] == 'zwave_new_binary_sensor' @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_ignore(self, discovery, import_module): """Test ignore workaround.""" self.node.manufacturer_id = '010f' self.node.product_type = '0301' self.primary.command_class = const.COMMAND_CLASS_SWITCH_BINARY self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore(self, discovery, import_module): """Test ignore config.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_IGNORED: True }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore_with_registry(self, discovery, import_module): """Test ignore config. The case when the device is in entity registry. """ self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {'mock_component.registry_id': { zwave.CONF_IGNORED: True }} with patch.object(self.registry, 'async_schedule_save'): self.registry.async_get_or_create( 'mock_component', zwave.DOMAIN, '567-1000', suggested_object_id='registry_id') zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_platform_ignore(self, discovery, import_module): """Test platform ignore device.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } platform = MagicMock() import_module.return_value = platform platform.get_device.return_value = None zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_config_polling_intensity(self, discovery, import_module): """Test polling intensity.""" mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_POLLING_INTENSITY: 123, }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert discovery.async_load_platform.called assert self.primary.enable_poll.called assert len(self.primary.enable_poll.mock_calls) == 1 assert self.primary.enable_poll.mock_calls[0][1][0] == 123 class TestZwave(unittest.TestCase): """Test zwave init.""" def test_device_config_glob_is_ordered(self): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): """Tests for zwave services.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() # Initialize zwave setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.zwave_network = self.hass.data[DATA_NETWORK] self.zwave_network.state = MockNetwork.STATE_READY self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.block_till_done() def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() self.hass.stop() def test_add_node(self): """Test zwave add_node service.""" self.hass.services.call('zwave', 'add_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller .add_node.mock_calls) == 1 assert len(self.zwave_network.controller .add_node.mock_calls[0][1]) == 0 def test_add_node_secure(self): """Test zwave add_node_secure service.""" self.hass.services.call('zwave', 'add_node_secure', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller.add_node.mock_calls) == 1 assert (self.zwave_network.controller .add_node.mock_calls[0][1][0] is True) def test_remove_node(self): """Test zwave remove_node service.""" self.hass.services.call('zwave', 'remove_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.remove_node.called assert len(self.zwave_network.controller.remove_node.mock_calls) == 1 def test_cancel_command(self): """Test zwave cancel_command service.""" self.hass.services.call('zwave', 'cancel_command', {}) self.hass.block_till_done() assert self.zwave_network.controller.cancel_command.called assert len(self.zwave_network.controller .cancel_command.mock_calls) == 1 def test_heal_network(self): """Test zwave heal_network service.""" self.hass.services.call('zwave', 'heal_network', {}) self.hass.block_till_done() assert self.zwave_network.heal.called assert len(self.zwave_network.heal.mock_calls) == 1 def test_soft_reset(self): """Test zwave soft_reset service.""" self.hass.services.call('zwave', 'soft_reset', {}) self.hass.block_till_done() assert self.zwave_network.controller.soft_reset.called assert len(self.zwave_network.controller.soft_reset.mock_calls) == 1 def test_test_network(self): """Test zwave test_network service.""" self.hass.services.call('zwave', 'test_network', {}) self.hass.block_till_done() assert self.zwave_network.test.called assert len(self.zwave_network.test.mock_calls) == 1 def test_stop_network(self): """Test zwave stop_network service.""" with patch.object(self.hass.bus, 'fire') as mock_fire: self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() assert self.zwave_network.stop.called assert len(self.zwave_network.stop.mock_calls) == 1 assert mock_fire.called assert len(mock_fire.mock_calls) == 1 assert mock_fire.mock_calls[0][1][0] == const.EVENT_NETWORK_STOP def test_rename_node(self): """Test zwave rename_node service.""" self.zwave_network.nodes = {11: MagicMock()} self.hass.services.call('zwave', 'rename_node', { const.ATTR_NODE_ID: 11, const.ATTR_NAME: 'test_name', }) self.hass.block_till_done() assert self.zwave_network.nodes[11].name == 'test_name' def test_rename_value(self): """Test zwave rename_value service.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, label="Old Label") node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.label == "Old Label" self.hass.services.call('zwave', 'rename_value', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_NAME: "New Label", }) self.hass.block_till_done() assert value.label == "New Label" def test_set_poll_intensity_enable(self): """Test zwave set_poll_intensity service, successful set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 2 assert enable_poll.mock_calls[0][1][0] == 4 def test_set_poll_intensity_enable_failed(self): """Test zwave set_poll_intensity service, failed set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) value.enable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 1 def test_set_poll_intensity_disable(self): """Test zwave set_poll_intensity service, successful disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 2 def test_set_poll_intensity_disable_failed(self): """Test zwave set_poll_intensity service, failed disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) value.disable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 1 def test_remove_failed_node(self): """Test zwave remove_failed_node service.""" self.hass.services.call('zwave', 'remove_failed_node', { const.ATTR_NODE_ID: 12, }) self.hass.block_till_done() remove_failed_node = self.zwave_network.controller.remove_failed_node assert remove_failed_node.called assert len(remove_failed_node.mock_calls) == 1 assert remove_failed_node.mock_calls[0][1][0] == 12 def test_replace_failed_node(self): """Test zwave replace_failed_node service.""" self.hass.services.call('zwave', 'replace_failed_node', { const.ATTR_NODE_ID: 13, }) self.hass.block_till_done() replace_failed_node = self.zwave_network.controller.replace_failed_node assert replace_failed_node.called assert len(replace_failed_node.mock_calls) == 1 assert replace_failed_node.mock_calls[0][1][0] == 13 def test_set_config_parameter(self): """Test zwave set_config_parameter service.""" value_byte = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BYTE, ) value_list = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['item1', 'item2', 'item3'], ) value_button = MockValue( index=14, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BUTTON, ) value_list_int = MockValue( index=15, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['1', '2', '3'], ) value_bool = MockValue( index=16, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BOOL, ) node = MockNode(node_id=14) node.get_values.return_value = { 12: value_byte, 13: value_list, 14: value_button, 15: value_list_int, 16: value_bool } self.zwave_network.nodes = {14: node} # Byte self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 12, const.ATTR_CONFIG_VALUE: 7, }) self.hass.block_till_done() assert value_byte.data == 7 # List self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, const.ATTR_CONFIG_VALUE: 'item3', }) self.hass.block_till_done() assert value_list.data == 'item3' # Button self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 14, const.ATTR_CONFIG_VALUE: True, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called assert self.zwave_network.manager.releaseButton.called # List of Ints self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 15, const.ATTR_CONFIG_VALUE: 3, }) self.hass.block_till_done() assert value_list_int.data == '3' # Boolean Truthy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'True', }) self.hass.block_till_done() assert value_bool.data == 1 # Boolean Falsy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'False', }) self.hass.block_till_done() assert value_bool.data == 0 # Different Parameter Size self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 19, const.ATTR_CONFIG_VALUE: 0x01020304, const.ATTR_CONFIG_SIZE: 4 }) self.hass.block_till_done() assert node.set_config_param.called assert len(node.set_config_param.mock_calls) == 1 assert node.set_config_param.mock_calls[0][1][0] == 19 assert node.set_config_param.mock_calls[0][1][1] == 0x01020304 assert node.set_config_param.mock_calls[0][1][2] == 4 node.set_config_param.reset_mock() def test_print_config_parameter(self): """Test zwave print_config_parameter service.""" value1 = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, data=1234, ) value2 = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, data=2345, ) node = MockNode(node_id=14) node.values = {12: value1, 13: value2} self.zwave_network.nodes = {14: node} with patch.object(zwave, '_LOGGER') as mock_logger: self.hass.services.call('zwave', 'print_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, }) self.hass.block_till_done() assert mock_logger.info.called assert len(mock_logger.info.mock_calls) == 1 assert mock_logger.info.mock_calls[0][1][1] == 13 assert mock_logger.info.mock_calls[0][1][2] == 14 assert mock_logger.info.mock_calls[0][1][3] == 2345 def test_print_node(self): """Test zwave print_node_parameter service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} with self.assertLogs(level='DEBUG') as mock_logger: self.hass.services.call('zwave', 'print_node', { const.ATTR_NODE_ID: 14 }) self.hass.block_till_done() assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 15, }) self.hass.block_till_done() assert value.data == 15 node.can_wake_up_value = False self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 20, }) self.hass.block_till_done() assert value.data == 15 def test_reset_node_meters(self): """Test zwave reset_node_meters service.""" value = MockValue( instance=1, index=8, data=99.5, command_class=const.COMMAND_CLASS_METER, ) reset_value = MockValue( instance=1, index=33, command_class=const.COMMAND_CLASS_METER, ) node = MockNode(node_id=14) node.values = {8: value, 33: reset_value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, const.ATTR_INSTANCE: 2, }) self.hass.block_till_done() assert not self.zwave_network.manager.pressButton.called assert not self.zwave_network.manager.releaseButton.called self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called value_id, = self.zwave_network.manager.pressButton.mock_calls.pop(0)[1] assert value_id == reset_value.value_id assert self.zwave_network.manager.releaseButton.called value_id, = ( self.zwave_network.manager.releaseButton.mock_calls.pop(0)[1]) assert value_id == reset_value.value_id def test_add_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'add', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.add_association.called assert len(group.add_association.mock_calls) == 1 assert group.add_association.mock_calls[0][1][0] == 24 assert group.add_association.mock_calls[0][1][1] == 5 def test_remove_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'remove', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.remove_association.called assert len(group.remove_association.mock_calls) == 1 assert group.remove_association.mock_calls[0][1][0] == 24 assert group.remove_association.mock_calls[0][1][1] == 5 def test_refresh_entity(self): """Test zwave refresh_entity service.""" node = MockNode() value = MockValue(data=False, node=node, command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50, node=node, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = get_device(node=node, values=values, node_config={}) device.hass = self.hass device.entity_id = 'binary_sensor.mock_entity_id' self.hass.add_job(device.async_added_to_hass()) self.hass.block_till_done() self.hass.services.call('zwave', 'refresh_entity', { ATTR_ENTITY_ID: 'binary_sensor.mock_entity_id', }) self.hass.block_till_done() assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 assert sorted([node.refresh_value.mock_calls[0][1][0], node.refresh_value.mock_calls[1][1][0]]) == \ sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert node.refresh_info.called assert len(node.refresh_info.mock_calls) == 1 def test_set_node_value(self): """Test zwave set_node_value service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=4 ) node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR]) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12, const.ATTR_CONFIG_VALUE: 2, }) self.hass.block_till_done() assert self.zwave_network.nodes[14].values[12].data == 2 def test_refresh_node_value(self): """Test zwave refresh_node_value service.""" node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR], network=self.zwave_network) value = MockValue( node=node, index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=2 ) value.refresh = MagicMock() node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12 }) self.hass.block_till_done() assert value.refresh.called def test_heal_node(self): """Test zwave heal_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'heal_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.heal.called assert len(node.heal.mock_calls) == 1 def test_test_node(self): """Test the zwave test_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'test_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.test.called assert len(node.test.mock_calls) == 1
jabesq/home-assistant
tests/components/zwave/test_init.py
homeassistant/components/hikvisioncam/switch.py
"""Each ElkM1 area will be created as a separate alarm_control_panel.""" import voluptuous as vol import homeassistant.components.alarm_control_panel as alarm from homeassistant.const import ( ATTR_CODE, ATTR_ENTITY_ID, STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, STATE_ALARM_ARMED_NIGHT, STATE_ALARM_ARMING, STATE_ALARM_DISARMED, STATE_ALARM_PENDING, STATE_ALARM_TRIGGERED) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import ( async_dispatcher_connect, async_dispatcher_send) from . import DOMAIN as ELK_DOMAIN, ElkEntity, create_elk_entities SIGNAL_ARM_ENTITY = 'elkm1_arm' SIGNAL_DISPLAY_MESSAGE = 'elkm1_display_message' ELK_ALARM_SERVICE_SCHEMA = vol.Schema({ vol.Required(ATTR_ENTITY_ID, default=[]): cv.entity_ids, vol.Required(ATTR_CODE): vol.All(vol.Coerce(int), vol.Range(0, 999999)), }) DISPLAY_MESSAGE_SERVICE_SCHEMA = vol.Schema({ vol.Optional(ATTR_ENTITY_ID, default=[]): cv.entity_ids, vol.Optional('clear', default=2): vol.In([0, 1, 2]), vol.Optional('beep', default=False): cv.boolean, vol.Optional('timeout', default=0): vol.Range(min=0, max=65535), vol.Optional('line1', default=''): cv.string, vol.Optional('line2', default=''): cv.string, }) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the ElkM1 alarm platform.""" if discovery_info is None: return elk = hass.data[ELK_DOMAIN]['elk'] entities = create_elk_entities(hass, elk.areas, 'area', ElkArea, []) async_add_entities(entities, True) def _dispatch(signal, entity_ids, *args): for entity_id in entity_ids: async_dispatcher_send( hass, '{}_{}'.format(signal, entity_id), *args) def _arm_service(service): entity_ids = service.data.get(ATTR_ENTITY_ID, []) arm_level = _arm_services().get(service.service) args = (arm_level, service.data.get(ATTR_CODE)) _dispatch(SIGNAL_ARM_ENTITY, entity_ids, *args) for service in _arm_services(): hass.services.async_register( alarm.DOMAIN, service, _arm_service, ELK_ALARM_SERVICE_SCHEMA) def _display_message_service(service): entity_ids = service.data.get(ATTR_ENTITY_ID, []) data = service.data args = (data['clear'], data['beep'], data['timeout'], data['line1'], data['line2']) _dispatch(SIGNAL_DISPLAY_MESSAGE, entity_ids, *args) hass.services.async_register( alarm.DOMAIN, 'elkm1_alarm_display_message', _display_message_service, DISPLAY_MESSAGE_SERVICE_SCHEMA) def _arm_services(): from elkm1_lib.const import ArmLevel return { 'elkm1_alarm_arm_vacation': ArmLevel.ARMED_VACATION.value, 'elkm1_alarm_arm_home_instant': ArmLevel.ARMED_STAY_INSTANT.value, 'elkm1_alarm_arm_night_instant': ArmLevel.ARMED_NIGHT_INSTANT.value, } class ElkArea(ElkEntity, alarm.AlarmControlPanel): """Representation of an Area / Partition within the ElkM1 alarm panel.""" def __init__(self, element, elk, elk_data): """Initialize Area as Alarm Control Panel.""" super().__init__(element, elk, elk_data) self._changed_by_entity_id = '' self._state = None async def async_added_to_hass(self): """Register callback for ElkM1 changes.""" await super().async_added_to_hass() for keypad in self._elk.keypads: keypad.add_callback(self._watch_keypad) async_dispatcher_connect( self.hass, '{}_{}'.format(SIGNAL_ARM_ENTITY, self.entity_id), self._arm_service) async_dispatcher_connect( self.hass, '{}_{}'.format(SIGNAL_DISPLAY_MESSAGE, self.entity_id), self._display_message) def _watch_keypad(self, keypad, changeset): if keypad.area != self._element.index: return if changeset.get('last_user') is not None: self._changed_by_entity_id = self.hass.data[ ELK_DOMAIN]['keypads'].get(keypad.index, '') self.async_schedule_update_ha_state(True) @property def code_format(self): """Return the alarm code format.""" return alarm.FORMAT_NUMBER @property def state(self): """Return the state of the element.""" return self._state @property def device_state_attributes(self): """Attributes of the area.""" from elkm1_lib.const import AlarmState, ArmedStatus, ArmUpState attrs = self.initial_attrs() elmt = self._element attrs['is_exit'] = elmt.is_exit attrs['timer1'] = elmt.timer1 attrs['timer2'] = elmt.timer2 if elmt.armed_status is not None: attrs['armed_status'] = \ ArmedStatus(elmt.armed_status).name.lower() if elmt.arm_up_state is not None: attrs['arm_up_state'] = ArmUpState(elmt.arm_up_state).name.lower() if elmt.alarm_state is not None: attrs['alarm_state'] = AlarmState(elmt.alarm_state).name.lower() attrs['changed_by_entity_id'] = self._changed_by_entity_id return attrs def _element_changed(self, element, changeset): from elkm1_lib.const import ArmedStatus elk_state_to_hass_state = { ArmedStatus.DISARMED.value: STATE_ALARM_DISARMED, ArmedStatus.ARMED_AWAY.value: STATE_ALARM_ARMED_AWAY, ArmedStatus.ARMED_STAY.value: STATE_ALARM_ARMED_HOME, ArmedStatus.ARMED_STAY_INSTANT.value: STATE_ALARM_ARMED_HOME, ArmedStatus.ARMED_TO_NIGHT.value: STATE_ALARM_ARMED_NIGHT, ArmedStatus.ARMED_TO_NIGHT_INSTANT.value: STATE_ALARM_ARMED_NIGHT, ArmedStatus.ARMED_TO_VACATION.value: STATE_ALARM_ARMED_AWAY, } if self._element.alarm_state is None: self._state = None elif self._area_is_in_alarm_state(): self._state = STATE_ALARM_TRIGGERED elif self._entry_exit_timer_is_running(): self._state = STATE_ALARM_ARMING \ if self._element.is_exit else STATE_ALARM_PENDING else: self._state = elk_state_to_hass_state[self._element.armed_status] def _entry_exit_timer_is_running(self): return self._element.timer1 > 0 or self._element.timer2 > 0 def _area_is_in_alarm_state(self): from elkm1_lib.const import AlarmState return self._element.alarm_state >= AlarmState.FIRE_ALARM.value async def async_alarm_disarm(self, code=None): """Send disarm command.""" self._element.disarm(int(code)) async def async_alarm_arm_home(self, code=None): """Send arm home command.""" from elkm1_lib.const import ArmLevel self._element.arm(ArmLevel.ARMED_STAY.value, int(code)) async def async_alarm_arm_away(self, code=None): """Send arm away command.""" from elkm1_lib.const import ArmLevel self._element.arm(ArmLevel.ARMED_AWAY.value, int(code)) async def async_alarm_arm_night(self, code=None): """Send arm night command.""" from elkm1_lib.const import ArmLevel self._element.arm(ArmLevel.ARMED_NIGHT.value, int(code)) async def _arm_service(self, arm_level, code): self._element.arm(arm_level, code) async def _display_message(self, clear, beep, timeout, line1, line2): """Display a message on all keypads for the area.""" self._element.display_message(clear, beep, timeout, line1, line2)
"""Tests for the Z-Wave init.""" import asyncio from collections import OrderedDict from datetime import datetime import unittest from unittest.mock import MagicMock, patch import pytest from pytz import utc import voluptuous as vol from homeassistant.bootstrap import async_setup_component from homeassistant.components import zwave from homeassistant.components.zwave import ( CONF_DEVICE_CONFIG_GLOB, CONFIG_SCHEMA, DATA_NETWORK, const) from homeassistant.components.zwave.binary_sensor import get_device from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.device_registry import ( async_get_registry as get_dev_reg) from homeassistant.setup import setup_component from tests.common import ( async_fire_time_changed, get_test_home_assistant, mock_coro, mock_registry) from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue async def test_valid_device_config(hass, mock_openzwave): """Test valid device config.""" device_config = { 'light.kitchen': { 'ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert result async def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = { 'light.kitchen': { 'some_ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert not result def test_config_access_error(): """Test threading error accessing config values.""" node = MagicMock() def side_effect(): raise RuntimeError node.values.values.side_effect = side_effect result = zwave.get_config_value(node, 1) assert result is None async def test_network_options(hass, mock_openzwave): """Test network options.""" result = await async_setup_component(hass, 'zwave', { 'zwave': { 'usb_path': 'mock_usb_path', 'config_path': 'mock_config_path', }}) await hass.async_block_till_done() assert result network = hass.data[zwave.DATA_NETWORK] assert network.options.device == 'mock_usb_path' assert network.options.config_path == 'mock_config_path' async def test_network_key_validation(hass, mock_openzwave): """Test network key validation.""" test_values = [ ('0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,' '0x0E,0x0F,0x10'), ] for value in test_values: result = zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) assert result['zwave']['network_key'] == value async def test_erronous_network_key_fails_validation(hass, mock_openzwave): """Test failing erronous network key validation.""" test_values = [ ('0x 01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0X01,0X02,0X03,0X04,0X05,0X06,0X07,0X08,0X09,0X0A,0X0B,0X0C,0X0D,' '0X0E,0X0F,0X10'), 'invalid', '1234567', 1234567 ] for value in test_values: with pytest.raises(vol.Invalid): zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) async def test_auto_heal_midnight(hass, mock_openzwave): """Test network auto-heal at midnight.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': True, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert network.heal.called assert len(network.heal.mock_calls) == 1 async def test_auto_heal_disabled(hass, mock_openzwave): """Test network auto-heal disabled.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': False, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert not network.heal.called async def test_setup_platform(hass, mock_openzwave): """Test invalid device config.""" mock_device = MagicMock() hass.data[DATA_NETWORK] = MagicMock() hass.data[zwave.DATA_DEVICES] = {456: mock_device} async_add_entities = MagicMock() result = await zwave.async_setup_platform( hass, None, async_add_entities, None) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 123}) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 456}) assert result assert async_add_entities.called assert len(async_add_entities.mock_calls) == 1 assert async_add_entities.mock_calls[0][1][0] == [mock_device] async def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): """Test device entity base class.""" node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.value_added() device.update_properties() await hass.async_block_till_done() assert not device.should_poll assert device.unique_id == "10-11" assert device.name == 'Mock Node Sensor' assert device.device_state_attributes[zwave.ATTR_POWER] == 50.123 async def test_node_removed(hass, mock_openzwave): """Test node removed in base class.""" # Create a mock node & node entity node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.entity_id = 'zwave.mock_node' device.value_added() device.update_properties() await hass.async_block_till_done() # Save it to the entity registry registry = mock_registry(hass) registry.async_get_or_create('zwave', 'zwave', device.unique_id) device.entity_id = registry.async_get_entity_id( 'zwave', 'zwave', device.unique_id) # Create dummy entity registry entries for other integrations hue_entity = registry.async_get_or_create('light', 'hue', 1234) zha_entity = registry.async_get_or_create('sensor', 'zha', 5678) # Verify our Z-Wave entity is registered assert registry.async_is_registered(device.entity_id) # Remove it entity_id = device.entity_id await device.node_removed() # Verify registry entry for our Z-Wave node is gone assert not registry.async_is_registered(entity_id) # Verify registry entries for our other entities remain assert registry.async_is_registered(hue_entity.entity_id) assert registry.async_is_registered(zha_entity.entity_id) async def test_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node').state == 'unknown' async def test_unparsed_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode( node_id=14, manufacturer_name=None, name=None, is_ready=False) sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert len(sleeps) == const.NODE_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1:] == \ (14, const.NODE_READY_WAIT_SECS) assert hass.states.get('zwave.unknown_node_14').state == 'unknown' async def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': { 'device_config': { 'zwave.mock_node': { 'ignored': True, }}}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None async def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' async def test_value_entities(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = {} def mock_connect(receiver, signal, *args, **kwargs): mock_receivers[signal] = receiver with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert mock_receivers hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_ALL_NODES_QUERIED]) node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) zwave_network.nodes = {node.node_id: node} value = MockValue( data=False, node=node, index=12, instance=1, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values = {'primary': value, value.value_id: value} value2 = MockValue( data=False, node=node, index=12, instance=2, label="Mock Value B", command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values[value2.value_id] = value2 hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_NODE_ADDED], node) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value2) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' assert hass.states.get( 'binary_sensor.mock_node_mock_value_b').state == 'off' ent_reg = await async_get_registry(hass) dev_reg = await get_dev_reg(hass) entry = ent_reg.async_get('zwave.mock_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) node_dev_id = entry.device_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) assert entry.name is None assert entry.device_id == node_dev_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value2.object_id) assert entry.name is None assert entry.device_id != node_dev_id device_id_b = entry.device_id device = dev_reg.async_get(node_dev_id) assert device is not None assert device.name == node.name old_device = device device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming without updating await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_NAME: "Demo Node", }) await hass.async_block_till_done() assert node.name == "Demo Node" entry = ent_reg.async_get('zwave.mock_node') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Node", }) await hass.async_block_till_done() assert node.name == "New Node" entry = ent_reg.async_get('zwave.new_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) entry = ent_reg.async_get('binary_sensor.new_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) await hass.services.async_call('zwave', 'rename_value', { const.ATTR_NODE_ID: node.node_id, const.ATTR_VALUE_ID: value.object_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Label", }) await hass.async_block_till_done() entry = ent_reg.async_get('binary_sensor.new_node_new_label') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) async def test_value_discovery_existing_entity(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_THERMOSTAT) setpoint = MockValue( data=22.0, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, setpoint) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] is None def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): temperature = MockValue( data=23.5, node=node, index=1, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, temperature) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] == 23.5 async def test_power_schemes(hass, mock_openzwave): """Test power attribute.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SWITCH_BINARY) switch = MockValue( data=True, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SWITCH_BINARY, genre=const.GENRE_USER, type=const.TYPE_BOOL) hass.async_add_job(mock_receivers[0], node, switch) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').state == 'on' assert 'power_consumption' not in hass.states.get( 'switch.mock_node_mock_value').attributes def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): power = MockValue( data=23.5, node=node, index=const.INDEX_SENSOR_MULTILEVEL_POWER, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL) hass.async_add_job(mock_receivers[0], node, power) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').attributes[ 'power_consumption'] == 23.5 async def test_network_ready(hass, mock_openzwave): """Test Node network ready event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete_some_dead(hass, mock_openzwave): """Test Node network complete some dead event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE_SOME_DEAD, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 class TestZWaveDeviceEntityValues(unittest.TestCase): """Tests for the ZWaveDeviceEntityValues helper.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() self.registry = mock_registry(self.hass) setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.node = MockNode() self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: ['mock_primary_class'], }, 'secondary': { const.DISC_COMMAND_CLASS: ['mock_secondary_class'], }, 'optional': { const.DISC_COMMAND_CLASS: ['mock_optional_class'], const.DISC_OPTIONAL: True, }}} self.primary = MockValue( command_class='mock_primary_class', node=self.node, value_id=1000) self.secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.duplicate_secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.optional = MockValue( command_class='mock_optional_class', node=self.node) self.no_match_value = MockValue( command_class='mock_bad_class', node=self.node) self.entity_id = 'mock_component.mock_node_mock_value' self.zwave_config = {'zwave': {}} self.device_config = {self.entity_id: {}} def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) assert values.primary is self.primary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) self.hass.block_till_done() assert values.secondary is self.secondary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config discovery.async_load_platform.reset_mock() values.check_value(self.optional) values.check_value(self.duplicate_secondary) values.check_value(self.no_match_value) self.hass.block_till_done() assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called assert len(values._entity.value_added.mock_calls) == 1 assert values._entity.value_changed.called assert len(values._entity.value_changed.mock_calls) == 1 @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, self.optional.value_id: self.optional, self.no_match_value.value_id: self.no_match_value, } values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert values.primary is self.primary assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config assert not self.primary.enable_poll.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_node_schema_mismatch(self, discovery, import_module): """Test node schema mismatch.""" self.node.generic = 'no_match' self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.mock_schema[const.DISC_GENERIC_DEVICE_CLASS] = ['generic_match'] values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.manufacturer_id = '010f' self.node.product_type = '0b00' self.primary.command_class = const.COMMAND_CLASS_SENSOR_ALARM self.entity_id = 'binary_sensor.mock_node_mock_value' self.device_config = {self.entity_id: {}} self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} with patch.object(zwave, 'async_dispatcher_send') as \ mock_dispatch_send: values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert mock_dispatch_send.called assert len(mock_dispatch_send.mock_calls) == 1 args = mock_dispatch_send.mock_calls[0][1] assert args[1] == 'zwave_new_binary_sensor' @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_ignore(self, discovery, import_module): """Test ignore workaround.""" self.node.manufacturer_id = '010f' self.node.product_type = '0301' self.primary.command_class = const.COMMAND_CLASS_SWITCH_BINARY self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore(self, discovery, import_module): """Test ignore config.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_IGNORED: True }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore_with_registry(self, discovery, import_module): """Test ignore config. The case when the device is in entity registry. """ self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {'mock_component.registry_id': { zwave.CONF_IGNORED: True }} with patch.object(self.registry, 'async_schedule_save'): self.registry.async_get_or_create( 'mock_component', zwave.DOMAIN, '567-1000', suggested_object_id='registry_id') zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_platform_ignore(self, discovery, import_module): """Test platform ignore device.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } platform = MagicMock() import_module.return_value = platform platform.get_device.return_value = None zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_config_polling_intensity(self, discovery, import_module): """Test polling intensity.""" mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_POLLING_INTENSITY: 123, }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert discovery.async_load_platform.called assert self.primary.enable_poll.called assert len(self.primary.enable_poll.mock_calls) == 1 assert self.primary.enable_poll.mock_calls[0][1][0] == 123 class TestZwave(unittest.TestCase): """Test zwave init.""" def test_device_config_glob_is_ordered(self): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): """Tests for zwave services.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() # Initialize zwave setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.zwave_network = self.hass.data[DATA_NETWORK] self.zwave_network.state = MockNetwork.STATE_READY self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.block_till_done() def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() self.hass.stop() def test_add_node(self): """Test zwave add_node service.""" self.hass.services.call('zwave', 'add_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller .add_node.mock_calls) == 1 assert len(self.zwave_network.controller .add_node.mock_calls[0][1]) == 0 def test_add_node_secure(self): """Test zwave add_node_secure service.""" self.hass.services.call('zwave', 'add_node_secure', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller.add_node.mock_calls) == 1 assert (self.zwave_network.controller .add_node.mock_calls[0][1][0] is True) def test_remove_node(self): """Test zwave remove_node service.""" self.hass.services.call('zwave', 'remove_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.remove_node.called assert len(self.zwave_network.controller.remove_node.mock_calls) == 1 def test_cancel_command(self): """Test zwave cancel_command service.""" self.hass.services.call('zwave', 'cancel_command', {}) self.hass.block_till_done() assert self.zwave_network.controller.cancel_command.called assert len(self.zwave_network.controller .cancel_command.mock_calls) == 1 def test_heal_network(self): """Test zwave heal_network service.""" self.hass.services.call('zwave', 'heal_network', {}) self.hass.block_till_done() assert self.zwave_network.heal.called assert len(self.zwave_network.heal.mock_calls) == 1 def test_soft_reset(self): """Test zwave soft_reset service.""" self.hass.services.call('zwave', 'soft_reset', {}) self.hass.block_till_done() assert self.zwave_network.controller.soft_reset.called assert len(self.zwave_network.controller.soft_reset.mock_calls) == 1 def test_test_network(self): """Test zwave test_network service.""" self.hass.services.call('zwave', 'test_network', {}) self.hass.block_till_done() assert self.zwave_network.test.called assert len(self.zwave_network.test.mock_calls) == 1 def test_stop_network(self): """Test zwave stop_network service.""" with patch.object(self.hass.bus, 'fire') as mock_fire: self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() assert self.zwave_network.stop.called assert len(self.zwave_network.stop.mock_calls) == 1 assert mock_fire.called assert len(mock_fire.mock_calls) == 1 assert mock_fire.mock_calls[0][1][0] == const.EVENT_NETWORK_STOP def test_rename_node(self): """Test zwave rename_node service.""" self.zwave_network.nodes = {11: MagicMock()} self.hass.services.call('zwave', 'rename_node', { const.ATTR_NODE_ID: 11, const.ATTR_NAME: 'test_name', }) self.hass.block_till_done() assert self.zwave_network.nodes[11].name == 'test_name' def test_rename_value(self): """Test zwave rename_value service.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, label="Old Label") node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.label == "Old Label" self.hass.services.call('zwave', 'rename_value', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_NAME: "New Label", }) self.hass.block_till_done() assert value.label == "New Label" def test_set_poll_intensity_enable(self): """Test zwave set_poll_intensity service, successful set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 2 assert enable_poll.mock_calls[0][1][0] == 4 def test_set_poll_intensity_enable_failed(self): """Test zwave set_poll_intensity service, failed set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) value.enable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 1 def test_set_poll_intensity_disable(self): """Test zwave set_poll_intensity service, successful disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 2 def test_set_poll_intensity_disable_failed(self): """Test zwave set_poll_intensity service, failed disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) value.disable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 1 def test_remove_failed_node(self): """Test zwave remove_failed_node service.""" self.hass.services.call('zwave', 'remove_failed_node', { const.ATTR_NODE_ID: 12, }) self.hass.block_till_done() remove_failed_node = self.zwave_network.controller.remove_failed_node assert remove_failed_node.called assert len(remove_failed_node.mock_calls) == 1 assert remove_failed_node.mock_calls[0][1][0] == 12 def test_replace_failed_node(self): """Test zwave replace_failed_node service.""" self.hass.services.call('zwave', 'replace_failed_node', { const.ATTR_NODE_ID: 13, }) self.hass.block_till_done() replace_failed_node = self.zwave_network.controller.replace_failed_node assert replace_failed_node.called assert len(replace_failed_node.mock_calls) == 1 assert replace_failed_node.mock_calls[0][1][0] == 13 def test_set_config_parameter(self): """Test zwave set_config_parameter service.""" value_byte = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BYTE, ) value_list = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['item1', 'item2', 'item3'], ) value_button = MockValue( index=14, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BUTTON, ) value_list_int = MockValue( index=15, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['1', '2', '3'], ) value_bool = MockValue( index=16, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BOOL, ) node = MockNode(node_id=14) node.get_values.return_value = { 12: value_byte, 13: value_list, 14: value_button, 15: value_list_int, 16: value_bool } self.zwave_network.nodes = {14: node} # Byte self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 12, const.ATTR_CONFIG_VALUE: 7, }) self.hass.block_till_done() assert value_byte.data == 7 # List self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, const.ATTR_CONFIG_VALUE: 'item3', }) self.hass.block_till_done() assert value_list.data == 'item3' # Button self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 14, const.ATTR_CONFIG_VALUE: True, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called assert self.zwave_network.manager.releaseButton.called # List of Ints self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 15, const.ATTR_CONFIG_VALUE: 3, }) self.hass.block_till_done() assert value_list_int.data == '3' # Boolean Truthy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'True', }) self.hass.block_till_done() assert value_bool.data == 1 # Boolean Falsy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'False', }) self.hass.block_till_done() assert value_bool.data == 0 # Different Parameter Size self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 19, const.ATTR_CONFIG_VALUE: 0x01020304, const.ATTR_CONFIG_SIZE: 4 }) self.hass.block_till_done() assert node.set_config_param.called assert len(node.set_config_param.mock_calls) == 1 assert node.set_config_param.mock_calls[0][1][0] == 19 assert node.set_config_param.mock_calls[0][1][1] == 0x01020304 assert node.set_config_param.mock_calls[0][1][2] == 4 node.set_config_param.reset_mock() def test_print_config_parameter(self): """Test zwave print_config_parameter service.""" value1 = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, data=1234, ) value2 = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, data=2345, ) node = MockNode(node_id=14) node.values = {12: value1, 13: value2} self.zwave_network.nodes = {14: node} with patch.object(zwave, '_LOGGER') as mock_logger: self.hass.services.call('zwave', 'print_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, }) self.hass.block_till_done() assert mock_logger.info.called assert len(mock_logger.info.mock_calls) == 1 assert mock_logger.info.mock_calls[0][1][1] == 13 assert mock_logger.info.mock_calls[0][1][2] == 14 assert mock_logger.info.mock_calls[0][1][3] == 2345 def test_print_node(self): """Test zwave print_node_parameter service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} with self.assertLogs(level='DEBUG') as mock_logger: self.hass.services.call('zwave', 'print_node', { const.ATTR_NODE_ID: 14 }) self.hass.block_till_done() assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 15, }) self.hass.block_till_done() assert value.data == 15 node.can_wake_up_value = False self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 20, }) self.hass.block_till_done() assert value.data == 15 def test_reset_node_meters(self): """Test zwave reset_node_meters service.""" value = MockValue( instance=1, index=8, data=99.5, command_class=const.COMMAND_CLASS_METER, ) reset_value = MockValue( instance=1, index=33, command_class=const.COMMAND_CLASS_METER, ) node = MockNode(node_id=14) node.values = {8: value, 33: reset_value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, const.ATTR_INSTANCE: 2, }) self.hass.block_till_done() assert not self.zwave_network.manager.pressButton.called assert not self.zwave_network.manager.releaseButton.called self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called value_id, = self.zwave_network.manager.pressButton.mock_calls.pop(0)[1] assert value_id == reset_value.value_id assert self.zwave_network.manager.releaseButton.called value_id, = ( self.zwave_network.manager.releaseButton.mock_calls.pop(0)[1]) assert value_id == reset_value.value_id def test_add_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'add', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.add_association.called assert len(group.add_association.mock_calls) == 1 assert group.add_association.mock_calls[0][1][0] == 24 assert group.add_association.mock_calls[0][1][1] == 5 def test_remove_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'remove', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.remove_association.called assert len(group.remove_association.mock_calls) == 1 assert group.remove_association.mock_calls[0][1][0] == 24 assert group.remove_association.mock_calls[0][1][1] == 5 def test_refresh_entity(self): """Test zwave refresh_entity service.""" node = MockNode() value = MockValue(data=False, node=node, command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50, node=node, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = get_device(node=node, values=values, node_config={}) device.hass = self.hass device.entity_id = 'binary_sensor.mock_entity_id' self.hass.add_job(device.async_added_to_hass()) self.hass.block_till_done() self.hass.services.call('zwave', 'refresh_entity', { ATTR_ENTITY_ID: 'binary_sensor.mock_entity_id', }) self.hass.block_till_done() assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 assert sorted([node.refresh_value.mock_calls[0][1][0], node.refresh_value.mock_calls[1][1][0]]) == \ sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert node.refresh_info.called assert len(node.refresh_info.mock_calls) == 1 def test_set_node_value(self): """Test zwave set_node_value service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=4 ) node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR]) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12, const.ATTR_CONFIG_VALUE: 2, }) self.hass.block_till_done() assert self.zwave_network.nodes[14].values[12].data == 2 def test_refresh_node_value(self): """Test zwave refresh_node_value service.""" node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR], network=self.zwave_network) value = MockValue( node=node, index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=2 ) value.refresh = MagicMock() node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12 }) self.hass.block_till_done() assert value.refresh.called def test_heal_node(self): """Test zwave heal_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'heal_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.heal.called assert len(node.heal.mock_calls) == 1 def test_test_node(self): """Test the zwave test_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'test_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.test.called assert len(node.test.mock_calls) == 1
jabesq/home-assistant
tests/components/zwave/test_init.py
homeassistant/components/elkm1/alarm_control_panel.py
"""Support for LCN lights.""" import pypck from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_TRANSITION, SUPPORT_BRIGHTNESS, SUPPORT_TRANSITION, Light) from homeassistant.const import CONF_ADDRESS from . import LcnDevice from .const import ( CONF_CONNECTIONS, CONF_DIMMABLE, CONF_OUTPUT, CONF_TRANSITION, DATA_LCN, OUTPUT_PORTS) from .helpers import get_connection async def async_setup_platform( hass, hass_config, async_add_entities, discovery_info=None): """Set up the LCN light platform.""" if discovery_info is None: return devices = [] for config in discovery_info: address, connection_id = config[CONF_ADDRESS] addr = pypck.lcn_addr.LcnAddr(*address) connections = hass.data[DATA_LCN][CONF_CONNECTIONS] connection = get_connection(connections, connection_id) address_connection = connection.get_address_conn(addr) if config[CONF_OUTPUT] in OUTPUT_PORTS: device = LcnOutputLight(config, address_connection) else: # in RELAY_PORTS device = LcnRelayLight(config, address_connection) devices.append(device) async_add_entities(devices) class LcnOutputLight(LcnDevice, Light): """Representation of a LCN light for output ports.""" def __init__(self, config, address_connection): """Initialize the LCN light.""" super().__init__(config, address_connection) self.output = pypck.lcn_defs.OutputPort[config[CONF_OUTPUT]] self._transition = pypck.lcn_defs.time_to_ramp_value( config[CONF_TRANSITION]) self.dimmable = config[CONF_DIMMABLE] self._brightness = 255 self._is_on = None self._is_dimming_to_zero = False async def async_added_to_hass(self): """Run when entity about to be added to hass.""" await super().async_added_to_hass() await self.address_connection.activate_status_request_handler( self.output) @property def supported_features(self): """Flag supported features.""" features = SUPPORT_TRANSITION if self.dimmable: features |= SUPPORT_BRIGHTNESS return features @property def brightness(self): """Return the brightness of this light between 0..255.""" return self._brightness @property def is_on(self): """Return True if entity is on.""" return self._is_on async def async_turn_on(self, **kwargs): """Turn the entity on.""" self._is_on = True self._is_dimming_to_zero = False if ATTR_BRIGHTNESS in kwargs: percent = int(kwargs[ATTR_BRIGHTNESS] / 255. * 100) else: percent = 100 if ATTR_TRANSITION in kwargs: transition = pypck.lcn_defs.time_to_ramp_value( kwargs[ATTR_TRANSITION] * 1000) else: transition = self._transition self.address_connection.dim_output(self.output.value, percent, transition) await self.async_update_ha_state() async def async_turn_off(self, **kwargs): """Turn the entity off.""" self._is_on = False if ATTR_TRANSITION in kwargs: transition = pypck.lcn_defs.time_to_ramp_value( kwargs[ATTR_TRANSITION] * 1000) else: transition = self._transition self._is_dimming_to_zero = bool(transition) self.address_connection.dim_output(self.output.value, 0, transition) await self.async_update_ha_state() def input_received(self, input_obj): """Set light state when LCN input object (command) is received.""" if not isinstance(input_obj, pypck.inputs.ModStatusOutput) or \ input_obj.get_output_id() != self.output.value: return self._brightness = int(input_obj.get_percent() / 100.*255) if self.brightness == 0: self._is_dimming_to_zero = False if not self._is_dimming_to_zero: self._is_on = self.brightness > 0 self.async_schedule_update_ha_state() class LcnRelayLight(LcnDevice, Light): """Representation of a LCN light for relay ports.""" def __init__(self, config, address_connection): """Initialize the LCN light.""" super().__init__(config, address_connection) self.output = pypck.lcn_defs.RelayPort[config[CONF_OUTPUT]] self._is_on = None async def async_added_to_hass(self): """Run when entity about to be added to hass.""" await super().async_added_to_hass() await self.address_connection.activate_status_request_handler( self.output) @property def is_on(self): """Return True if entity is on.""" return self._is_on async def async_turn_on(self, **kwargs): """Turn the entity on.""" self._is_on = True states = [pypck.lcn_defs.RelayStateModifier.NOCHANGE] * 8 states[self.output.value] = pypck.lcn_defs.RelayStateModifier.ON self.address_connection.control_relays(states) await self.async_update_ha_state() async def async_turn_off(self, **kwargs): """Turn the entity off.""" self._is_on = False states = [pypck.lcn_defs.RelayStateModifier.NOCHANGE] * 8 states[self.output.value] = pypck.lcn_defs.RelayStateModifier.OFF self.address_connection.control_relays(states) await self.async_update_ha_state() def input_received(self, input_obj): """Set light state when LCN input object (command) is received.""" if not isinstance(input_obj, pypck.inputs.ModStatusRelays): return self._is_on = input_obj.get_state(self.output.value) self.async_schedule_update_ha_state()
"""Tests for the Z-Wave init.""" import asyncio from collections import OrderedDict from datetime import datetime import unittest from unittest.mock import MagicMock, patch import pytest from pytz import utc import voluptuous as vol from homeassistant.bootstrap import async_setup_component from homeassistant.components import zwave from homeassistant.components.zwave import ( CONF_DEVICE_CONFIG_GLOB, CONFIG_SCHEMA, DATA_NETWORK, const) from homeassistant.components.zwave.binary_sensor import get_device from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.device_registry import ( async_get_registry as get_dev_reg) from homeassistant.setup import setup_component from tests.common import ( async_fire_time_changed, get_test_home_assistant, mock_coro, mock_registry) from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue async def test_valid_device_config(hass, mock_openzwave): """Test valid device config.""" device_config = { 'light.kitchen': { 'ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert result async def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = { 'light.kitchen': { 'some_ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert not result def test_config_access_error(): """Test threading error accessing config values.""" node = MagicMock() def side_effect(): raise RuntimeError node.values.values.side_effect = side_effect result = zwave.get_config_value(node, 1) assert result is None async def test_network_options(hass, mock_openzwave): """Test network options.""" result = await async_setup_component(hass, 'zwave', { 'zwave': { 'usb_path': 'mock_usb_path', 'config_path': 'mock_config_path', }}) await hass.async_block_till_done() assert result network = hass.data[zwave.DATA_NETWORK] assert network.options.device == 'mock_usb_path' assert network.options.config_path == 'mock_config_path' async def test_network_key_validation(hass, mock_openzwave): """Test network key validation.""" test_values = [ ('0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,' '0x0E,0x0F,0x10'), ] for value in test_values: result = zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) assert result['zwave']['network_key'] == value async def test_erronous_network_key_fails_validation(hass, mock_openzwave): """Test failing erronous network key validation.""" test_values = [ ('0x 01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0X01,0X02,0X03,0X04,0X05,0X06,0X07,0X08,0X09,0X0A,0X0B,0X0C,0X0D,' '0X0E,0X0F,0X10'), 'invalid', '1234567', 1234567 ] for value in test_values: with pytest.raises(vol.Invalid): zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) async def test_auto_heal_midnight(hass, mock_openzwave): """Test network auto-heal at midnight.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': True, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert network.heal.called assert len(network.heal.mock_calls) == 1 async def test_auto_heal_disabled(hass, mock_openzwave): """Test network auto-heal disabled.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': False, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert not network.heal.called async def test_setup_platform(hass, mock_openzwave): """Test invalid device config.""" mock_device = MagicMock() hass.data[DATA_NETWORK] = MagicMock() hass.data[zwave.DATA_DEVICES] = {456: mock_device} async_add_entities = MagicMock() result = await zwave.async_setup_platform( hass, None, async_add_entities, None) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 123}) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 456}) assert result assert async_add_entities.called assert len(async_add_entities.mock_calls) == 1 assert async_add_entities.mock_calls[0][1][0] == [mock_device] async def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): """Test device entity base class.""" node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.value_added() device.update_properties() await hass.async_block_till_done() assert not device.should_poll assert device.unique_id == "10-11" assert device.name == 'Mock Node Sensor' assert device.device_state_attributes[zwave.ATTR_POWER] == 50.123 async def test_node_removed(hass, mock_openzwave): """Test node removed in base class.""" # Create a mock node & node entity node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.entity_id = 'zwave.mock_node' device.value_added() device.update_properties() await hass.async_block_till_done() # Save it to the entity registry registry = mock_registry(hass) registry.async_get_or_create('zwave', 'zwave', device.unique_id) device.entity_id = registry.async_get_entity_id( 'zwave', 'zwave', device.unique_id) # Create dummy entity registry entries for other integrations hue_entity = registry.async_get_or_create('light', 'hue', 1234) zha_entity = registry.async_get_or_create('sensor', 'zha', 5678) # Verify our Z-Wave entity is registered assert registry.async_is_registered(device.entity_id) # Remove it entity_id = device.entity_id await device.node_removed() # Verify registry entry for our Z-Wave node is gone assert not registry.async_is_registered(entity_id) # Verify registry entries for our other entities remain assert registry.async_is_registered(hue_entity.entity_id) assert registry.async_is_registered(zha_entity.entity_id) async def test_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node').state == 'unknown' async def test_unparsed_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode( node_id=14, manufacturer_name=None, name=None, is_ready=False) sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert len(sleeps) == const.NODE_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1:] == \ (14, const.NODE_READY_WAIT_SECS) assert hass.states.get('zwave.unknown_node_14').state == 'unknown' async def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': { 'device_config': { 'zwave.mock_node': { 'ignored': True, }}}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None async def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' async def test_value_entities(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = {} def mock_connect(receiver, signal, *args, **kwargs): mock_receivers[signal] = receiver with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert mock_receivers hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_ALL_NODES_QUERIED]) node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) zwave_network.nodes = {node.node_id: node} value = MockValue( data=False, node=node, index=12, instance=1, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values = {'primary': value, value.value_id: value} value2 = MockValue( data=False, node=node, index=12, instance=2, label="Mock Value B", command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values[value2.value_id] = value2 hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_NODE_ADDED], node) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value2) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' assert hass.states.get( 'binary_sensor.mock_node_mock_value_b').state == 'off' ent_reg = await async_get_registry(hass) dev_reg = await get_dev_reg(hass) entry = ent_reg.async_get('zwave.mock_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) node_dev_id = entry.device_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) assert entry.name is None assert entry.device_id == node_dev_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value2.object_id) assert entry.name is None assert entry.device_id != node_dev_id device_id_b = entry.device_id device = dev_reg.async_get(node_dev_id) assert device is not None assert device.name == node.name old_device = device device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming without updating await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_NAME: "Demo Node", }) await hass.async_block_till_done() assert node.name == "Demo Node" entry = ent_reg.async_get('zwave.mock_node') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Node", }) await hass.async_block_till_done() assert node.name == "New Node" entry = ent_reg.async_get('zwave.new_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) entry = ent_reg.async_get('binary_sensor.new_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) await hass.services.async_call('zwave', 'rename_value', { const.ATTR_NODE_ID: node.node_id, const.ATTR_VALUE_ID: value.object_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Label", }) await hass.async_block_till_done() entry = ent_reg.async_get('binary_sensor.new_node_new_label') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) async def test_value_discovery_existing_entity(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_THERMOSTAT) setpoint = MockValue( data=22.0, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, setpoint) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] is None def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): temperature = MockValue( data=23.5, node=node, index=1, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, temperature) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] == 23.5 async def test_power_schemes(hass, mock_openzwave): """Test power attribute.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SWITCH_BINARY) switch = MockValue( data=True, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SWITCH_BINARY, genre=const.GENRE_USER, type=const.TYPE_BOOL) hass.async_add_job(mock_receivers[0], node, switch) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').state == 'on' assert 'power_consumption' not in hass.states.get( 'switch.mock_node_mock_value').attributes def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): power = MockValue( data=23.5, node=node, index=const.INDEX_SENSOR_MULTILEVEL_POWER, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL) hass.async_add_job(mock_receivers[0], node, power) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').attributes[ 'power_consumption'] == 23.5 async def test_network_ready(hass, mock_openzwave): """Test Node network ready event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete_some_dead(hass, mock_openzwave): """Test Node network complete some dead event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE_SOME_DEAD, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 class TestZWaveDeviceEntityValues(unittest.TestCase): """Tests for the ZWaveDeviceEntityValues helper.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() self.registry = mock_registry(self.hass) setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.node = MockNode() self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: ['mock_primary_class'], }, 'secondary': { const.DISC_COMMAND_CLASS: ['mock_secondary_class'], }, 'optional': { const.DISC_COMMAND_CLASS: ['mock_optional_class'], const.DISC_OPTIONAL: True, }}} self.primary = MockValue( command_class='mock_primary_class', node=self.node, value_id=1000) self.secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.duplicate_secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.optional = MockValue( command_class='mock_optional_class', node=self.node) self.no_match_value = MockValue( command_class='mock_bad_class', node=self.node) self.entity_id = 'mock_component.mock_node_mock_value' self.zwave_config = {'zwave': {}} self.device_config = {self.entity_id: {}} def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) assert values.primary is self.primary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) self.hass.block_till_done() assert values.secondary is self.secondary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config discovery.async_load_platform.reset_mock() values.check_value(self.optional) values.check_value(self.duplicate_secondary) values.check_value(self.no_match_value) self.hass.block_till_done() assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called assert len(values._entity.value_added.mock_calls) == 1 assert values._entity.value_changed.called assert len(values._entity.value_changed.mock_calls) == 1 @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, self.optional.value_id: self.optional, self.no_match_value.value_id: self.no_match_value, } values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert values.primary is self.primary assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config assert not self.primary.enable_poll.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_node_schema_mismatch(self, discovery, import_module): """Test node schema mismatch.""" self.node.generic = 'no_match' self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.mock_schema[const.DISC_GENERIC_DEVICE_CLASS] = ['generic_match'] values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.manufacturer_id = '010f' self.node.product_type = '0b00' self.primary.command_class = const.COMMAND_CLASS_SENSOR_ALARM self.entity_id = 'binary_sensor.mock_node_mock_value' self.device_config = {self.entity_id: {}} self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} with patch.object(zwave, 'async_dispatcher_send') as \ mock_dispatch_send: values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert mock_dispatch_send.called assert len(mock_dispatch_send.mock_calls) == 1 args = mock_dispatch_send.mock_calls[0][1] assert args[1] == 'zwave_new_binary_sensor' @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_ignore(self, discovery, import_module): """Test ignore workaround.""" self.node.manufacturer_id = '010f' self.node.product_type = '0301' self.primary.command_class = const.COMMAND_CLASS_SWITCH_BINARY self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore(self, discovery, import_module): """Test ignore config.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_IGNORED: True }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore_with_registry(self, discovery, import_module): """Test ignore config. The case when the device is in entity registry. """ self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {'mock_component.registry_id': { zwave.CONF_IGNORED: True }} with patch.object(self.registry, 'async_schedule_save'): self.registry.async_get_or_create( 'mock_component', zwave.DOMAIN, '567-1000', suggested_object_id='registry_id') zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_platform_ignore(self, discovery, import_module): """Test platform ignore device.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } platform = MagicMock() import_module.return_value = platform platform.get_device.return_value = None zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_config_polling_intensity(self, discovery, import_module): """Test polling intensity.""" mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_POLLING_INTENSITY: 123, }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert discovery.async_load_platform.called assert self.primary.enable_poll.called assert len(self.primary.enable_poll.mock_calls) == 1 assert self.primary.enable_poll.mock_calls[0][1][0] == 123 class TestZwave(unittest.TestCase): """Test zwave init.""" def test_device_config_glob_is_ordered(self): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): """Tests for zwave services.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() # Initialize zwave setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.zwave_network = self.hass.data[DATA_NETWORK] self.zwave_network.state = MockNetwork.STATE_READY self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.block_till_done() def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() self.hass.stop() def test_add_node(self): """Test zwave add_node service.""" self.hass.services.call('zwave', 'add_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller .add_node.mock_calls) == 1 assert len(self.zwave_network.controller .add_node.mock_calls[0][1]) == 0 def test_add_node_secure(self): """Test zwave add_node_secure service.""" self.hass.services.call('zwave', 'add_node_secure', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller.add_node.mock_calls) == 1 assert (self.zwave_network.controller .add_node.mock_calls[0][1][0] is True) def test_remove_node(self): """Test zwave remove_node service.""" self.hass.services.call('zwave', 'remove_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.remove_node.called assert len(self.zwave_network.controller.remove_node.mock_calls) == 1 def test_cancel_command(self): """Test zwave cancel_command service.""" self.hass.services.call('zwave', 'cancel_command', {}) self.hass.block_till_done() assert self.zwave_network.controller.cancel_command.called assert len(self.zwave_network.controller .cancel_command.mock_calls) == 1 def test_heal_network(self): """Test zwave heal_network service.""" self.hass.services.call('zwave', 'heal_network', {}) self.hass.block_till_done() assert self.zwave_network.heal.called assert len(self.zwave_network.heal.mock_calls) == 1 def test_soft_reset(self): """Test zwave soft_reset service.""" self.hass.services.call('zwave', 'soft_reset', {}) self.hass.block_till_done() assert self.zwave_network.controller.soft_reset.called assert len(self.zwave_network.controller.soft_reset.mock_calls) == 1 def test_test_network(self): """Test zwave test_network service.""" self.hass.services.call('zwave', 'test_network', {}) self.hass.block_till_done() assert self.zwave_network.test.called assert len(self.zwave_network.test.mock_calls) == 1 def test_stop_network(self): """Test zwave stop_network service.""" with patch.object(self.hass.bus, 'fire') as mock_fire: self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() assert self.zwave_network.stop.called assert len(self.zwave_network.stop.mock_calls) == 1 assert mock_fire.called assert len(mock_fire.mock_calls) == 1 assert mock_fire.mock_calls[0][1][0] == const.EVENT_NETWORK_STOP def test_rename_node(self): """Test zwave rename_node service.""" self.zwave_network.nodes = {11: MagicMock()} self.hass.services.call('zwave', 'rename_node', { const.ATTR_NODE_ID: 11, const.ATTR_NAME: 'test_name', }) self.hass.block_till_done() assert self.zwave_network.nodes[11].name == 'test_name' def test_rename_value(self): """Test zwave rename_value service.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, label="Old Label") node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.label == "Old Label" self.hass.services.call('zwave', 'rename_value', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_NAME: "New Label", }) self.hass.block_till_done() assert value.label == "New Label" def test_set_poll_intensity_enable(self): """Test zwave set_poll_intensity service, successful set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 2 assert enable_poll.mock_calls[0][1][0] == 4 def test_set_poll_intensity_enable_failed(self): """Test zwave set_poll_intensity service, failed set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) value.enable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 1 def test_set_poll_intensity_disable(self): """Test zwave set_poll_intensity service, successful disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 2 def test_set_poll_intensity_disable_failed(self): """Test zwave set_poll_intensity service, failed disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) value.disable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 1 def test_remove_failed_node(self): """Test zwave remove_failed_node service.""" self.hass.services.call('zwave', 'remove_failed_node', { const.ATTR_NODE_ID: 12, }) self.hass.block_till_done() remove_failed_node = self.zwave_network.controller.remove_failed_node assert remove_failed_node.called assert len(remove_failed_node.mock_calls) == 1 assert remove_failed_node.mock_calls[0][1][0] == 12 def test_replace_failed_node(self): """Test zwave replace_failed_node service.""" self.hass.services.call('zwave', 'replace_failed_node', { const.ATTR_NODE_ID: 13, }) self.hass.block_till_done() replace_failed_node = self.zwave_network.controller.replace_failed_node assert replace_failed_node.called assert len(replace_failed_node.mock_calls) == 1 assert replace_failed_node.mock_calls[0][1][0] == 13 def test_set_config_parameter(self): """Test zwave set_config_parameter service.""" value_byte = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BYTE, ) value_list = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['item1', 'item2', 'item3'], ) value_button = MockValue( index=14, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BUTTON, ) value_list_int = MockValue( index=15, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['1', '2', '3'], ) value_bool = MockValue( index=16, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BOOL, ) node = MockNode(node_id=14) node.get_values.return_value = { 12: value_byte, 13: value_list, 14: value_button, 15: value_list_int, 16: value_bool } self.zwave_network.nodes = {14: node} # Byte self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 12, const.ATTR_CONFIG_VALUE: 7, }) self.hass.block_till_done() assert value_byte.data == 7 # List self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, const.ATTR_CONFIG_VALUE: 'item3', }) self.hass.block_till_done() assert value_list.data == 'item3' # Button self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 14, const.ATTR_CONFIG_VALUE: True, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called assert self.zwave_network.manager.releaseButton.called # List of Ints self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 15, const.ATTR_CONFIG_VALUE: 3, }) self.hass.block_till_done() assert value_list_int.data == '3' # Boolean Truthy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'True', }) self.hass.block_till_done() assert value_bool.data == 1 # Boolean Falsy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'False', }) self.hass.block_till_done() assert value_bool.data == 0 # Different Parameter Size self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 19, const.ATTR_CONFIG_VALUE: 0x01020304, const.ATTR_CONFIG_SIZE: 4 }) self.hass.block_till_done() assert node.set_config_param.called assert len(node.set_config_param.mock_calls) == 1 assert node.set_config_param.mock_calls[0][1][0] == 19 assert node.set_config_param.mock_calls[0][1][1] == 0x01020304 assert node.set_config_param.mock_calls[0][1][2] == 4 node.set_config_param.reset_mock() def test_print_config_parameter(self): """Test zwave print_config_parameter service.""" value1 = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, data=1234, ) value2 = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, data=2345, ) node = MockNode(node_id=14) node.values = {12: value1, 13: value2} self.zwave_network.nodes = {14: node} with patch.object(zwave, '_LOGGER') as mock_logger: self.hass.services.call('zwave', 'print_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, }) self.hass.block_till_done() assert mock_logger.info.called assert len(mock_logger.info.mock_calls) == 1 assert mock_logger.info.mock_calls[0][1][1] == 13 assert mock_logger.info.mock_calls[0][1][2] == 14 assert mock_logger.info.mock_calls[0][1][3] == 2345 def test_print_node(self): """Test zwave print_node_parameter service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} with self.assertLogs(level='DEBUG') as mock_logger: self.hass.services.call('zwave', 'print_node', { const.ATTR_NODE_ID: 14 }) self.hass.block_till_done() assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 15, }) self.hass.block_till_done() assert value.data == 15 node.can_wake_up_value = False self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 20, }) self.hass.block_till_done() assert value.data == 15 def test_reset_node_meters(self): """Test zwave reset_node_meters service.""" value = MockValue( instance=1, index=8, data=99.5, command_class=const.COMMAND_CLASS_METER, ) reset_value = MockValue( instance=1, index=33, command_class=const.COMMAND_CLASS_METER, ) node = MockNode(node_id=14) node.values = {8: value, 33: reset_value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, const.ATTR_INSTANCE: 2, }) self.hass.block_till_done() assert not self.zwave_network.manager.pressButton.called assert not self.zwave_network.manager.releaseButton.called self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called value_id, = self.zwave_network.manager.pressButton.mock_calls.pop(0)[1] assert value_id == reset_value.value_id assert self.zwave_network.manager.releaseButton.called value_id, = ( self.zwave_network.manager.releaseButton.mock_calls.pop(0)[1]) assert value_id == reset_value.value_id def test_add_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'add', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.add_association.called assert len(group.add_association.mock_calls) == 1 assert group.add_association.mock_calls[0][1][0] == 24 assert group.add_association.mock_calls[0][1][1] == 5 def test_remove_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'remove', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.remove_association.called assert len(group.remove_association.mock_calls) == 1 assert group.remove_association.mock_calls[0][1][0] == 24 assert group.remove_association.mock_calls[0][1][1] == 5 def test_refresh_entity(self): """Test zwave refresh_entity service.""" node = MockNode() value = MockValue(data=False, node=node, command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50, node=node, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = get_device(node=node, values=values, node_config={}) device.hass = self.hass device.entity_id = 'binary_sensor.mock_entity_id' self.hass.add_job(device.async_added_to_hass()) self.hass.block_till_done() self.hass.services.call('zwave', 'refresh_entity', { ATTR_ENTITY_ID: 'binary_sensor.mock_entity_id', }) self.hass.block_till_done() assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 assert sorted([node.refresh_value.mock_calls[0][1][0], node.refresh_value.mock_calls[1][1][0]]) == \ sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert node.refresh_info.called assert len(node.refresh_info.mock_calls) == 1 def test_set_node_value(self): """Test zwave set_node_value service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=4 ) node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR]) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12, const.ATTR_CONFIG_VALUE: 2, }) self.hass.block_till_done() assert self.zwave_network.nodes[14].values[12].data == 2 def test_refresh_node_value(self): """Test zwave refresh_node_value service.""" node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR], network=self.zwave_network) value = MockValue( node=node, index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=2 ) value.refresh = MagicMock() node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12 }) self.hass.block_till_done() assert value.refresh.called def test_heal_node(self): """Test zwave heal_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'heal_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.heal.called assert len(node.heal.mock_calls) == 1 def test_test_node(self): """Test the zwave test_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'test_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.test.called assert len(node.test.mock_calls) == 1
jabesq/home-assistant
tests/components/zwave/test_init.py
homeassistant/components/lcn/light.py
"""Support for Lutron scenes.""" import logging from homeassistant.components.scene import Scene from . import LUTRON_CONTROLLER, LUTRON_DEVICES, LutronDevice _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Lutron scenes.""" devs = [] for scene_data in hass.data[LUTRON_DEVICES]['scene']: (area_name, keypad_name, device, led) = scene_data dev = LutronScene(area_name, keypad_name, device, led, hass.data[LUTRON_CONTROLLER]) devs.append(dev) add_entities(devs, True) class LutronScene(LutronDevice, Scene): """Representation of a Lutron Scene.""" def __init__( self, area_name, keypad_name, lutron_device, lutron_led, controller): """Initialize the scene/button.""" super().__init__(area_name, lutron_device, controller) self._keypad_name = keypad_name self._led = lutron_led def activate(self): """Activate the scene.""" self._lutron_device.press() @property def name(self): """Return the name of the device.""" return "{} {}: {}".format( self._area_name, self._keypad_name, self._lutron_device.name)
"""Tests for the Z-Wave init.""" import asyncio from collections import OrderedDict from datetime import datetime import unittest from unittest.mock import MagicMock, patch import pytest from pytz import utc import voluptuous as vol from homeassistant.bootstrap import async_setup_component from homeassistant.components import zwave from homeassistant.components.zwave import ( CONF_DEVICE_CONFIG_GLOB, CONFIG_SCHEMA, DATA_NETWORK, const) from homeassistant.components.zwave.binary_sensor import get_device from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.device_registry import ( async_get_registry as get_dev_reg) from homeassistant.setup import setup_component from tests.common import ( async_fire_time_changed, get_test_home_assistant, mock_coro, mock_registry) from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue async def test_valid_device_config(hass, mock_openzwave): """Test valid device config.""" device_config = { 'light.kitchen': { 'ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert result async def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = { 'light.kitchen': { 'some_ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert not result def test_config_access_error(): """Test threading error accessing config values.""" node = MagicMock() def side_effect(): raise RuntimeError node.values.values.side_effect = side_effect result = zwave.get_config_value(node, 1) assert result is None async def test_network_options(hass, mock_openzwave): """Test network options.""" result = await async_setup_component(hass, 'zwave', { 'zwave': { 'usb_path': 'mock_usb_path', 'config_path': 'mock_config_path', }}) await hass.async_block_till_done() assert result network = hass.data[zwave.DATA_NETWORK] assert network.options.device == 'mock_usb_path' assert network.options.config_path == 'mock_config_path' async def test_network_key_validation(hass, mock_openzwave): """Test network key validation.""" test_values = [ ('0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,' '0x0E,0x0F,0x10'), ] for value in test_values: result = zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) assert result['zwave']['network_key'] == value async def test_erronous_network_key_fails_validation(hass, mock_openzwave): """Test failing erronous network key validation.""" test_values = [ ('0x 01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0X01,0X02,0X03,0X04,0X05,0X06,0X07,0X08,0X09,0X0A,0X0B,0X0C,0X0D,' '0X0E,0X0F,0X10'), 'invalid', '1234567', 1234567 ] for value in test_values: with pytest.raises(vol.Invalid): zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) async def test_auto_heal_midnight(hass, mock_openzwave): """Test network auto-heal at midnight.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': True, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert network.heal.called assert len(network.heal.mock_calls) == 1 async def test_auto_heal_disabled(hass, mock_openzwave): """Test network auto-heal disabled.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': False, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert not network.heal.called async def test_setup_platform(hass, mock_openzwave): """Test invalid device config.""" mock_device = MagicMock() hass.data[DATA_NETWORK] = MagicMock() hass.data[zwave.DATA_DEVICES] = {456: mock_device} async_add_entities = MagicMock() result = await zwave.async_setup_platform( hass, None, async_add_entities, None) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 123}) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 456}) assert result assert async_add_entities.called assert len(async_add_entities.mock_calls) == 1 assert async_add_entities.mock_calls[0][1][0] == [mock_device] async def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): """Test device entity base class.""" node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.value_added() device.update_properties() await hass.async_block_till_done() assert not device.should_poll assert device.unique_id == "10-11" assert device.name == 'Mock Node Sensor' assert device.device_state_attributes[zwave.ATTR_POWER] == 50.123 async def test_node_removed(hass, mock_openzwave): """Test node removed in base class.""" # Create a mock node & node entity node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.entity_id = 'zwave.mock_node' device.value_added() device.update_properties() await hass.async_block_till_done() # Save it to the entity registry registry = mock_registry(hass) registry.async_get_or_create('zwave', 'zwave', device.unique_id) device.entity_id = registry.async_get_entity_id( 'zwave', 'zwave', device.unique_id) # Create dummy entity registry entries for other integrations hue_entity = registry.async_get_or_create('light', 'hue', 1234) zha_entity = registry.async_get_or_create('sensor', 'zha', 5678) # Verify our Z-Wave entity is registered assert registry.async_is_registered(device.entity_id) # Remove it entity_id = device.entity_id await device.node_removed() # Verify registry entry for our Z-Wave node is gone assert not registry.async_is_registered(entity_id) # Verify registry entries for our other entities remain assert registry.async_is_registered(hue_entity.entity_id) assert registry.async_is_registered(zha_entity.entity_id) async def test_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node').state == 'unknown' async def test_unparsed_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode( node_id=14, manufacturer_name=None, name=None, is_ready=False) sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert len(sleeps) == const.NODE_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1:] == \ (14, const.NODE_READY_WAIT_SECS) assert hass.states.get('zwave.unknown_node_14').state == 'unknown' async def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': { 'device_config': { 'zwave.mock_node': { 'ignored': True, }}}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None async def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' async def test_value_entities(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = {} def mock_connect(receiver, signal, *args, **kwargs): mock_receivers[signal] = receiver with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert mock_receivers hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_ALL_NODES_QUERIED]) node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) zwave_network.nodes = {node.node_id: node} value = MockValue( data=False, node=node, index=12, instance=1, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values = {'primary': value, value.value_id: value} value2 = MockValue( data=False, node=node, index=12, instance=2, label="Mock Value B", command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values[value2.value_id] = value2 hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_NODE_ADDED], node) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value2) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' assert hass.states.get( 'binary_sensor.mock_node_mock_value_b').state == 'off' ent_reg = await async_get_registry(hass) dev_reg = await get_dev_reg(hass) entry = ent_reg.async_get('zwave.mock_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) node_dev_id = entry.device_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) assert entry.name is None assert entry.device_id == node_dev_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value2.object_id) assert entry.name is None assert entry.device_id != node_dev_id device_id_b = entry.device_id device = dev_reg.async_get(node_dev_id) assert device is not None assert device.name == node.name old_device = device device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming without updating await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_NAME: "Demo Node", }) await hass.async_block_till_done() assert node.name == "Demo Node" entry = ent_reg.async_get('zwave.mock_node') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Node", }) await hass.async_block_till_done() assert node.name == "New Node" entry = ent_reg.async_get('zwave.new_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) entry = ent_reg.async_get('binary_sensor.new_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) await hass.services.async_call('zwave', 'rename_value', { const.ATTR_NODE_ID: node.node_id, const.ATTR_VALUE_ID: value.object_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Label", }) await hass.async_block_till_done() entry = ent_reg.async_get('binary_sensor.new_node_new_label') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) async def test_value_discovery_existing_entity(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_THERMOSTAT) setpoint = MockValue( data=22.0, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, setpoint) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] is None def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): temperature = MockValue( data=23.5, node=node, index=1, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, temperature) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] == 23.5 async def test_power_schemes(hass, mock_openzwave): """Test power attribute.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SWITCH_BINARY) switch = MockValue( data=True, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SWITCH_BINARY, genre=const.GENRE_USER, type=const.TYPE_BOOL) hass.async_add_job(mock_receivers[0], node, switch) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').state == 'on' assert 'power_consumption' not in hass.states.get( 'switch.mock_node_mock_value').attributes def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): power = MockValue( data=23.5, node=node, index=const.INDEX_SENSOR_MULTILEVEL_POWER, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL) hass.async_add_job(mock_receivers[0], node, power) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').attributes[ 'power_consumption'] == 23.5 async def test_network_ready(hass, mock_openzwave): """Test Node network ready event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete_some_dead(hass, mock_openzwave): """Test Node network complete some dead event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE_SOME_DEAD, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 class TestZWaveDeviceEntityValues(unittest.TestCase): """Tests for the ZWaveDeviceEntityValues helper.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() self.registry = mock_registry(self.hass) setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.node = MockNode() self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: ['mock_primary_class'], }, 'secondary': { const.DISC_COMMAND_CLASS: ['mock_secondary_class'], }, 'optional': { const.DISC_COMMAND_CLASS: ['mock_optional_class'], const.DISC_OPTIONAL: True, }}} self.primary = MockValue( command_class='mock_primary_class', node=self.node, value_id=1000) self.secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.duplicate_secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.optional = MockValue( command_class='mock_optional_class', node=self.node) self.no_match_value = MockValue( command_class='mock_bad_class', node=self.node) self.entity_id = 'mock_component.mock_node_mock_value' self.zwave_config = {'zwave': {}} self.device_config = {self.entity_id: {}} def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) assert values.primary is self.primary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) self.hass.block_till_done() assert values.secondary is self.secondary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config discovery.async_load_platform.reset_mock() values.check_value(self.optional) values.check_value(self.duplicate_secondary) values.check_value(self.no_match_value) self.hass.block_till_done() assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called assert len(values._entity.value_added.mock_calls) == 1 assert values._entity.value_changed.called assert len(values._entity.value_changed.mock_calls) == 1 @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, self.optional.value_id: self.optional, self.no_match_value.value_id: self.no_match_value, } values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert values.primary is self.primary assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config assert not self.primary.enable_poll.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_node_schema_mismatch(self, discovery, import_module): """Test node schema mismatch.""" self.node.generic = 'no_match' self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.mock_schema[const.DISC_GENERIC_DEVICE_CLASS] = ['generic_match'] values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.manufacturer_id = '010f' self.node.product_type = '0b00' self.primary.command_class = const.COMMAND_CLASS_SENSOR_ALARM self.entity_id = 'binary_sensor.mock_node_mock_value' self.device_config = {self.entity_id: {}} self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} with patch.object(zwave, 'async_dispatcher_send') as \ mock_dispatch_send: values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert mock_dispatch_send.called assert len(mock_dispatch_send.mock_calls) == 1 args = mock_dispatch_send.mock_calls[0][1] assert args[1] == 'zwave_new_binary_sensor' @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_ignore(self, discovery, import_module): """Test ignore workaround.""" self.node.manufacturer_id = '010f' self.node.product_type = '0301' self.primary.command_class = const.COMMAND_CLASS_SWITCH_BINARY self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore(self, discovery, import_module): """Test ignore config.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_IGNORED: True }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore_with_registry(self, discovery, import_module): """Test ignore config. The case when the device is in entity registry. """ self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {'mock_component.registry_id': { zwave.CONF_IGNORED: True }} with patch.object(self.registry, 'async_schedule_save'): self.registry.async_get_or_create( 'mock_component', zwave.DOMAIN, '567-1000', suggested_object_id='registry_id') zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_platform_ignore(self, discovery, import_module): """Test platform ignore device.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } platform = MagicMock() import_module.return_value = platform platform.get_device.return_value = None zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_config_polling_intensity(self, discovery, import_module): """Test polling intensity.""" mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_POLLING_INTENSITY: 123, }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert discovery.async_load_platform.called assert self.primary.enable_poll.called assert len(self.primary.enable_poll.mock_calls) == 1 assert self.primary.enable_poll.mock_calls[0][1][0] == 123 class TestZwave(unittest.TestCase): """Test zwave init.""" def test_device_config_glob_is_ordered(self): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): """Tests for zwave services.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() # Initialize zwave setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.zwave_network = self.hass.data[DATA_NETWORK] self.zwave_network.state = MockNetwork.STATE_READY self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.block_till_done() def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() self.hass.stop() def test_add_node(self): """Test zwave add_node service.""" self.hass.services.call('zwave', 'add_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller .add_node.mock_calls) == 1 assert len(self.zwave_network.controller .add_node.mock_calls[0][1]) == 0 def test_add_node_secure(self): """Test zwave add_node_secure service.""" self.hass.services.call('zwave', 'add_node_secure', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller.add_node.mock_calls) == 1 assert (self.zwave_network.controller .add_node.mock_calls[0][1][0] is True) def test_remove_node(self): """Test zwave remove_node service.""" self.hass.services.call('zwave', 'remove_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.remove_node.called assert len(self.zwave_network.controller.remove_node.mock_calls) == 1 def test_cancel_command(self): """Test zwave cancel_command service.""" self.hass.services.call('zwave', 'cancel_command', {}) self.hass.block_till_done() assert self.zwave_network.controller.cancel_command.called assert len(self.zwave_network.controller .cancel_command.mock_calls) == 1 def test_heal_network(self): """Test zwave heal_network service.""" self.hass.services.call('zwave', 'heal_network', {}) self.hass.block_till_done() assert self.zwave_network.heal.called assert len(self.zwave_network.heal.mock_calls) == 1 def test_soft_reset(self): """Test zwave soft_reset service.""" self.hass.services.call('zwave', 'soft_reset', {}) self.hass.block_till_done() assert self.zwave_network.controller.soft_reset.called assert len(self.zwave_network.controller.soft_reset.mock_calls) == 1 def test_test_network(self): """Test zwave test_network service.""" self.hass.services.call('zwave', 'test_network', {}) self.hass.block_till_done() assert self.zwave_network.test.called assert len(self.zwave_network.test.mock_calls) == 1 def test_stop_network(self): """Test zwave stop_network service.""" with patch.object(self.hass.bus, 'fire') as mock_fire: self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() assert self.zwave_network.stop.called assert len(self.zwave_network.stop.mock_calls) == 1 assert mock_fire.called assert len(mock_fire.mock_calls) == 1 assert mock_fire.mock_calls[0][1][0] == const.EVENT_NETWORK_STOP def test_rename_node(self): """Test zwave rename_node service.""" self.zwave_network.nodes = {11: MagicMock()} self.hass.services.call('zwave', 'rename_node', { const.ATTR_NODE_ID: 11, const.ATTR_NAME: 'test_name', }) self.hass.block_till_done() assert self.zwave_network.nodes[11].name == 'test_name' def test_rename_value(self): """Test zwave rename_value service.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, label="Old Label") node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.label == "Old Label" self.hass.services.call('zwave', 'rename_value', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_NAME: "New Label", }) self.hass.block_till_done() assert value.label == "New Label" def test_set_poll_intensity_enable(self): """Test zwave set_poll_intensity service, successful set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 2 assert enable_poll.mock_calls[0][1][0] == 4 def test_set_poll_intensity_enable_failed(self): """Test zwave set_poll_intensity service, failed set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) value.enable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 1 def test_set_poll_intensity_disable(self): """Test zwave set_poll_intensity service, successful disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 2 def test_set_poll_intensity_disable_failed(self): """Test zwave set_poll_intensity service, failed disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) value.disable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 1 def test_remove_failed_node(self): """Test zwave remove_failed_node service.""" self.hass.services.call('zwave', 'remove_failed_node', { const.ATTR_NODE_ID: 12, }) self.hass.block_till_done() remove_failed_node = self.zwave_network.controller.remove_failed_node assert remove_failed_node.called assert len(remove_failed_node.mock_calls) == 1 assert remove_failed_node.mock_calls[0][1][0] == 12 def test_replace_failed_node(self): """Test zwave replace_failed_node service.""" self.hass.services.call('zwave', 'replace_failed_node', { const.ATTR_NODE_ID: 13, }) self.hass.block_till_done() replace_failed_node = self.zwave_network.controller.replace_failed_node assert replace_failed_node.called assert len(replace_failed_node.mock_calls) == 1 assert replace_failed_node.mock_calls[0][1][0] == 13 def test_set_config_parameter(self): """Test zwave set_config_parameter service.""" value_byte = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BYTE, ) value_list = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['item1', 'item2', 'item3'], ) value_button = MockValue( index=14, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BUTTON, ) value_list_int = MockValue( index=15, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['1', '2', '3'], ) value_bool = MockValue( index=16, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BOOL, ) node = MockNode(node_id=14) node.get_values.return_value = { 12: value_byte, 13: value_list, 14: value_button, 15: value_list_int, 16: value_bool } self.zwave_network.nodes = {14: node} # Byte self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 12, const.ATTR_CONFIG_VALUE: 7, }) self.hass.block_till_done() assert value_byte.data == 7 # List self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, const.ATTR_CONFIG_VALUE: 'item3', }) self.hass.block_till_done() assert value_list.data == 'item3' # Button self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 14, const.ATTR_CONFIG_VALUE: True, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called assert self.zwave_network.manager.releaseButton.called # List of Ints self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 15, const.ATTR_CONFIG_VALUE: 3, }) self.hass.block_till_done() assert value_list_int.data == '3' # Boolean Truthy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'True', }) self.hass.block_till_done() assert value_bool.data == 1 # Boolean Falsy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'False', }) self.hass.block_till_done() assert value_bool.data == 0 # Different Parameter Size self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 19, const.ATTR_CONFIG_VALUE: 0x01020304, const.ATTR_CONFIG_SIZE: 4 }) self.hass.block_till_done() assert node.set_config_param.called assert len(node.set_config_param.mock_calls) == 1 assert node.set_config_param.mock_calls[0][1][0] == 19 assert node.set_config_param.mock_calls[0][1][1] == 0x01020304 assert node.set_config_param.mock_calls[0][1][2] == 4 node.set_config_param.reset_mock() def test_print_config_parameter(self): """Test zwave print_config_parameter service.""" value1 = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, data=1234, ) value2 = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, data=2345, ) node = MockNode(node_id=14) node.values = {12: value1, 13: value2} self.zwave_network.nodes = {14: node} with patch.object(zwave, '_LOGGER') as mock_logger: self.hass.services.call('zwave', 'print_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, }) self.hass.block_till_done() assert mock_logger.info.called assert len(mock_logger.info.mock_calls) == 1 assert mock_logger.info.mock_calls[0][1][1] == 13 assert mock_logger.info.mock_calls[0][1][2] == 14 assert mock_logger.info.mock_calls[0][1][3] == 2345 def test_print_node(self): """Test zwave print_node_parameter service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} with self.assertLogs(level='DEBUG') as mock_logger: self.hass.services.call('zwave', 'print_node', { const.ATTR_NODE_ID: 14 }) self.hass.block_till_done() assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 15, }) self.hass.block_till_done() assert value.data == 15 node.can_wake_up_value = False self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 20, }) self.hass.block_till_done() assert value.data == 15 def test_reset_node_meters(self): """Test zwave reset_node_meters service.""" value = MockValue( instance=1, index=8, data=99.5, command_class=const.COMMAND_CLASS_METER, ) reset_value = MockValue( instance=1, index=33, command_class=const.COMMAND_CLASS_METER, ) node = MockNode(node_id=14) node.values = {8: value, 33: reset_value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, const.ATTR_INSTANCE: 2, }) self.hass.block_till_done() assert not self.zwave_network.manager.pressButton.called assert not self.zwave_network.manager.releaseButton.called self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called value_id, = self.zwave_network.manager.pressButton.mock_calls.pop(0)[1] assert value_id == reset_value.value_id assert self.zwave_network.manager.releaseButton.called value_id, = ( self.zwave_network.manager.releaseButton.mock_calls.pop(0)[1]) assert value_id == reset_value.value_id def test_add_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'add', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.add_association.called assert len(group.add_association.mock_calls) == 1 assert group.add_association.mock_calls[0][1][0] == 24 assert group.add_association.mock_calls[0][1][1] == 5 def test_remove_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'remove', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.remove_association.called assert len(group.remove_association.mock_calls) == 1 assert group.remove_association.mock_calls[0][1][0] == 24 assert group.remove_association.mock_calls[0][1][1] == 5 def test_refresh_entity(self): """Test zwave refresh_entity service.""" node = MockNode() value = MockValue(data=False, node=node, command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50, node=node, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = get_device(node=node, values=values, node_config={}) device.hass = self.hass device.entity_id = 'binary_sensor.mock_entity_id' self.hass.add_job(device.async_added_to_hass()) self.hass.block_till_done() self.hass.services.call('zwave', 'refresh_entity', { ATTR_ENTITY_ID: 'binary_sensor.mock_entity_id', }) self.hass.block_till_done() assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 assert sorted([node.refresh_value.mock_calls[0][1][0], node.refresh_value.mock_calls[1][1][0]]) == \ sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert node.refresh_info.called assert len(node.refresh_info.mock_calls) == 1 def test_set_node_value(self): """Test zwave set_node_value service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=4 ) node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR]) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12, const.ATTR_CONFIG_VALUE: 2, }) self.hass.block_till_done() assert self.zwave_network.nodes[14].values[12].data == 2 def test_refresh_node_value(self): """Test zwave refresh_node_value service.""" node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR], network=self.zwave_network) value = MockValue( node=node, index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=2 ) value.refresh = MagicMock() node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12 }) self.hass.block_till_done() assert value.refresh.called def test_heal_node(self): """Test zwave heal_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'heal_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.heal.called assert len(node.heal.mock_calls) == 1 def test_test_node(self): """Test the zwave test_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'test_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.test.called assert len(node.test.mock_calls) == 1
jabesq/home-assistant
tests/components/zwave/test_init.py
homeassistant/components/lutron/scene.py
"""Support for transport.opendata.ch.""" from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ATTR_ATTRIBUTION, CONF_NAME from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity import homeassistant.util.dt as dt_util _LOGGER = logging.getLogger(__name__) ATTR_DEPARTURE_TIME1 = 'next_departure' ATTR_DEPARTURE_TIME2 = 'next_on_departure' ATTR_DURATION = 'duration' ATTR_PLATFORM = 'platform' ATTR_REMAINING_TIME = 'remaining_time' ATTR_START = 'start' ATTR_TARGET = 'destination' ATTR_TRAIN_NUMBER = 'train_number' ATTR_TRANSFERS = 'transfers' ATTRIBUTION = "Data provided by transport.opendata.ch" CONF_DESTINATION = 'to' CONF_START = 'from' DEFAULT_NAME = 'Next Departure' ICON = 'mdi:bus' SCAN_INTERVAL = timedelta(seconds=90) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_DESTINATION): cv.string, vol.Required(CONF_START): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, }) async def async_setup_platform( hass, config, async_add_entities, discovery_info=None): """Set up the Swiss public transport sensor.""" from opendata_transport import OpendataTransport, exceptions name = config.get(CONF_NAME) start = config.get(CONF_START) destination = config.get(CONF_DESTINATION) session = async_get_clientsession(hass) opendata = OpendataTransport(start, destination, hass.loop, session) try: await opendata.async_get_data() except exceptions.OpendataTransportError: _LOGGER.error( "Check at http://transport.opendata.ch/examples/stationboard.html " "if your station names are valid") return async_add_entities( [SwissPublicTransportSensor(opendata, start, destination, name)]) class SwissPublicTransportSensor(Entity): """Implementation of an Swiss public transport sensor.""" def __init__(self, opendata, start, destination, name): """Initialize the sensor.""" self._opendata = opendata self._name = name self._from = start self._to = destination self._remaining_time = "" @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._opendata.connections[0]['departure'] \ if self._opendata is not None else None @property def device_state_attributes(self): """Return the state attributes.""" if self._opendata is None: return self._remaining_time = dt_util.parse_datetime( self._opendata.connections[0]['departure']) -\ dt_util.as_local(dt_util.utcnow()) attr = { ATTR_TRAIN_NUMBER: self._opendata.connections[0]['number'], ATTR_PLATFORM: self._opendata.connections[0]['platform'], ATTR_TRANSFERS: self._opendata.connections[0]['transfers'], ATTR_DURATION: self._opendata.connections[0]['duration'], ATTR_DEPARTURE_TIME1: self._opendata.connections[1]['departure'], ATTR_DEPARTURE_TIME2: self._opendata.connections[2]['departure'], ATTR_START: self._opendata.from_name, ATTR_TARGET: self._opendata.to_name, ATTR_REMAINING_TIME: '{}'.format(self._remaining_time), ATTR_ATTRIBUTION: ATTRIBUTION, } return attr @property def icon(self): """Icon to use in the frontend, if any.""" return ICON async def async_update(self): """Get the latest data from opendata.ch and update the states.""" from opendata_transport.exceptions import OpendataTransportError try: if self._remaining_time.total_seconds() < 0: await self._opendata.async_get_data() except OpendataTransportError: _LOGGER.error("Unable to retrieve data from transport.opendata.ch")
"""Tests for the Z-Wave init.""" import asyncio from collections import OrderedDict from datetime import datetime import unittest from unittest.mock import MagicMock, patch import pytest from pytz import utc import voluptuous as vol from homeassistant.bootstrap import async_setup_component from homeassistant.components import zwave from homeassistant.components.zwave import ( CONF_DEVICE_CONFIG_GLOB, CONFIG_SCHEMA, DATA_NETWORK, const) from homeassistant.components.zwave.binary_sensor import get_device from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.device_registry import ( async_get_registry as get_dev_reg) from homeassistant.setup import setup_component from tests.common import ( async_fire_time_changed, get_test_home_assistant, mock_coro, mock_registry) from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue async def test_valid_device_config(hass, mock_openzwave): """Test valid device config.""" device_config = { 'light.kitchen': { 'ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert result async def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = { 'light.kitchen': { 'some_ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert not result def test_config_access_error(): """Test threading error accessing config values.""" node = MagicMock() def side_effect(): raise RuntimeError node.values.values.side_effect = side_effect result = zwave.get_config_value(node, 1) assert result is None async def test_network_options(hass, mock_openzwave): """Test network options.""" result = await async_setup_component(hass, 'zwave', { 'zwave': { 'usb_path': 'mock_usb_path', 'config_path': 'mock_config_path', }}) await hass.async_block_till_done() assert result network = hass.data[zwave.DATA_NETWORK] assert network.options.device == 'mock_usb_path' assert network.options.config_path == 'mock_config_path' async def test_network_key_validation(hass, mock_openzwave): """Test network key validation.""" test_values = [ ('0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,' '0x0E,0x0F,0x10'), ] for value in test_values: result = zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) assert result['zwave']['network_key'] == value async def test_erronous_network_key_fails_validation(hass, mock_openzwave): """Test failing erronous network key validation.""" test_values = [ ('0x 01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0X01,0X02,0X03,0X04,0X05,0X06,0X07,0X08,0X09,0X0A,0X0B,0X0C,0X0D,' '0X0E,0X0F,0X10'), 'invalid', '1234567', 1234567 ] for value in test_values: with pytest.raises(vol.Invalid): zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) async def test_auto_heal_midnight(hass, mock_openzwave): """Test network auto-heal at midnight.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': True, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert network.heal.called assert len(network.heal.mock_calls) == 1 async def test_auto_heal_disabled(hass, mock_openzwave): """Test network auto-heal disabled.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': False, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert not network.heal.called async def test_setup_platform(hass, mock_openzwave): """Test invalid device config.""" mock_device = MagicMock() hass.data[DATA_NETWORK] = MagicMock() hass.data[zwave.DATA_DEVICES] = {456: mock_device} async_add_entities = MagicMock() result = await zwave.async_setup_platform( hass, None, async_add_entities, None) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 123}) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 456}) assert result assert async_add_entities.called assert len(async_add_entities.mock_calls) == 1 assert async_add_entities.mock_calls[0][1][0] == [mock_device] async def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): """Test device entity base class.""" node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.value_added() device.update_properties() await hass.async_block_till_done() assert not device.should_poll assert device.unique_id == "10-11" assert device.name == 'Mock Node Sensor' assert device.device_state_attributes[zwave.ATTR_POWER] == 50.123 async def test_node_removed(hass, mock_openzwave): """Test node removed in base class.""" # Create a mock node & node entity node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.entity_id = 'zwave.mock_node' device.value_added() device.update_properties() await hass.async_block_till_done() # Save it to the entity registry registry = mock_registry(hass) registry.async_get_or_create('zwave', 'zwave', device.unique_id) device.entity_id = registry.async_get_entity_id( 'zwave', 'zwave', device.unique_id) # Create dummy entity registry entries for other integrations hue_entity = registry.async_get_or_create('light', 'hue', 1234) zha_entity = registry.async_get_or_create('sensor', 'zha', 5678) # Verify our Z-Wave entity is registered assert registry.async_is_registered(device.entity_id) # Remove it entity_id = device.entity_id await device.node_removed() # Verify registry entry for our Z-Wave node is gone assert not registry.async_is_registered(entity_id) # Verify registry entries for our other entities remain assert registry.async_is_registered(hue_entity.entity_id) assert registry.async_is_registered(zha_entity.entity_id) async def test_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node').state == 'unknown' async def test_unparsed_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode( node_id=14, manufacturer_name=None, name=None, is_ready=False) sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert len(sleeps) == const.NODE_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1:] == \ (14, const.NODE_READY_WAIT_SECS) assert hass.states.get('zwave.unknown_node_14').state == 'unknown' async def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': { 'device_config': { 'zwave.mock_node': { 'ignored': True, }}}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None async def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' async def test_value_entities(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = {} def mock_connect(receiver, signal, *args, **kwargs): mock_receivers[signal] = receiver with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert mock_receivers hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_ALL_NODES_QUERIED]) node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) zwave_network.nodes = {node.node_id: node} value = MockValue( data=False, node=node, index=12, instance=1, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values = {'primary': value, value.value_id: value} value2 = MockValue( data=False, node=node, index=12, instance=2, label="Mock Value B", command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values[value2.value_id] = value2 hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_NODE_ADDED], node) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value2) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' assert hass.states.get( 'binary_sensor.mock_node_mock_value_b').state == 'off' ent_reg = await async_get_registry(hass) dev_reg = await get_dev_reg(hass) entry = ent_reg.async_get('zwave.mock_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) node_dev_id = entry.device_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) assert entry.name is None assert entry.device_id == node_dev_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value2.object_id) assert entry.name is None assert entry.device_id != node_dev_id device_id_b = entry.device_id device = dev_reg.async_get(node_dev_id) assert device is not None assert device.name == node.name old_device = device device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming without updating await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_NAME: "Demo Node", }) await hass.async_block_till_done() assert node.name == "Demo Node" entry = ent_reg.async_get('zwave.mock_node') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Node", }) await hass.async_block_till_done() assert node.name == "New Node" entry = ent_reg.async_get('zwave.new_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) entry = ent_reg.async_get('binary_sensor.new_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) await hass.services.async_call('zwave', 'rename_value', { const.ATTR_NODE_ID: node.node_id, const.ATTR_VALUE_ID: value.object_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Label", }) await hass.async_block_till_done() entry = ent_reg.async_get('binary_sensor.new_node_new_label') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) async def test_value_discovery_existing_entity(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_THERMOSTAT) setpoint = MockValue( data=22.0, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, setpoint) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] is None def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): temperature = MockValue( data=23.5, node=node, index=1, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, temperature) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] == 23.5 async def test_power_schemes(hass, mock_openzwave): """Test power attribute.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SWITCH_BINARY) switch = MockValue( data=True, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SWITCH_BINARY, genre=const.GENRE_USER, type=const.TYPE_BOOL) hass.async_add_job(mock_receivers[0], node, switch) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').state == 'on' assert 'power_consumption' not in hass.states.get( 'switch.mock_node_mock_value').attributes def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): power = MockValue( data=23.5, node=node, index=const.INDEX_SENSOR_MULTILEVEL_POWER, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL) hass.async_add_job(mock_receivers[0], node, power) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').attributes[ 'power_consumption'] == 23.5 async def test_network_ready(hass, mock_openzwave): """Test Node network ready event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete_some_dead(hass, mock_openzwave): """Test Node network complete some dead event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE_SOME_DEAD, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 class TestZWaveDeviceEntityValues(unittest.TestCase): """Tests for the ZWaveDeviceEntityValues helper.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() self.registry = mock_registry(self.hass) setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.node = MockNode() self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: ['mock_primary_class'], }, 'secondary': { const.DISC_COMMAND_CLASS: ['mock_secondary_class'], }, 'optional': { const.DISC_COMMAND_CLASS: ['mock_optional_class'], const.DISC_OPTIONAL: True, }}} self.primary = MockValue( command_class='mock_primary_class', node=self.node, value_id=1000) self.secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.duplicate_secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.optional = MockValue( command_class='mock_optional_class', node=self.node) self.no_match_value = MockValue( command_class='mock_bad_class', node=self.node) self.entity_id = 'mock_component.mock_node_mock_value' self.zwave_config = {'zwave': {}} self.device_config = {self.entity_id: {}} def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) assert values.primary is self.primary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) self.hass.block_till_done() assert values.secondary is self.secondary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config discovery.async_load_platform.reset_mock() values.check_value(self.optional) values.check_value(self.duplicate_secondary) values.check_value(self.no_match_value) self.hass.block_till_done() assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called assert len(values._entity.value_added.mock_calls) == 1 assert values._entity.value_changed.called assert len(values._entity.value_changed.mock_calls) == 1 @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, self.optional.value_id: self.optional, self.no_match_value.value_id: self.no_match_value, } values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert values.primary is self.primary assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config assert not self.primary.enable_poll.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_node_schema_mismatch(self, discovery, import_module): """Test node schema mismatch.""" self.node.generic = 'no_match' self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.mock_schema[const.DISC_GENERIC_DEVICE_CLASS] = ['generic_match'] values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.manufacturer_id = '010f' self.node.product_type = '0b00' self.primary.command_class = const.COMMAND_CLASS_SENSOR_ALARM self.entity_id = 'binary_sensor.mock_node_mock_value' self.device_config = {self.entity_id: {}} self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} with patch.object(zwave, 'async_dispatcher_send') as \ mock_dispatch_send: values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert mock_dispatch_send.called assert len(mock_dispatch_send.mock_calls) == 1 args = mock_dispatch_send.mock_calls[0][1] assert args[1] == 'zwave_new_binary_sensor' @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_ignore(self, discovery, import_module): """Test ignore workaround.""" self.node.manufacturer_id = '010f' self.node.product_type = '0301' self.primary.command_class = const.COMMAND_CLASS_SWITCH_BINARY self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore(self, discovery, import_module): """Test ignore config.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_IGNORED: True }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore_with_registry(self, discovery, import_module): """Test ignore config. The case when the device is in entity registry. """ self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {'mock_component.registry_id': { zwave.CONF_IGNORED: True }} with patch.object(self.registry, 'async_schedule_save'): self.registry.async_get_or_create( 'mock_component', zwave.DOMAIN, '567-1000', suggested_object_id='registry_id') zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_platform_ignore(self, discovery, import_module): """Test platform ignore device.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } platform = MagicMock() import_module.return_value = platform platform.get_device.return_value = None zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_config_polling_intensity(self, discovery, import_module): """Test polling intensity.""" mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_POLLING_INTENSITY: 123, }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert discovery.async_load_platform.called assert self.primary.enable_poll.called assert len(self.primary.enable_poll.mock_calls) == 1 assert self.primary.enable_poll.mock_calls[0][1][0] == 123 class TestZwave(unittest.TestCase): """Test zwave init.""" def test_device_config_glob_is_ordered(self): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): """Tests for zwave services.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() # Initialize zwave setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.zwave_network = self.hass.data[DATA_NETWORK] self.zwave_network.state = MockNetwork.STATE_READY self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.block_till_done() def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() self.hass.stop() def test_add_node(self): """Test zwave add_node service.""" self.hass.services.call('zwave', 'add_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller .add_node.mock_calls) == 1 assert len(self.zwave_network.controller .add_node.mock_calls[0][1]) == 0 def test_add_node_secure(self): """Test zwave add_node_secure service.""" self.hass.services.call('zwave', 'add_node_secure', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller.add_node.mock_calls) == 1 assert (self.zwave_network.controller .add_node.mock_calls[0][1][0] is True) def test_remove_node(self): """Test zwave remove_node service.""" self.hass.services.call('zwave', 'remove_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.remove_node.called assert len(self.zwave_network.controller.remove_node.mock_calls) == 1 def test_cancel_command(self): """Test zwave cancel_command service.""" self.hass.services.call('zwave', 'cancel_command', {}) self.hass.block_till_done() assert self.zwave_network.controller.cancel_command.called assert len(self.zwave_network.controller .cancel_command.mock_calls) == 1 def test_heal_network(self): """Test zwave heal_network service.""" self.hass.services.call('zwave', 'heal_network', {}) self.hass.block_till_done() assert self.zwave_network.heal.called assert len(self.zwave_network.heal.mock_calls) == 1 def test_soft_reset(self): """Test zwave soft_reset service.""" self.hass.services.call('zwave', 'soft_reset', {}) self.hass.block_till_done() assert self.zwave_network.controller.soft_reset.called assert len(self.zwave_network.controller.soft_reset.mock_calls) == 1 def test_test_network(self): """Test zwave test_network service.""" self.hass.services.call('zwave', 'test_network', {}) self.hass.block_till_done() assert self.zwave_network.test.called assert len(self.zwave_network.test.mock_calls) == 1 def test_stop_network(self): """Test zwave stop_network service.""" with patch.object(self.hass.bus, 'fire') as mock_fire: self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() assert self.zwave_network.stop.called assert len(self.zwave_network.stop.mock_calls) == 1 assert mock_fire.called assert len(mock_fire.mock_calls) == 1 assert mock_fire.mock_calls[0][1][0] == const.EVENT_NETWORK_STOP def test_rename_node(self): """Test zwave rename_node service.""" self.zwave_network.nodes = {11: MagicMock()} self.hass.services.call('zwave', 'rename_node', { const.ATTR_NODE_ID: 11, const.ATTR_NAME: 'test_name', }) self.hass.block_till_done() assert self.zwave_network.nodes[11].name == 'test_name' def test_rename_value(self): """Test zwave rename_value service.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, label="Old Label") node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.label == "Old Label" self.hass.services.call('zwave', 'rename_value', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_NAME: "New Label", }) self.hass.block_till_done() assert value.label == "New Label" def test_set_poll_intensity_enable(self): """Test zwave set_poll_intensity service, successful set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 2 assert enable_poll.mock_calls[0][1][0] == 4 def test_set_poll_intensity_enable_failed(self): """Test zwave set_poll_intensity service, failed set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) value.enable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 1 def test_set_poll_intensity_disable(self): """Test zwave set_poll_intensity service, successful disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 2 def test_set_poll_intensity_disable_failed(self): """Test zwave set_poll_intensity service, failed disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) value.disable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 1 def test_remove_failed_node(self): """Test zwave remove_failed_node service.""" self.hass.services.call('zwave', 'remove_failed_node', { const.ATTR_NODE_ID: 12, }) self.hass.block_till_done() remove_failed_node = self.zwave_network.controller.remove_failed_node assert remove_failed_node.called assert len(remove_failed_node.mock_calls) == 1 assert remove_failed_node.mock_calls[0][1][0] == 12 def test_replace_failed_node(self): """Test zwave replace_failed_node service.""" self.hass.services.call('zwave', 'replace_failed_node', { const.ATTR_NODE_ID: 13, }) self.hass.block_till_done() replace_failed_node = self.zwave_network.controller.replace_failed_node assert replace_failed_node.called assert len(replace_failed_node.mock_calls) == 1 assert replace_failed_node.mock_calls[0][1][0] == 13 def test_set_config_parameter(self): """Test zwave set_config_parameter service.""" value_byte = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BYTE, ) value_list = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['item1', 'item2', 'item3'], ) value_button = MockValue( index=14, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BUTTON, ) value_list_int = MockValue( index=15, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['1', '2', '3'], ) value_bool = MockValue( index=16, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BOOL, ) node = MockNode(node_id=14) node.get_values.return_value = { 12: value_byte, 13: value_list, 14: value_button, 15: value_list_int, 16: value_bool } self.zwave_network.nodes = {14: node} # Byte self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 12, const.ATTR_CONFIG_VALUE: 7, }) self.hass.block_till_done() assert value_byte.data == 7 # List self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, const.ATTR_CONFIG_VALUE: 'item3', }) self.hass.block_till_done() assert value_list.data == 'item3' # Button self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 14, const.ATTR_CONFIG_VALUE: True, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called assert self.zwave_network.manager.releaseButton.called # List of Ints self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 15, const.ATTR_CONFIG_VALUE: 3, }) self.hass.block_till_done() assert value_list_int.data == '3' # Boolean Truthy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'True', }) self.hass.block_till_done() assert value_bool.data == 1 # Boolean Falsy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'False', }) self.hass.block_till_done() assert value_bool.data == 0 # Different Parameter Size self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 19, const.ATTR_CONFIG_VALUE: 0x01020304, const.ATTR_CONFIG_SIZE: 4 }) self.hass.block_till_done() assert node.set_config_param.called assert len(node.set_config_param.mock_calls) == 1 assert node.set_config_param.mock_calls[0][1][0] == 19 assert node.set_config_param.mock_calls[0][1][1] == 0x01020304 assert node.set_config_param.mock_calls[0][1][2] == 4 node.set_config_param.reset_mock() def test_print_config_parameter(self): """Test zwave print_config_parameter service.""" value1 = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, data=1234, ) value2 = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, data=2345, ) node = MockNode(node_id=14) node.values = {12: value1, 13: value2} self.zwave_network.nodes = {14: node} with patch.object(zwave, '_LOGGER') as mock_logger: self.hass.services.call('zwave', 'print_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, }) self.hass.block_till_done() assert mock_logger.info.called assert len(mock_logger.info.mock_calls) == 1 assert mock_logger.info.mock_calls[0][1][1] == 13 assert mock_logger.info.mock_calls[0][1][2] == 14 assert mock_logger.info.mock_calls[0][1][3] == 2345 def test_print_node(self): """Test zwave print_node_parameter service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} with self.assertLogs(level='DEBUG') as mock_logger: self.hass.services.call('zwave', 'print_node', { const.ATTR_NODE_ID: 14 }) self.hass.block_till_done() assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 15, }) self.hass.block_till_done() assert value.data == 15 node.can_wake_up_value = False self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 20, }) self.hass.block_till_done() assert value.data == 15 def test_reset_node_meters(self): """Test zwave reset_node_meters service.""" value = MockValue( instance=1, index=8, data=99.5, command_class=const.COMMAND_CLASS_METER, ) reset_value = MockValue( instance=1, index=33, command_class=const.COMMAND_CLASS_METER, ) node = MockNode(node_id=14) node.values = {8: value, 33: reset_value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, const.ATTR_INSTANCE: 2, }) self.hass.block_till_done() assert not self.zwave_network.manager.pressButton.called assert not self.zwave_network.manager.releaseButton.called self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called value_id, = self.zwave_network.manager.pressButton.mock_calls.pop(0)[1] assert value_id == reset_value.value_id assert self.zwave_network.manager.releaseButton.called value_id, = ( self.zwave_network.manager.releaseButton.mock_calls.pop(0)[1]) assert value_id == reset_value.value_id def test_add_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'add', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.add_association.called assert len(group.add_association.mock_calls) == 1 assert group.add_association.mock_calls[0][1][0] == 24 assert group.add_association.mock_calls[0][1][1] == 5 def test_remove_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'remove', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.remove_association.called assert len(group.remove_association.mock_calls) == 1 assert group.remove_association.mock_calls[0][1][0] == 24 assert group.remove_association.mock_calls[0][1][1] == 5 def test_refresh_entity(self): """Test zwave refresh_entity service.""" node = MockNode() value = MockValue(data=False, node=node, command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50, node=node, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = get_device(node=node, values=values, node_config={}) device.hass = self.hass device.entity_id = 'binary_sensor.mock_entity_id' self.hass.add_job(device.async_added_to_hass()) self.hass.block_till_done() self.hass.services.call('zwave', 'refresh_entity', { ATTR_ENTITY_ID: 'binary_sensor.mock_entity_id', }) self.hass.block_till_done() assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 assert sorted([node.refresh_value.mock_calls[0][1][0], node.refresh_value.mock_calls[1][1][0]]) == \ sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert node.refresh_info.called assert len(node.refresh_info.mock_calls) == 1 def test_set_node_value(self): """Test zwave set_node_value service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=4 ) node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR]) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12, const.ATTR_CONFIG_VALUE: 2, }) self.hass.block_till_done() assert self.zwave_network.nodes[14].values[12].data == 2 def test_refresh_node_value(self): """Test zwave refresh_node_value service.""" node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR], network=self.zwave_network) value = MockValue( node=node, index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=2 ) value.refresh = MagicMock() node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12 }) self.hass.block_till_done() assert value.refresh.called def test_heal_node(self): """Test zwave heal_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'heal_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.heal.called assert len(node.heal.mock_calls) == 1 def test_test_node(self): """Test the zwave test_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'test_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.test.called assert len(node.test.mock_calls) == 1
jabesq/home-assistant
tests/components/zwave/test_init.py
homeassistant/components/swiss_public_transport/sensor.py
"""Class to hold all alarm control panel accessories.""" import logging from pyhap.const import CATEGORY_ALARM_SYSTEM from homeassistant.components.alarm_control_panel import DOMAIN from homeassistant.const import ( ATTR_CODE, ATTR_ENTITY_ID, SERVICE_ALARM_ARM_AWAY, SERVICE_ALARM_ARM_HOME, SERVICE_ALARM_ARM_NIGHT, SERVICE_ALARM_DISARM, STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, STATE_ALARM_ARMED_NIGHT, STATE_ALARM_DISARMED, STATE_ALARM_TRIGGERED) from . import TYPES from .accessories import HomeAccessory from .const import ( CHAR_CURRENT_SECURITY_STATE, CHAR_TARGET_SECURITY_STATE, SERV_SECURITY_SYSTEM) _LOGGER = logging.getLogger(__name__) HASS_TO_HOMEKIT = { STATE_ALARM_ARMED_HOME: 0, STATE_ALARM_ARMED_AWAY: 1, STATE_ALARM_ARMED_NIGHT: 2, STATE_ALARM_DISARMED: 3, STATE_ALARM_TRIGGERED: 4, } HOMEKIT_TO_HASS = {c: s for s, c in HASS_TO_HOMEKIT.items()} STATE_TO_SERVICE = { STATE_ALARM_ARMED_AWAY: SERVICE_ALARM_ARM_AWAY, STATE_ALARM_ARMED_HOME: SERVICE_ALARM_ARM_HOME, STATE_ALARM_ARMED_NIGHT: SERVICE_ALARM_ARM_NIGHT, STATE_ALARM_DISARMED: SERVICE_ALARM_DISARM, } @TYPES.register('SecuritySystem') class SecuritySystem(HomeAccessory): """Generate an SecuritySystem accessory for an alarm control panel.""" def __init__(self, *args): """Initialize a SecuritySystem accessory object.""" super().__init__(*args, category=CATEGORY_ALARM_SYSTEM) self._alarm_code = self.config.get(ATTR_CODE) self._flag_state = False serv_alarm = self.add_preload_service(SERV_SECURITY_SYSTEM) self.char_current_state = serv_alarm.configure_char( CHAR_CURRENT_SECURITY_STATE, value=3) self.char_target_state = serv_alarm.configure_char( CHAR_TARGET_SECURITY_STATE, value=3, setter_callback=self.set_security_state) def set_security_state(self, value): """Move security state to value if call came from HomeKit.""" _LOGGER.debug('%s: Set security state to %d', self.entity_id, value) self._flag_state = True hass_value = HOMEKIT_TO_HASS[value] service = STATE_TO_SERVICE[hass_value] params = {ATTR_ENTITY_ID: self.entity_id} if self._alarm_code: params[ATTR_CODE] = self._alarm_code self.call_service(DOMAIN, service, params) def update_state(self, new_state): """Update security state after state changed.""" hass_state = new_state.state if hass_state in HASS_TO_HOMEKIT: current_security_state = HASS_TO_HOMEKIT[hass_state] self.char_current_state.set_value(current_security_state) _LOGGER.debug('%s: Updated current state to %s (%d)', self.entity_id, hass_state, current_security_state) # SecuritySystemTargetState does not support triggered if not self._flag_state and \ hass_state != STATE_ALARM_TRIGGERED: self.char_target_state.set_value(current_security_state) self._flag_state = False
"""Tests for the Z-Wave init.""" import asyncio from collections import OrderedDict from datetime import datetime import unittest from unittest.mock import MagicMock, patch import pytest from pytz import utc import voluptuous as vol from homeassistant.bootstrap import async_setup_component from homeassistant.components import zwave from homeassistant.components.zwave import ( CONF_DEVICE_CONFIG_GLOB, CONFIG_SCHEMA, DATA_NETWORK, const) from homeassistant.components.zwave.binary_sensor import get_device from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.device_registry import ( async_get_registry as get_dev_reg) from homeassistant.setup import setup_component from tests.common import ( async_fire_time_changed, get_test_home_assistant, mock_coro, mock_registry) from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue async def test_valid_device_config(hass, mock_openzwave): """Test valid device config.""" device_config = { 'light.kitchen': { 'ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert result async def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = { 'light.kitchen': { 'some_ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert not result def test_config_access_error(): """Test threading error accessing config values.""" node = MagicMock() def side_effect(): raise RuntimeError node.values.values.side_effect = side_effect result = zwave.get_config_value(node, 1) assert result is None async def test_network_options(hass, mock_openzwave): """Test network options.""" result = await async_setup_component(hass, 'zwave', { 'zwave': { 'usb_path': 'mock_usb_path', 'config_path': 'mock_config_path', }}) await hass.async_block_till_done() assert result network = hass.data[zwave.DATA_NETWORK] assert network.options.device == 'mock_usb_path' assert network.options.config_path == 'mock_config_path' async def test_network_key_validation(hass, mock_openzwave): """Test network key validation.""" test_values = [ ('0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,' '0x0E,0x0F,0x10'), ] for value in test_values: result = zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) assert result['zwave']['network_key'] == value async def test_erronous_network_key_fails_validation(hass, mock_openzwave): """Test failing erronous network key validation.""" test_values = [ ('0x 01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0X01,0X02,0X03,0X04,0X05,0X06,0X07,0X08,0X09,0X0A,0X0B,0X0C,0X0D,' '0X0E,0X0F,0X10'), 'invalid', '1234567', 1234567 ] for value in test_values: with pytest.raises(vol.Invalid): zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) async def test_auto_heal_midnight(hass, mock_openzwave): """Test network auto-heal at midnight.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': True, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert network.heal.called assert len(network.heal.mock_calls) == 1 async def test_auto_heal_disabled(hass, mock_openzwave): """Test network auto-heal disabled.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': False, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert not network.heal.called async def test_setup_platform(hass, mock_openzwave): """Test invalid device config.""" mock_device = MagicMock() hass.data[DATA_NETWORK] = MagicMock() hass.data[zwave.DATA_DEVICES] = {456: mock_device} async_add_entities = MagicMock() result = await zwave.async_setup_platform( hass, None, async_add_entities, None) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 123}) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 456}) assert result assert async_add_entities.called assert len(async_add_entities.mock_calls) == 1 assert async_add_entities.mock_calls[0][1][0] == [mock_device] async def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): """Test device entity base class.""" node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.value_added() device.update_properties() await hass.async_block_till_done() assert not device.should_poll assert device.unique_id == "10-11" assert device.name == 'Mock Node Sensor' assert device.device_state_attributes[zwave.ATTR_POWER] == 50.123 async def test_node_removed(hass, mock_openzwave): """Test node removed in base class.""" # Create a mock node & node entity node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.entity_id = 'zwave.mock_node' device.value_added() device.update_properties() await hass.async_block_till_done() # Save it to the entity registry registry = mock_registry(hass) registry.async_get_or_create('zwave', 'zwave', device.unique_id) device.entity_id = registry.async_get_entity_id( 'zwave', 'zwave', device.unique_id) # Create dummy entity registry entries for other integrations hue_entity = registry.async_get_or_create('light', 'hue', 1234) zha_entity = registry.async_get_or_create('sensor', 'zha', 5678) # Verify our Z-Wave entity is registered assert registry.async_is_registered(device.entity_id) # Remove it entity_id = device.entity_id await device.node_removed() # Verify registry entry for our Z-Wave node is gone assert not registry.async_is_registered(entity_id) # Verify registry entries for our other entities remain assert registry.async_is_registered(hue_entity.entity_id) assert registry.async_is_registered(zha_entity.entity_id) async def test_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node').state == 'unknown' async def test_unparsed_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode( node_id=14, manufacturer_name=None, name=None, is_ready=False) sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert len(sleeps) == const.NODE_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1:] == \ (14, const.NODE_READY_WAIT_SECS) assert hass.states.get('zwave.unknown_node_14').state == 'unknown' async def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': { 'device_config': { 'zwave.mock_node': { 'ignored': True, }}}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None async def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' async def test_value_entities(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = {} def mock_connect(receiver, signal, *args, **kwargs): mock_receivers[signal] = receiver with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert mock_receivers hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_ALL_NODES_QUERIED]) node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) zwave_network.nodes = {node.node_id: node} value = MockValue( data=False, node=node, index=12, instance=1, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values = {'primary': value, value.value_id: value} value2 = MockValue( data=False, node=node, index=12, instance=2, label="Mock Value B", command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values[value2.value_id] = value2 hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_NODE_ADDED], node) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value2) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' assert hass.states.get( 'binary_sensor.mock_node_mock_value_b').state == 'off' ent_reg = await async_get_registry(hass) dev_reg = await get_dev_reg(hass) entry = ent_reg.async_get('zwave.mock_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) node_dev_id = entry.device_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) assert entry.name is None assert entry.device_id == node_dev_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value2.object_id) assert entry.name is None assert entry.device_id != node_dev_id device_id_b = entry.device_id device = dev_reg.async_get(node_dev_id) assert device is not None assert device.name == node.name old_device = device device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming without updating await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_NAME: "Demo Node", }) await hass.async_block_till_done() assert node.name == "Demo Node" entry = ent_reg.async_get('zwave.mock_node') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Node", }) await hass.async_block_till_done() assert node.name == "New Node" entry = ent_reg.async_get('zwave.new_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) entry = ent_reg.async_get('binary_sensor.new_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) await hass.services.async_call('zwave', 'rename_value', { const.ATTR_NODE_ID: node.node_id, const.ATTR_VALUE_ID: value.object_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Label", }) await hass.async_block_till_done() entry = ent_reg.async_get('binary_sensor.new_node_new_label') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) async def test_value_discovery_existing_entity(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_THERMOSTAT) setpoint = MockValue( data=22.0, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, setpoint) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] is None def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): temperature = MockValue( data=23.5, node=node, index=1, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, temperature) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] == 23.5 async def test_power_schemes(hass, mock_openzwave): """Test power attribute.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SWITCH_BINARY) switch = MockValue( data=True, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SWITCH_BINARY, genre=const.GENRE_USER, type=const.TYPE_BOOL) hass.async_add_job(mock_receivers[0], node, switch) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').state == 'on' assert 'power_consumption' not in hass.states.get( 'switch.mock_node_mock_value').attributes def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): power = MockValue( data=23.5, node=node, index=const.INDEX_SENSOR_MULTILEVEL_POWER, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL) hass.async_add_job(mock_receivers[0], node, power) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').attributes[ 'power_consumption'] == 23.5 async def test_network_ready(hass, mock_openzwave): """Test Node network ready event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete_some_dead(hass, mock_openzwave): """Test Node network complete some dead event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE_SOME_DEAD, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 class TestZWaveDeviceEntityValues(unittest.TestCase): """Tests for the ZWaveDeviceEntityValues helper.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() self.registry = mock_registry(self.hass) setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.node = MockNode() self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: ['mock_primary_class'], }, 'secondary': { const.DISC_COMMAND_CLASS: ['mock_secondary_class'], }, 'optional': { const.DISC_COMMAND_CLASS: ['mock_optional_class'], const.DISC_OPTIONAL: True, }}} self.primary = MockValue( command_class='mock_primary_class', node=self.node, value_id=1000) self.secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.duplicate_secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.optional = MockValue( command_class='mock_optional_class', node=self.node) self.no_match_value = MockValue( command_class='mock_bad_class', node=self.node) self.entity_id = 'mock_component.mock_node_mock_value' self.zwave_config = {'zwave': {}} self.device_config = {self.entity_id: {}} def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) assert values.primary is self.primary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) self.hass.block_till_done() assert values.secondary is self.secondary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config discovery.async_load_platform.reset_mock() values.check_value(self.optional) values.check_value(self.duplicate_secondary) values.check_value(self.no_match_value) self.hass.block_till_done() assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called assert len(values._entity.value_added.mock_calls) == 1 assert values._entity.value_changed.called assert len(values._entity.value_changed.mock_calls) == 1 @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, self.optional.value_id: self.optional, self.no_match_value.value_id: self.no_match_value, } values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert values.primary is self.primary assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config assert not self.primary.enable_poll.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_node_schema_mismatch(self, discovery, import_module): """Test node schema mismatch.""" self.node.generic = 'no_match' self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.mock_schema[const.DISC_GENERIC_DEVICE_CLASS] = ['generic_match'] values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.manufacturer_id = '010f' self.node.product_type = '0b00' self.primary.command_class = const.COMMAND_CLASS_SENSOR_ALARM self.entity_id = 'binary_sensor.mock_node_mock_value' self.device_config = {self.entity_id: {}} self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} with patch.object(zwave, 'async_dispatcher_send') as \ mock_dispatch_send: values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert mock_dispatch_send.called assert len(mock_dispatch_send.mock_calls) == 1 args = mock_dispatch_send.mock_calls[0][1] assert args[1] == 'zwave_new_binary_sensor' @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_ignore(self, discovery, import_module): """Test ignore workaround.""" self.node.manufacturer_id = '010f' self.node.product_type = '0301' self.primary.command_class = const.COMMAND_CLASS_SWITCH_BINARY self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore(self, discovery, import_module): """Test ignore config.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_IGNORED: True }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore_with_registry(self, discovery, import_module): """Test ignore config. The case when the device is in entity registry. """ self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {'mock_component.registry_id': { zwave.CONF_IGNORED: True }} with patch.object(self.registry, 'async_schedule_save'): self.registry.async_get_or_create( 'mock_component', zwave.DOMAIN, '567-1000', suggested_object_id='registry_id') zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_platform_ignore(self, discovery, import_module): """Test platform ignore device.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } platform = MagicMock() import_module.return_value = platform platform.get_device.return_value = None zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_config_polling_intensity(self, discovery, import_module): """Test polling intensity.""" mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_POLLING_INTENSITY: 123, }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert discovery.async_load_platform.called assert self.primary.enable_poll.called assert len(self.primary.enable_poll.mock_calls) == 1 assert self.primary.enable_poll.mock_calls[0][1][0] == 123 class TestZwave(unittest.TestCase): """Test zwave init.""" def test_device_config_glob_is_ordered(self): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): """Tests for zwave services.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() # Initialize zwave setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.zwave_network = self.hass.data[DATA_NETWORK] self.zwave_network.state = MockNetwork.STATE_READY self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.block_till_done() def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() self.hass.stop() def test_add_node(self): """Test zwave add_node service.""" self.hass.services.call('zwave', 'add_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller .add_node.mock_calls) == 1 assert len(self.zwave_network.controller .add_node.mock_calls[0][1]) == 0 def test_add_node_secure(self): """Test zwave add_node_secure service.""" self.hass.services.call('zwave', 'add_node_secure', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller.add_node.mock_calls) == 1 assert (self.zwave_network.controller .add_node.mock_calls[0][1][0] is True) def test_remove_node(self): """Test zwave remove_node service.""" self.hass.services.call('zwave', 'remove_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.remove_node.called assert len(self.zwave_network.controller.remove_node.mock_calls) == 1 def test_cancel_command(self): """Test zwave cancel_command service.""" self.hass.services.call('zwave', 'cancel_command', {}) self.hass.block_till_done() assert self.zwave_network.controller.cancel_command.called assert len(self.zwave_network.controller .cancel_command.mock_calls) == 1 def test_heal_network(self): """Test zwave heal_network service.""" self.hass.services.call('zwave', 'heal_network', {}) self.hass.block_till_done() assert self.zwave_network.heal.called assert len(self.zwave_network.heal.mock_calls) == 1 def test_soft_reset(self): """Test zwave soft_reset service.""" self.hass.services.call('zwave', 'soft_reset', {}) self.hass.block_till_done() assert self.zwave_network.controller.soft_reset.called assert len(self.zwave_network.controller.soft_reset.mock_calls) == 1 def test_test_network(self): """Test zwave test_network service.""" self.hass.services.call('zwave', 'test_network', {}) self.hass.block_till_done() assert self.zwave_network.test.called assert len(self.zwave_network.test.mock_calls) == 1 def test_stop_network(self): """Test zwave stop_network service.""" with patch.object(self.hass.bus, 'fire') as mock_fire: self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() assert self.zwave_network.stop.called assert len(self.zwave_network.stop.mock_calls) == 1 assert mock_fire.called assert len(mock_fire.mock_calls) == 1 assert mock_fire.mock_calls[0][1][0] == const.EVENT_NETWORK_STOP def test_rename_node(self): """Test zwave rename_node service.""" self.zwave_network.nodes = {11: MagicMock()} self.hass.services.call('zwave', 'rename_node', { const.ATTR_NODE_ID: 11, const.ATTR_NAME: 'test_name', }) self.hass.block_till_done() assert self.zwave_network.nodes[11].name == 'test_name' def test_rename_value(self): """Test zwave rename_value service.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, label="Old Label") node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.label == "Old Label" self.hass.services.call('zwave', 'rename_value', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_NAME: "New Label", }) self.hass.block_till_done() assert value.label == "New Label" def test_set_poll_intensity_enable(self): """Test zwave set_poll_intensity service, successful set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 2 assert enable_poll.mock_calls[0][1][0] == 4 def test_set_poll_intensity_enable_failed(self): """Test zwave set_poll_intensity service, failed set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) value.enable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 1 def test_set_poll_intensity_disable(self): """Test zwave set_poll_intensity service, successful disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 2 def test_set_poll_intensity_disable_failed(self): """Test zwave set_poll_intensity service, failed disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) value.disable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 1 def test_remove_failed_node(self): """Test zwave remove_failed_node service.""" self.hass.services.call('zwave', 'remove_failed_node', { const.ATTR_NODE_ID: 12, }) self.hass.block_till_done() remove_failed_node = self.zwave_network.controller.remove_failed_node assert remove_failed_node.called assert len(remove_failed_node.mock_calls) == 1 assert remove_failed_node.mock_calls[0][1][0] == 12 def test_replace_failed_node(self): """Test zwave replace_failed_node service.""" self.hass.services.call('zwave', 'replace_failed_node', { const.ATTR_NODE_ID: 13, }) self.hass.block_till_done() replace_failed_node = self.zwave_network.controller.replace_failed_node assert replace_failed_node.called assert len(replace_failed_node.mock_calls) == 1 assert replace_failed_node.mock_calls[0][1][0] == 13 def test_set_config_parameter(self): """Test zwave set_config_parameter service.""" value_byte = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BYTE, ) value_list = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['item1', 'item2', 'item3'], ) value_button = MockValue( index=14, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BUTTON, ) value_list_int = MockValue( index=15, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['1', '2', '3'], ) value_bool = MockValue( index=16, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BOOL, ) node = MockNode(node_id=14) node.get_values.return_value = { 12: value_byte, 13: value_list, 14: value_button, 15: value_list_int, 16: value_bool } self.zwave_network.nodes = {14: node} # Byte self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 12, const.ATTR_CONFIG_VALUE: 7, }) self.hass.block_till_done() assert value_byte.data == 7 # List self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, const.ATTR_CONFIG_VALUE: 'item3', }) self.hass.block_till_done() assert value_list.data == 'item3' # Button self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 14, const.ATTR_CONFIG_VALUE: True, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called assert self.zwave_network.manager.releaseButton.called # List of Ints self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 15, const.ATTR_CONFIG_VALUE: 3, }) self.hass.block_till_done() assert value_list_int.data == '3' # Boolean Truthy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'True', }) self.hass.block_till_done() assert value_bool.data == 1 # Boolean Falsy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'False', }) self.hass.block_till_done() assert value_bool.data == 0 # Different Parameter Size self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 19, const.ATTR_CONFIG_VALUE: 0x01020304, const.ATTR_CONFIG_SIZE: 4 }) self.hass.block_till_done() assert node.set_config_param.called assert len(node.set_config_param.mock_calls) == 1 assert node.set_config_param.mock_calls[0][1][0] == 19 assert node.set_config_param.mock_calls[0][1][1] == 0x01020304 assert node.set_config_param.mock_calls[0][1][2] == 4 node.set_config_param.reset_mock() def test_print_config_parameter(self): """Test zwave print_config_parameter service.""" value1 = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, data=1234, ) value2 = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, data=2345, ) node = MockNode(node_id=14) node.values = {12: value1, 13: value2} self.zwave_network.nodes = {14: node} with patch.object(zwave, '_LOGGER') as mock_logger: self.hass.services.call('zwave', 'print_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, }) self.hass.block_till_done() assert mock_logger.info.called assert len(mock_logger.info.mock_calls) == 1 assert mock_logger.info.mock_calls[0][1][1] == 13 assert mock_logger.info.mock_calls[0][1][2] == 14 assert mock_logger.info.mock_calls[0][1][3] == 2345 def test_print_node(self): """Test zwave print_node_parameter service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} with self.assertLogs(level='DEBUG') as mock_logger: self.hass.services.call('zwave', 'print_node', { const.ATTR_NODE_ID: 14 }) self.hass.block_till_done() assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 15, }) self.hass.block_till_done() assert value.data == 15 node.can_wake_up_value = False self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 20, }) self.hass.block_till_done() assert value.data == 15 def test_reset_node_meters(self): """Test zwave reset_node_meters service.""" value = MockValue( instance=1, index=8, data=99.5, command_class=const.COMMAND_CLASS_METER, ) reset_value = MockValue( instance=1, index=33, command_class=const.COMMAND_CLASS_METER, ) node = MockNode(node_id=14) node.values = {8: value, 33: reset_value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, const.ATTR_INSTANCE: 2, }) self.hass.block_till_done() assert not self.zwave_network.manager.pressButton.called assert not self.zwave_network.manager.releaseButton.called self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called value_id, = self.zwave_network.manager.pressButton.mock_calls.pop(0)[1] assert value_id == reset_value.value_id assert self.zwave_network.manager.releaseButton.called value_id, = ( self.zwave_network.manager.releaseButton.mock_calls.pop(0)[1]) assert value_id == reset_value.value_id def test_add_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'add', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.add_association.called assert len(group.add_association.mock_calls) == 1 assert group.add_association.mock_calls[0][1][0] == 24 assert group.add_association.mock_calls[0][1][1] == 5 def test_remove_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'remove', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.remove_association.called assert len(group.remove_association.mock_calls) == 1 assert group.remove_association.mock_calls[0][1][0] == 24 assert group.remove_association.mock_calls[0][1][1] == 5 def test_refresh_entity(self): """Test zwave refresh_entity service.""" node = MockNode() value = MockValue(data=False, node=node, command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50, node=node, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = get_device(node=node, values=values, node_config={}) device.hass = self.hass device.entity_id = 'binary_sensor.mock_entity_id' self.hass.add_job(device.async_added_to_hass()) self.hass.block_till_done() self.hass.services.call('zwave', 'refresh_entity', { ATTR_ENTITY_ID: 'binary_sensor.mock_entity_id', }) self.hass.block_till_done() assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 assert sorted([node.refresh_value.mock_calls[0][1][0], node.refresh_value.mock_calls[1][1][0]]) == \ sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert node.refresh_info.called assert len(node.refresh_info.mock_calls) == 1 def test_set_node_value(self): """Test zwave set_node_value service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=4 ) node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR]) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12, const.ATTR_CONFIG_VALUE: 2, }) self.hass.block_till_done() assert self.zwave_network.nodes[14].values[12].data == 2 def test_refresh_node_value(self): """Test zwave refresh_node_value service.""" node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR], network=self.zwave_network) value = MockValue( node=node, index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=2 ) value.refresh = MagicMock() node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12 }) self.hass.block_till_done() assert value.refresh.called def test_heal_node(self): """Test zwave heal_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'heal_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.heal.called assert len(node.heal.mock_calls) == 1 def test_test_node(self): """Test the zwave test_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'test_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.test.called assert len(node.test.mock_calls) == 1
jabesq/home-assistant
tests/components/zwave/test_init.py
homeassistant/components/homekit/type_security_systems.py
"""Support for WeMo binary sensors.""" import asyncio import logging import async_timeout import requests from homeassistant.components.binary_sensor import BinarySensorDevice from homeassistant.exceptions import PlatformNotReady from . import SUBSCRIPTION_REGISTRY _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Register discovered WeMo binary sensors.""" from pywemo import discovery if discovery_info is not None: location = discovery_info['ssdp_description'] mac = discovery_info['mac_address'] try: device = discovery.device_from_description(location, mac) except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as err: _LOGGER.error('Unable to access %s (%s)', location, err) raise PlatformNotReady if device: add_entities([WemoBinarySensor(hass, device)]) class WemoBinarySensor(BinarySensorDevice): """Representation a WeMo binary sensor.""" def __init__(self, hass, device): """Initialize the WeMo sensor.""" self.wemo = device self._state = None self._available = True self._update_lock = None self._model_name = self.wemo.model_name self._name = self.wemo.name self._serialnumber = self.wemo.serialnumber def _subscription_callback(self, _device, _type, _params): """Update the state by the Wemo sensor.""" _LOGGER.debug("Subscription update for %s", self.name) updated = self.wemo.subscription_update(_type, _params) self.hass.add_job( self._async_locked_subscription_callback(not updated)) async def _async_locked_subscription_callback(self, force_update): """Handle an update from a subscription.""" # If an update is in progress, we don't do anything if self._update_lock.locked(): return await self._async_locked_update(force_update) self.async_schedule_update_ha_state() async def async_added_to_hass(self): """Wemo sensor added to HASS.""" # Define inside async context so we know our event loop self._update_lock = asyncio.Lock() registry = SUBSCRIPTION_REGISTRY await self.hass.async_add_executor_job(registry.register, self.wemo) registry.on(self.wemo, None, self._subscription_callback) async def async_update(self): """Update WeMo state. Wemo has an aggressive retry logic that sometimes can take over a minute to return. If we don't get a state after 5 seconds, assume the Wemo sensor is unreachable. If update goes through, it will be made available again. """ # If an update is in progress, we don't do anything if self._update_lock.locked(): return try: with async_timeout.timeout(5): await asyncio.shield(self._async_locked_update(True)) except asyncio.TimeoutError: _LOGGER.warning('Lost connection to %s', self.name) self._available = False async def _async_locked_update(self, force_update): """Try updating within an async lock.""" async with self._update_lock: await self.hass.async_add_executor_job(self._update, force_update) def _update(self, force_update=True): """Update the sensor state.""" try: self._state = self.wemo.get_state(force_update) if not self._available: _LOGGER.info('Reconnected to %s', self.name) self._available = True except AttributeError as err: _LOGGER.warning("Could not update status for %s (%s)", self.name, err) self._available = False @property def unique_id(self): """Return the id of this WeMo sensor.""" return self._serialnumber @property def name(self): """Return the name of the service if any.""" return self._name @property def is_on(self): """Return true if sensor is on.""" return self._state @property def available(self): """Return true if sensor is available.""" return self._available
"""Tests for the Z-Wave init.""" import asyncio from collections import OrderedDict from datetime import datetime import unittest from unittest.mock import MagicMock, patch import pytest from pytz import utc import voluptuous as vol from homeassistant.bootstrap import async_setup_component from homeassistant.components import zwave from homeassistant.components.zwave import ( CONF_DEVICE_CONFIG_GLOB, CONFIG_SCHEMA, DATA_NETWORK, const) from homeassistant.components.zwave.binary_sensor import get_device from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.device_registry import ( async_get_registry as get_dev_reg) from homeassistant.setup import setup_component from tests.common import ( async_fire_time_changed, get_test_home_assistant, mock_coro, mock_registry) from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue async def test_valid_device_config(hass, mock_openzwave): """Test valid device config.""" device_config = { 'light.kitchen': { 'ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert result async def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = { 'light.kitchen': { 'some_ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert not result def test_config_access_error(): """Test threading error accessing config values.""" node = MagicMock() def side_effect(): raise RuntimeError node.values.values.side_effect = side_effect result = zwave.get_config_value(node, 1) assert result is None async def test_network_options(hass, mock_openzwave): """Test network options.""" result = await async_setup_component(hass, 'zwave', { 'zwave': { 'usb_path': 'mock_usb_path', 'config_path': 'mock_config_path', }}) await hass.async_block_till_done() assert result network = hass.data[zwave.DATA_NETWORK] assert network.options.device == 'mock_usb_path' assert network.options.config_path == 'mock_config_path' async def test_network_key_validation(hass, mock_openzwave): """Test network key validation.""" test_values = [ ('0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,' '0x0E,0x0F,0x10'), ] for value in test_values: result = zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) assert result['zwave']['network_key'] == value async def test_erronous_network_key_fails_validation(hass, mock_openzwave): """Test failing erronous network key validation.""" test_values = [ ('0x 01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0X01,0X02,0X03,0X04,0X05,0X06,0X07,0X08,0X09,0X0A,0X0B,0X0C,0X0D,' '0X0E,0X0F,0X10'), 'invalid', '1234567', 1234567 ] for value in test_values: with pytest.raises(vol.Invalid): zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) async def test_auto_heal_midnight(hass, mock_openzwave): """Test network auto-heal at midnight.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': True, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert network.heal.called assert len(network.heal.mock_calls) == 1 async def test_auto_heal_disabled(hass, mock_openzwave): """Test network auto-heal disabled.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': False, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert not network.heal.called async def test_setup_platform(hass, mock_openzwave): """Test invalid device config.""" mock_device = MagicMock() hass.data[DATA_NETWORK] = MagicMock() hass.data[zwave.DATA_DEVICES] = {456: mock_device} async_add_entities = MagicMock() result = await zwave.async_setup_platform( hass, None, async_add_entities, None) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 123}) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 456}) assert result assert async_add_entities.called assert len(async_add_entities.mock_calls) == 1 assert async_add_entities.mock_calls[0][1][0] == [mock_device] async def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): """Test device entity base class.""" node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.value_added() device.update_properties() await hass.async_block_till_done() assert not device.should_poll assert device.unique_id == "10-11" assert device.name == 'Mock Node Sensor' assert device.device_state_attributes[zwave.ATTR_POWER] == 50.123 async def test_node_removed(hass, mock_openzwave): """Test node removed in base class.""" # Create a mock node & node entity node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.entity_id = 'zwave.mock_node' device.value_added() device.update_properties() await hass.async_block_till_done() # Save it to the entity registry registry = mock_registry(hass) registry.async_get_or_create('zwave', 'zwave', device.unique_id) device.entity_id = registry.async_get_entity_id( 'zwave', 'zwave', device.unique_id) # Create dummy entity registry entries for other integrations hue_entity = registry.async_get_or_create('light', 'hue', 1234) zha_entity = registry.async_get_or_create('sensor', 'zha', 5678) # Verify our Z-Wave entity is registered assert registry.async_is_registered(device.entity_id) # Remove it entity_id = device.entity_id await device.node_removed() # Verify registry entry for our Z-Wave node is gone assert not registry.async_is_registered(entity_id) # Verify registry entries for our other entities remain assert registry.async_is_registered(hue_entity.entity_id) assert registry.async_is_registered(zha_entity.entity_id) async def test_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node').state == 'unknown' async def test_unparsed_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode( node_id=14, manufacturer_name=None, name=None, is_ready=False) sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert len(sleeps) == const.NODE_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1:] == \ (14, const.NODE_READY_WAIT_SECS) assert hass.states.get('zwave.unknown_node_14').state == 'unknown' async def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': { 'device_config': { 'zwave.mock_node': { 'ignored': True, }}}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None async def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' async def test_value_entities(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = {} def mock_connect(receiver, signal, *args, **kwargs): mock_receivers[signal] = receiver with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert mock_receivers hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_ALL_NODES_QUERIED]) node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) zwave_network.nodes = {node.node_id: node} value = MockValue( data=False, node=node, index=12, instance=1, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values = {'primary': value, value.value_id: value} value2 = MockValue( data=False, node=node, index=12, instance=2, label="Mock Value B", command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values[value2.value_id] = value2 hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_NODE_ADDED], node) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value2) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' assert hass.states.get( 'binary_sensor.mock_node_mock_value_b').state == 'off' ent_reg = await async_get_registry(hass) dev_reg = await get_dev_reg(hass) entry = ent_reg.async_get('zwave.mock_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) node_dev_id = entry.device_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) assert entry.name is None assert entry.device_id == node_dev_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value2.object_id) assert entry.name is None assert entry.device_id != node_dev_id device_id_b = entry.device_id device = dev_reg.async_get(node_dev_id) assert device is not None assert device.name == node.name old_device = device device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming without updating await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_NAME: "Demo Node", }) await hass.async_block_till_done() assert node.name == "Demo Node" entry = ent_reg.async_get('zwave.mock_node') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Node", }) await hass.async_block_till_done() assert node.name == "New Node" entry = ent_reg.async_get('zwave.new_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) entry = ent_reg.async_get('binary_sensor.new_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) await hass.services.async_call('zwave', 'rename_value', { const.ATTR_NODE_ID: node.node_id, const.ATTR_VALUE_ID: value.object_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Label", }) await hass.async_block_till_done() entry = ent_reg.async_get('binary_sensor.new_node_new_label') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) async def test_value_discovery_existing_entity(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_THERMOSTAT) setpoint = MockValue( data=22.0, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, setpoint) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] is None def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): temperature = MockValue( data=23.5, node=node, index=1, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, temperature) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] == 23.5 async def test_power_schemes(hass, mock_openzwave): """Test power attribute.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SWITCH_BINARY) switch = MockValue( data=True, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SWITCH_BINARY, genre=const.GENRE_USER, type=const.TYPE_BOOL) hass.async_add_job(mock_receivers[0], node, switch) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').state == 'on' assert 'power_consumption' not in hass.states.get( 'switch.mock_node_mock_value').attributes def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): power = MockValue( data=23.5, node=node, index=const.INDEX_SENSOR_MULTILEVEL_POWER, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL) hass.async_add_job(mock_receivers[0], node, power) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').attributes[ 'power_consumption'] == 23.5 async def test_network_ready(hass, mock_openzwave): """Test Node network ready event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete_some_dead(hass, mock_openzwave): """Test Node network complete some dead event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE_SOME_DEAD, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 class TestZWaveDeviceEntityValues(unittest.TestCase): """Tests for the ZWaveDeviceEntityValues helper.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() self.registry = mock_registry(self.hass) setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.node = MockNode() self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: ['mock_primary_class'], }, 'secondary': { const.DISC_COMMAND_CLASS: ['mock_secondary_class'], }, 'optional': { const.DISC_COMMAND_CLASS: ['mock_optional_class'], const.DISC_OPTIONAL: True, }}} self.primary = MockValue( command_class='mock_primary_class', node=self.node, value_id=1000) self.secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.duplicate_secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.optional = MockValue( command_class='mock_optional_class', node=self.node) self.no_match_value = MockValue( command_class='mock_bad_class', node=self.node) self.entity_id = 'mock_component.mock_node_mock_value' self.zwave_config = {'zwave': {}} self.device_config = {self.entity_id: {}} def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) assert values.primary is self.primary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) self.hass.block_till_done() assert values.secondary is self.secondary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config discovery.async_load_platform.reset_mock() values.check_value(self.optional) values.check_value(self.duplicate_secondary) values.check_value(self.no_match_value) self.hass.block_till_done() assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called assert len(values._entity.value_added.mock_calls) == 1 assert values._entity.value_changed.called assert len(values._entity.value_changed.mock_calls) == 1 @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, self.optional.value_id: self.optional, self.no_match_value.value_id: self.no_match_value, } values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert values.primary is self.primary assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config assert not self.primary.enable_poll.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_node_schema_mismatch(self, discovery, import_module): """Test node schema mismatch.""" self.node.generic = 'no_match' self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.mock_schema[const.DISC_GENERIC_DEVICE_CLASS] = ['generic_match'] values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.manufacturer_id = '010f' self.node.product_type = '0b00' self.primary.command_class = const.COMMAND_CLASS_SENSOR_ALARM self.entity_id = 'binary_sensor.mock_node_mock_value' self.device_config = {self.entity_id: {}} self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} with patch.object(zwave, 'async_dispatcher_send') as \ mock_dispatch_send: values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert mock_dispatch_send.called assert len(mock_dispatch_send.mock_calls) == 1 args = mock_dispatch_send.mock_calls[0][1] assert args[1] == 'zwave_new_binary_sensor' @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_ignore(self, discovery, import_module): """Test ignore workaround.""" self.node.manufacturer_id = '010f' self.node.product_type = '0301' self.primary.command_class = const.COMMAND_CLASS_SWITCH_BINARY self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore(self, discovery, import_module): """Test ignore config.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_IGNORED: True }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore_with_registry(self, discovery, import_module): """Test ignore config. The case when the device is in entity registry. """ self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {'mock_component.registry_id': { zwave.CONF_IGNORED: True }} with patch.object(self.registry, 'async_schedule_save'): self.registry.async_get_or_create( 'mock_component', zwave.DOMAIN, '567-1000', suggested_object_id='registry_id') zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_platform_ignore(self, discovery, import_module): """Test platform ignore device.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } platform = MagicMock() import_module.return_value = platform platform.get_device.return_value = None zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_config_polling_intensity(self, discovery, import_module): """Test polling intensity.""" mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_POLLING_INTENSITY: 123, }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert discovery.async_load_platform.called assert self.primary.enable_poll.called assert len(self.primary.enable_poll.mock_calls) == 1 assert self.primary.enable_poll.mock_calls[0][1][0] == 123 class TestZwave(unittest.TestCase): """Test zwave init.""" def test_device_config_glob_is_ordered(self): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): """Tests for zwave services.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() # Initialize zwave setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.zwave_network = self.hass.data[DATA_NETWORK] self.zwave_network.state = MockNetwork.STATE_READY self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.block_till_done() def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() self.hass.stop() def test_add_node(self): """Test zwave add_node service.""" self.hass.services.call('zwave', 'add_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller .add_node.mock_calls) == 1 assert len(self.zwave_network.controller .add_node.mock_calls[0][1]) == 0 def test_add_node_secure(self): """Test zwave add_node_secure service.""" self.hass.services.call('zwave', 'add_node_secure', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller.add_node.mock_calls) == 1 assert (self.zwave_network.controller .add_node.mock_calls[0][1][0] is True) def test_remove_node(self): """Test zwave remove_node service.""" self.hass.services.call('zwave', 'remove_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.remove_node.called assert len(self.zwave_network.controller.remove_node.mock_calls) == 1 def test_cancel_command(self): """Test zwave cancel_command service.""" self.hass.services.call('zwave', 'cancel_command', {}) self.hass.block_till_done() assert self.zwave_network.controller.cancel_command.called assert len(self.zwave_network.controller .cancel_command.mock_calls) == 1 def test_heal_network(self): """Test zwave heal_network service.""" self.hass.services.call('zwave', 'heal_network', {}) self.hass.block_till_done() assert self.zwave_network.heal.called assert len(self.zwave_network.heal.mock_calls) == 1 def test_soft_reset(self): """Test zwave soft_reset service.""" self.hass.services.call('zwave', 'soft_reset', {}) self.hass.block_till_done() assert self.zwave_network.controller.soft_reset.called assert len(self.zwave_network.controller.soft_reset.mock_calls) == 1 def test_test_network(self): """Test zwave test_network service.""" self.hass.services.call('zwave', 'test_network', {}) self.hass.block_till_done() assert self.zwave_network.test.called assert len(self.zwave_network.test.mock_calls) == 1 def test_stop_network(self): """Test zwave stop_network service.""" with patch.object(self.hass.bus, 'fire') as mock_fire: self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() assert self.zwave_network.stop.called assert len(self.zwave_network.stop.mock_calls) == 1 assert mock_fire.called assert len(mock_fire.mock_calls) == 1 assert mock_fire.mock_calls[0][1][0] == const.EVENT_NETWORK_STOP def test_rename_node(self): """Test zwave rename_node service.""" self.zwave_network.nodes = {11: MagicMock()} self.hass.services.call('zwave', 'rename_node', { const.ATTR_NODE_ID: 11, const.ATTR_NAME: 'test_name', }) self.hass.block_till_done() assert self.zwave_network.nodes[11].name == 'test_name' def test_rename_value(self): """Test zwave rename_value service.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, label="Old Label") node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.label == "Old Label" self.hass.services.call('zwave', 'rename_value', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_NAME: "New Label", }) self.hass.block_till_done() assert value.label == "New Label" def test_set_poll_intensity_enable(self): """Test zwave set_poll_intensity service, successful set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 2 assert enable_poll.mock_calls[0][1][0] == 4 def test_set_poll_intensity_enable_failed(self): """Test zwave set_poll_intensity service, failed set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) value.enable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 1 def test_set_poll_intensity_disable(self): """Test zwave set_poll_intensity service, successful disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 2 def test_set_poll_intensity_disable_failed(self): """Test zwave set_poll_intensity service, failed disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) value.disable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 1 def test_remove_failed_node(self): """Test zwave remove_failed_node service.""" self.hass.services.call('zwave', 'remove_failed_node', { const.ATTR_NODE_ID: 12, }) self.hass.block_till_done() remove_failed_node = self.zwave_network.controller.remove_failed_node assert remove_failed_node.called assert len(remove_failed_node.mock_calls) == 1 assert remove_failed_node.mock_calls[0][1][0] == 12 def test_replace_failed_node(self): """Test zwave replace_failed_node service.""" self.hass.services.call('zwave', 'replace_failed_node', { const.ATTR_NODE_ID: 13, }) self.hass.block_till_done() replace_failed_node = self.zwave_network.controller.replace_failed_node assert replace_failed_node.called assert len(replace_failed_node.mock_calls) == 1 assert replace_failed_node.mock_calls[0][1][0] == 13 def test_set_config_parameter(self): """Test zwave set_config_parameter service.""" value_byte = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BYTE, ) value_list = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['item1', 'item2', 'item3'], ) value_button = MockValue( index=14, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BUTTON, ) value_list_int = MockValue( index=15, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['1', '2', '3'], ) value_bool = MockValue( index=16, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BOOL, ) node = MockNode(node_id=14) node.get_values.return_value = { 12: value_byte, 13: value_list, 14: value_button, 15: value_list_int, 16: value_bool } self.zwave_network.nodes = {14: node} # Byte self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 12, const.ATTR_CONFIG_VALUE: 7, }) self.hass.block_till_done() assert value_byte.data == 7 # List self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, const.ATTR_CONFIG_VALUE: 'item3', }) self.hass.block_till_done() assert value_list.data == 'item3' # Button self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 14, const.ATTR_CONFIG_VALUE: True, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called assert self.zwave_network.manager.releaseButton.called # List of Ints self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 15, const.ATTR_CONFIG_VALUE: 3, }) self.hass.block_till_done() assert value_list_int.data == '3' # Boolean Truthy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'True', }) self.hass.block_till_done() assert value_bool.data == 1 # Boolean Falsy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'False', }) self.hass.block_till_done() assert value_bool.data == 0 # Different Parameter Size self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 19, const.ATTR_CONFIG_VALUE: 0x01020304, const.ATTR_CONFIG_SIZE: 4 }) self.hass.block_till_done() assert node.set_config_param.called assert len(node.set_config_param.mock_calls) == 1 assert node.set_config_param.mock_calls[0][1][0] == 19 assert node.set_config_param.mock_calls[0][1][1] == 0x01020304 assert node.set_config_param.mock_calls[0][1][2] == 4 node.set_config_param.reset_mock() def test_print_config_parameter(self): """Test zwave print_config_parameter service.""" value1 = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, data=1234, ) value2 = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, data=2345, ) node = MockNode(node_id=14) node.values = {12: value1, 13: value2} self.zwave_network.nodes = {14: node} with patch.object(zwave, '_LOGGER') as mock_logger: self.hass.services.call('zwave', 'print_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, }) self.hass.block_till_done() assert mock_logger.info.called assert len(mock_logger.info.mock_calls) == 1 assert mock_logger.info.mock_calls[0][1][1] == 13 assert mock_logger.info.mock_calls[0][1][2] == 14 assert mock_logger.info.mock_calls[0][1][3] == 2345 def test_print_node(self): """Test zwave print_node_parameter service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} with self.assertLogs(level='DEBUG') as mock_logger: self.hass.services.call('zwave', 'print_node', { const.ATTR_NODE_ID: 14 }) self.hass.block_till_done() assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 15, }) self.hass.block_till_done() assert value.data == 15 node.can_wake_up_value = False self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 20, }) self.hass.block_till_done() assert value.data == 15 def test_reset_node_meters(self): """Test zwave reset_node_meters service.""" value = MockValue( instance=1, index=8, data=99.5, command_class=const.COMMAND_CLASS_METER, ) reset_value = MockValue( instance=1, index=33, command_class=const.COMMAND_CLASS_METER, ) node = MockNode(node_id=14) node.values = {8: value, 33: reset_value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, const.ATTR_INSTANCE: 2, }) self.hass.block_till_done() assert not self.zwave_network.manager.pressButton.called assert not self.zwave_network.manager.releaseButton.called self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called value_id, = self.zwave_network.manager.pressButton.mock_calls.pop(0)[1] assert value_id == reset_value.value_id assert self.zwave_network.manager.releaseButton.called value_id, = ( self.zwave_network.manager.releaseButton.mock_calls.pop(0)[1]) assert value_id == reset_value.value_id def test_add_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'add', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.add_association.called assert len(group.add_association.mock_calls) == 1 assert group.add_association.mock_calls[0][1][0] == 24 assert group.add_association.mock_calls[0][1][1] == 5 def test_remove_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'remove', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.remove_association.called assert len(group.remove_association.mock_calls) == 1 assert group.remove_association.mock_calls[0][1][0] == 24 assert group.remove_association.mock_calls[0][1][1] == 5 def test_refresh_entity(self): """Test zwave refresh_entity service.""" node = MockNode() value = MockValue(data=False, node=node, command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50, node=node, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = get_device(node=node, values=values, node_config={}) device.hass = self.hass device.entity_id = 'binary_sensor.mock_entity_id' self.hass.add_job(device.async_added_to_hass()) self.hass.block_till_done() self.hass.services.call('zwave', 'refresh_entity', { ATTR_ENTITY_ID: 'binary_sensor.mock_entity_id', }) self.hass.block_till_done() assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 assert sorted([node.refresh_value.mock_calls[0][1][0], node.refresh_value.mock_calls[1][1][0]]) == \ sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert node.refresh_info.called assert len(node.refresh_info.mock_calls) == 1 def test_set_node_value(self): """Test zwave set_node_value service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=4 ) node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR]) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12, const.ATTR_CONFIG_VALUE: 2, }) self.hass.block_till_done() assert self.zwave_network.nodes[14].values[12].data == 2 def test_refresh_node_value(self): """Test zwave refresh_node_value service.""" node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR], network=self.zwave_network) value = MockValue( node=node, index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=2 ) value.refresh = MagicMock() node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12 }) self.hass.block_till_done() assert value.refresh.called def test_heal_node(self): """Test zwave heal_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'heal_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.heal.called assert len(node.heal.mock_calls) == 1 def test_test_node(self): """Test the zwave test_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'test_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.test.called assert len(node.test.mock_calls) == 1
jabesq/home-assistant
tests/components/zwave/test_init.py
homeassistant/components/wemo/binary_sensor.py
"""Support for Fast.com internet speed testing sensor.""" import logging from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.restore_state import RestoreEntity from . import DATA_UPDATED, DOMAIN as FASTDOTCOM_DOMAIN _LOGGER = logging.getLogger(__name__) ICON = 'mdi:speedometer' UNIT_OF_MEASUREMENT = 'Mbit/s' async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Fast.com sensor.""" async_add_entities([SpeedtestSensor(hass.data[FASTDOTCOM_DOMAIN])]) class SpeedtestSensor(RestoreEntity): """Implementation of a FAst.com sensor.""" def __init__(self, speedtest_data): """Initialize the sensor.""" self._name = 'Fast.com Download' self.speedtest_client = speedtest_data self._state = None @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the device.""" return self._state @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return UNIT_OF_MEASUREMENT @property def icon(self): """Return icon.""" return ICON @property def should_poll(self): """Return the polling requirement for this sensor.""" return False async def async_added_to_hass(self): """Handle entity which will be added.""" await super().async_added_to_hass() state = await self.async_get_last_state() if not state: return self._state = state.state async_dispatcher_connect( self.hass, DATA_UPDATED, self._schedule_immediate_update ) def update(self): """Get the latest data and update the states.""" data = self.speedtest_client.data if data is None: return self._state = data['download'] @callback def _schedule_immediate_update(self): self.async_schedule_update_ha_state(True)
"""Tests for the Z-Wave init.""" import asyncio from collections import OrderedDict from datetime import datetime import unittest from unittest.mock import MagicMock, patch import pytest from pytz import utc import voluptuous as vol from homeassistant.bootstrap import async_setup_component from homeassistant.components import zwave from homeassistant.components.zwave import ( CONF_DEVICE_CONFIG_GLOB, CONFIG_SCHEMA, DATA_NETWORK, const) from homeassistant.components.zwave.binary_sensor import get_device from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.device_registry import ( async_get_registry as get_dev_reg) from homeassistant.setup import setup_component from tests.common import ( async_fire_time_changed, get_test_home_assistant, mock_coro, mock_registry) from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue async def test_valid_device_config(hass, mock_openzwave): """Test valid device config.""" device_config = { 'light.kitchen': { 'ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert result async def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = { 'light.kitchen': { 'some_ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert not result def test_config_access_error(): """Test threading error accessing config values.""" node = MagicMock() def side_effect(): raise RuntimeError node.values.values.side_effect = side_effect result = zwave.get_config_value(node, 1) assert result is None async def test_network_options(hass, mock_openzwave): """Test network options.""" result = await async_setup_component(hass, 'zwave', { 'zwave': { 'usb_path': 'mock_usb_path', 'config_path': 'mock_config_path', }}) await hass.async_block_till_done() assert result network = hass.data[zwave.DATA_NETWORK] assert network.options.device == 'mock_usb_path' assert network.options.config_path == 'mock_config_path' async def test_network_key_validation(hass, mock_openzwave): """Test network key validation.""" test_values = [ ('0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,' '0x0E,0x0F,0x10'), ] for value in test_values: result = zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) assert result['zwave']['network_key'] == value async def test_erronous_network_key_fails_validation(hass, mock_openzwave): """Test failing erronous network key validation.""" test_values = [ ('0x 01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0X01,0X02,0X03,0X04,0X05,0X06,0X07,0X08,0X09,0X0A,0X0B,0X0C,0X0D,' '0X0E,0X0F,0X10'), 'invalid', '1234567', 1234567 ] for value in test_values: with pytest.raises(vol.Invalid): zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) async def test_auto_heal_midnight(hass, mock_openzwave): """Test network auto-heal at midnight.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': True, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert network.heal.called assert len(network.heal.mock_calls) == 1 async def test_auto_heal_disabled(hass, mock_openzwave): """Test network auto-heal disabled.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': False, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert not network.heal.called async def test_setup_platform(hass, mock_openzwave): """Test invalid device config.""" mock_device = MagicMock() hass.data[DATA_NETWORK] = MagicMock() hass.data[zwave.DATA_DEVICES] = {456: mock_device} async_add_entities = MagicMock() result = await zwave.async_setup_platform( hass, None, async_add_entities, None) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 123}) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 456}) assert result assert async_add_entities.called assert len(async_add_entities.mock_calls) == 1 assert async_add_entities.mock_calls[0][1][0] == [mock_device] async def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): """Test device entity base class.""" node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.value_added() device.update_properties() await hass.async_block_till_done() assert not device.should_poll assert device.unique_id == "10-11" assert device.name == 'Mock Node Sensor' assert device.device_state_attributes[zwave.ATTR_POWER] == 50.123 async def test_node_removed(hass, mock_openzwave): """Test node removed in base class.""" # Create a mock node & node entity node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.entity_id = 'zwave.mock_node' device.value_added() device.update_properties() await hass.async_block_till_done() # Save it to the entity registry registry = mock_registry(hass) registry.async_get_or_create('zwave', 'zwave', device.unique_id) device.entity_id = registry.async_get_entity_id( 'zwave', 'zwave', device.unique_id) # Create dummy entity registry entries for other integrations hue_entity = registry.async_get_or_create('light', 'hue', 1234) zha_entity = registry.async_get_or_create('sensor', 'zha', 5678) # Verify our Z-Wave entity is registered assert registry.async_is_registered(device.entity_id) # Remove it entity_id = device.entity_id await device.node_removed() # Verify registry entry for our Z-Wave node is gone assert not registry.async_is_registered(entity_id) # Verify registry entries for our other entities remain assert registry.async_is_registered(hue_entity.entity_id) assert registry.async_is_registered(zha_entity.entity_id) async def test_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node').state == 'unknown' async def test_unparsed_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode( node_id=14, manufacturer_name=None, name=None, is_ready=False) sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert len(sleeps) == const.NODE_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1:] == \ (14, const.NODE_READY_WAIT_SECS) assert hass.states.get('zwave.unknown_node_14').state == 'unknown' async def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': { 'device_config': { 'zwave.mock_node': { 'ignored': True, }}}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None async def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' async def test_value_entities(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = {} def mock_connect(receiver, signal, *args, **kwargs): mock_receivers[signal] = receiver with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert mock_receivers hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_ALL_NODES_QUERIED]) node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) zwave_network.nodes = {node.node_id: node} value = MockValue( data=False, node=node, index=12, instance=1, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values = {'primary': value, value.value_id: value} value2 = MockValue( data=False, node=node, index=12, instance=2, label="Mock Value B", command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values[value2.value_id] = value2 hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_NODE_ADDED], node) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value2) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' assert hass.states.get( 'binary_sensor.mock_node_mock_value_b').state == 'off' ent_reg = await async_get_registry(hass) dev_reg = await get_dev_reg(hass) entry = ent_reg.async_get('zwave.mock_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) node_dev_id = entry.device_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) assert entry.name is None assert entry.device_id == node_dev_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value2.object_id) assert entry.name is None assert entry.device_id != node_dev_id device_id_b = entry.device_id device = dev_reg.async_get(node_dev_id) assert device is not None assert device.name == node.name old_device = device device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming without updating await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_NAME: "Demo Node", }) await hass.async_block_till_done() assert node.name == "Demo Node" entry = ent_reg.async_get('zwave.mock_node') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Node", }) await hass.async_block_till_done() assert node.name == "New Node" entry = ent_reg.async_get('zwave.new_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) entry = ent_reg.async_get('binary_sensor.new_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) await hass.services.async_call('zwave', 'rename_value', { const.ATTR_NODE_ID: node.node_id, const.ATTR_VALUE_ID: value.object_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Label", }) await hass.async_block_till_done() entry = ent_reg.async_get('binary_sensor.new_node_new_label') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) async def test_value_discovery_existing_entity(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_THERMOSTAT) setpoint = MockValue( data=22.0, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, setpoint) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] is None def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): temperature = MockValue( data=23.5, node=node, index=1, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, temperature) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] == 23.5 async def test_power_schemes(hass, mock_openzwave): """Test power attribute.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SWITCH_BINARY) switch = MockValue( data=True, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SWITCH_BINARY, genre=const.GENRE_USER, type=const.TYPE_BOOL) hass.async_add_job(mock_receivers[0], node, switch) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').state == 'on' assert 'power_consumption' not in hass.states.get( 'switch.mock_node_mock_value').attributes def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): power = MockValue( data=23.5, node=node, index=const.INDEX_SENSOR_MULTILEVEL_POWER, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL) hass.async_add_job(mock_receivers[0], node, power) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').attributes[ 'power_consumption'] == 23.5 async def test_network_ready(hass, mock_openzwave): """Test Node network ready event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete_some_dead(hass, mock_openzwave): """Test Node network complete some dead event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE_SOME_DEAD, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 class TestZWaveDeviceEntityValues(unittest.TestCase): """Tests for the ZWaveDeviceEntityValues helper.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() self.registry = mock_registry(self.hass) setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.node = MockNode() self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: ['mock_primary_class'], }, 'secondary': { const.DISC_COMMAND_CLASS: ['mock_secondary_class'], }, 'optional': { const.DISC_COMMAND_CLASS: ['mock_optional_class'], const.DISC_OPTIONAL: True, }}} self.primary = MockValue( command_class='mock_primary_class', node=self.node, value_id=1000) self.secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.duplicate_secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.optional = MockValue( command_class='mock_optional_class', node=self.node) self.no_match_value = MockValue( command_class='mock_bad_class', node=self.node) self.entity_id = 'mock_component.mock_node_mock_value' self.zwave_config = {'zwave': {}} self.device_config = {self.entity_id: {}} def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) assert values.primary is self.primary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) self.hass.block_till_done() assert values.secondary is self.secondary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config discovery.async_load_platform.reset_mock() values.check_value(self.optional) values.check_value(self.duplicate_secondary) values.check_value(self.no_match_value) self.hass.block_till_done() assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called assert len(values._entity.value_added.mock_calls) == 1 assert values._entity.value_changed.called assert len(values._entity.value_changed.mock_calls) == 1 @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, self.optional.value_id: self.optional, self.no_match_value.value_id: self.no_match_value, } values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert values.primary is self.primary assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config assert not self.primary.enable_poll.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_node_schema_mismatch(self, discovery, import_module): """Test node schema mismatch.""" self.node.generic = 'no_match' self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.mock_schema[const.DISC_GENERIC_DEVICE_CLASS] = ['generic_match'] values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.manufacturer_id = '010f' self.node.product_type = '0b00' self.primary.command_class = const.COMMAND_CLASS_SENSOR_ALARM self.entity_id = 'binary_sensor.mock_node_mock_value' self.device_config = {self.entity_id: {}} self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} with patch.object(zwave, 'async_dispatcher_send') as \ mock_dispatch_send: values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert mock_dispatch_send.called assert len(mock_dispatch_send.mock_calls) == 1 args = mock_dispatch_send.mock_calls[0][1] assert args[1] == 'zwave_new_binary_sensor' @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_ignore(self, discovery, import_module): """Test ignore workaround.""" self.node.manufacturer_id = '010f' self.node.product_type = '0301' self.primary.command_class = const.COMMAND_CLASS_SWITCH_BINARY self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore(self, discovery, import_module): """Test ignore config.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_IGNORED: True }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore_with_registry(self, discovery, import_module): """Test ignore config. The case when the device is in entity registry. """ self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {'mock_component.registry_id': { zwave.CONF_IGNORED: True }} with patch.object(self.registry, 'async_schedule_save'): self.registry.async_get_or_create( 'mock_component', zwave.DOMAIN, '567-1000', suggested_object_id='registry_id') zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_platform_ignore(self, discovery, import_module): """Test platform ignore device.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } platform = MagicMock() import_module.return_value = platform platform.get_device.return_value = None zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_config_polling_intensity(self, discovery, import_module): """Test polling intensity.""" mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_POLLING_INTENSITY: 123, }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert discovery.async_load_platform.called assert self.primary.enable_poll.called assert len(self.primary.enable_poll.mock_calls) == 1 assert self.primary.enable_poll.mock_calls[0][1][0] == 123 class TestZwave(unittest.TestCase): """Test zwave init.""" def test_device_config_glob_is_ordered(self): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): """Tests for zwave services.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() # Initialize zwave setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.zwave_network = self.hass.data[DATA_NETWORK] self.zwave_network.state = MockNetwork.STATE_READY self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.block_till_done() def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() self.hass.stop() def test_add_node(self): """Test zwave add_node service.""" self.hass.services.call('zwave', 'add_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller .add_node.mock_calls) == 1 assert len(self.zwave_network.controller .add_node.mock_calls[0][1]) == 0 def test_add_node_secure(self): """Test zwave add_node_secure service.""" self.hass.services.call('zwave', 'add_node_secure', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller.add_node.mock_calls) == 1 assert (self.zwave_network.controller .add_node.mock_calls[0][1][0] is True) def test_remove_node(self): """Test zwave remove_node service.""" self.hass.services.call('zwave', 'remove_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.remove_node.called assert len(self.zwave_network.controller.remove_node.mock_calls) == 1 def test_cancel_command(self): """Test zwave cancel_command service.""" self.hass.services.call('zwave', 'cancel_command', {}) self.hass.block_till_done() assert self.zwave_network.controller.cancel_command.called assert len(self.zwave_network.controller .cancel_command.mock_calls) == 1 def test_heal_network(self): """Test zwave heal_network service.""" self.hass.services.call('zwave', 'heal_network', {}) self.hass.block_till_done() assert self.zwave_network.heal.called assert len(self.zwave_network.heal.mock_calls) == 1 def test_soft_reset(self): """Test zwave soft_reset service.""" self.hass.services.call('zwave', 'soft_reset', {}) self.hass.block_till_done() assert self.zwave_network.controller.soft_reset.called assert len(self.zwave_network.controller.soft_reset.mock_calls) == 1 def test_test_network(self): """Test zwave test_network service.""" self.hass.services.call('zwave', 'test_network', {}) self.hass.block_till_done() assert self.zwave_network.test.called assert len(self.zwave_network.test.mock_calls) == 1 def test_stop_network(self): """Test zwave stop_network service.""" with patch.object(self.hass.bus, 'fire') as mock_fire: self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() assert self.zwave_network.stop.called assert len(self.zwave_network.stop.mock_calls) == 1 assert mock_fire.called assert len(mock_fire.mock_calls) == 1 assert mock_fire.mock_calls[0][1][0] == const.EVENT_NETWORK_STOP def test_rename_node(self): """Test zwave rename_node service.""" self.zwave_network.nodes = {11: MagicMock()} self.hass.services.call('zwave', 'rename_node', { const.ATTR_NODE_ID: 11, const.ATTR_NAME: 'test_name', }) self.hass.block_till_done() assert self.zwave_network.nodes[11].name == 'test_name' def test_rename_value(self): """Test zwave rename_value service.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, label="Old Label") node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.label == "Old Label" self.hass.services.call('zwave', 'rename_value', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_NAME: "New Label", }) self.hass.block_till_done() assert value.label == "New Label" def test_set_poll_intensity_enable(self): """Test zwave set_poll_intensity service, successful set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 2 assert enable_poll.mock_calls[0][1][0] == 4 def test_set_poll_intensity_enable_failed(self): """Test zwave set_poll_intensity service, failed set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) value.enable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 1 def test_set_poll_intensity_disable(self): """Test zwave set_poll_intensity service, successful disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 2 def test_set_poll_intensity_disable_failed(self): """Test zwave set_poll_intensity service, failed disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) value.disable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 1 def test_remove_failed_node(self): """Test zwave remove_failed_node service.""" self.hass.services.call('zwave', 'remove_failed_node', { const.ATTR_NODE_ID: 12, }) self.hass.block_till_done() remove_failed_node = self.zwave_network.controller.remove_failed_node assert remove_failed_node.called assert len(remove_failed_node.mock_calls) == 1 assert remove_failed_node.mock_calls[0][1][0] == 12 def test_replace_failed_node(self): """Test zwave replace_failed_node service.""" self.hass.services.call('zwave', 'replace_failed_node', { const.ATTR_NODE_ID: 13, }) self.hass.block_till_done() replace_failed_node = self.zwave_network.controller.replace_failed_node assert replace_failed_node.called assert len(replace_failed_node.mock_calls) == 1 assert replace_failed_node.mock_calls[0][1][0] == 13 def test_set_config_parameter(self): """Test zwave set_config_parameter service.""" value_byte = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BYTE, ) value_list = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['item1', 'item2', 'item3'], ) value_button = MockValue( index=14, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BUTTON, ) value_list_int = MockValue( index=15, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['1', '2', '3'], ) value_bool = MockValue( index=16, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BOOL, ) node = MockNode(node_id=14) node.get_values.return_value = { 12: value_byte, 13: value_list, 14: value_button, 15: value_list_int, 16: value_bool } self.zwave_network.nodes = {14: node} # Byte self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 12, const.ATTR_CONFIG_VALUE: 7, }) self.hass.block_till_done() assert value_byte.data == 7 # List self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, const.ATTR_CONFIG_VALUE: 'item3', }) self.hass.block_till_done() assert value_list.data == 'item3' # Button self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 14, const.ATTR_CONFIG_VALUE: True, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called assert self.zwave_network.manager.releaseButton.called # List of Ints self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 15, const.ATTR_CONFIG_VALUE: 3, }) self.hass.block_till_done() assert value_list_int.data == '3' # Boolean Truthy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'True', }) self.hass.block_till_done() assert value_bool.data == 1 # Boolean Falsy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'False', }) self.hass.block_till_done() assert value_bool.data == 0 # Different Parameter Size self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 19, const.ATTR_CONFIG_VALUE: 0x01020304, const.ATTR_CONFIG_SIZE: 4 }) self.hass.block_till_done() assert node.set_config_param.called assert len(node.set_config_param.mock_calls) == 1 assert node.set_config_param.mock_calls[0][1][0] == 19 assert node.set_config_param.mock_calls[0][1][1] == 0x01020304 assert node.set_config_param.mock_calls[0][1][2] == 4 node.set_config_param.reset_mock() def test_print_config_parameter(self): """Test zwave print_config_parameter service.""" value1 = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, data=1234, ) value2 = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, data=2345, ) node = MockNode(node_id=14) node.values = {12: value1, 13: value2} self.zwave_network.nodes = {14: node} with patch.object(zwave, '_LOGGER') as mock_logger: self.hass.services.call('zwave', 'print_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, }) self.hass.block_till_done() assert mock_logger.info.called assert len(mock_logger.info.mock_calls) == 1 assert mock_logger.info.mock_calls[0][1][1] == 13 assert mock_logger.info.mock_calls[0][1][2] == 14 assert mock_logger.info.mock_calls[0][1][3] == 2345 def test_print_node(self): """Test zwave print_node_parameter service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} with self.assertLogs(level='DEBUG') as mock_logger: self.hass.services.call('zwave', 'print_node', { const.ATTR_NODE_ID: 14 }) self.hass.block_till_done() assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 15, }) self.hass.block_till_done() assert value.data == 15 node.can_wake_up_value = False self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 20, }) self.hass.block_till_done() assert value.data == 15 def test_reset_node_meters(self): """Test zwave reset_node_meters service.""" value = MockValue( instance=1, index=8, data=99.5, command_class=const.COMMAND_CLASS_METER, ) reset_value = MockValue( instance=1, index=33, command_class=const.COMMAND_CLASS_METER, ) node = MockNode(node_id=14) node.values = {8: value, 33: reset_value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, const.ATTR_INSTANCE: 2, }) self.hass.block_till_done() assert not self.zwave_network.manager.pressButton.called assert not self.zwave_network.manager.releaseButton.called self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called value_id, = self.zwave_network.manager.pressButton.mock_calls.pop(0)[1] assert value_id == reset_value.value_id assert self.zwave_network.manager.releaseButton.called value_id, = ( self.zwave_network.manager.releaseButton.mock_calls.pop(0)[1]) assert value_id == reset_value.value_id def test_add_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'add', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.add_association.called assert len(group.add_association.mock_calls) == 1 assert group.add_association.mock_calls[0][1][0] == 24 assert group.add_association.mock_calls[0][1][1] == 5 def test_remove_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'remove', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.remove_association.called assert len(group.remove_association.mock_calls) == 1 assert group.remove_association.mock_calls[0][1][0] == 24 assert group.remove_association.mock_calls[0][1][1] == 5 def test_refresh_entity(self): """Test zwave refresh_entity service.""" node = MockNode() value = MockValue(data=False, node=node, command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50, node=node, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = get_device(node=node, values=values, node_config={}) device.hass = self.hass device.entity_id = 'binary_sensor.mock_entity_id' self.hass.add_job(device.async_added_to_hass()) self.hass.block_till_done() self.hass.services.call('zwave', 'refresh_entity', { ATTR_ENTITY_ID: 'binary_sensor.mock_entity_id', }) self.hass.block_till_done() assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 assert sorted([node.refresh_value.mock_calls[0][1][0], node.refresh_value.mock_calls[1][1][0]]) == \ sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert node.refresh_info.called assert len(node.refresh_info.mock_calls) == 1 def test_set_node_value(self): """Test zwave set_node_value service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=4 ) node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR]) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12, const.ATTR_CONFIG_VALUE: 2, }) self.hass.block_till_done() assert self.zwave_network.nodes[14].values[12].data == 2 def test_refresh_node_value(self): """Test zwave refresh_node_value service.""" node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR], network=self.zwave_network) value = MockValue( node=node, index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=2 ) value.refresh = MagicMock() node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12 }) self.hass.block_till_done() assert value.refresh.called def test_heal_node(self): """Test zwave heal_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'heal_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.heal.called assert len(node.heal.mock_calls) == 1 def test_test_node(self): """Test the zwave test_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'test_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.test.called assert len(node.test.mock_calls) == 1
jabesq/home-assistant
tests/components/zwave/test_init.py
homeassistant/components/fastdotcom/sensor.py
"""Support for OpenUV sensors.""" import logging from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.util.dt import as_local, parse_datetime from . import ( DATA_OPENUV_CLIENT, DATA_UV, DOMAIN, SENSORS, TOPIC_UPDATE, TYPE_CURRENT_OZONE_LEVEL, TYPE_CURRENT_UV_INDEX, TYPE_CURRENT_UV_LEVEL, TYPE_MAX_UV_INDEX, TYPE_SAFE_EXPOSURE_TIME_1, TYPE_SAFE_EXPOSURE_TIME_2, TYPE_SAFE_EXPOSURE_TIME_3, TYPE_SAFE_EXPOSURE_TIME_4, TYPE_SAFE_EXPOSURE_TIME_5, TYPE_SAFE_EXPOSURE_TIME_6, OpenUvEntity) _LOGGER = logging.getLogger(__name__) ATTR_MAX_UV_TIME = 'time' EXPOSURE_TYPE_MAP = { TYPE_SAFE_EXPOSURE_TIME_1: 'st1', TYPE_SAFE_EXPOSURE_TIME_2: 'st2', TYPE_SAFE_EXPOSURE_TIME_3: 'st3', TYPE_SAFE_EXPOSURE_TIME_4: 'st4', TYPE_SAFE_EXPOSURE_TIME_5: 'st5', TYPE_SAFE_EXPOSURE_TIME_6: 'st6' } UV_LEVEL_EXTREME = 'Extreme' UV_LEVEL_VHIGH = 'Very High' UV_LEVEL_HIGH = 'High' UV_LEVEL_MODERATE = 'Moderate' UV_LEVEL_LOW = 'Low' async def async_setup_platform( hass, config, async_add_entities, discovery_info=None): """Set up an OpenUV sensor based on existing config.""" pass async def async_setup_entry(hass, entry, async_add_entities): """Set up a Nest sensor based on a config entry.""" openuv = hass.data[DOMAIN][DATA_OPENUV_CLIENT][entry.entry_id] sensors = [] for sensor_type in openuv.sensor_conditions: name, icon, unit = SENSORS[sensor_type] sensors.append( OpenUvSensor( openuv, sensor_type, name, icon, unit, entry.entry_id)) async_add_entities(sensors, True) class OpenUvSensor(OpenUvEntity): """Define a binary sensor for OpenUV.""" def __init__(self, openuv, sensor_type, name, icon, unit, entry_id): """Initialize the sensor.""" super().__init__(openuv) self._async_unsub_dispatcher_connect = None self._entry_id = entry_id self._icon = icon self._latitude = openuv.client.latitude self._longitude = openuv.client.longitude self._name = name self._sensor_type = sensor_type self._state = None self._unit = unit @property def icon(self): """Return the icon.""" return self._icon @property def should_poll(self): """Disable polling.""" return False @property def state(self): """Return the status of the sensor.""" return self._state @property def unique_id(self) -> str: """Return a unique, HASS-friendly identifier for this entity.""" return '{0}_{1}_{2}'.format( self._latitude, self._longitude, self._sensor_type) @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return self._unit async def async_added_to_hass(self): """Register callbacks.""" @callback def update(): """Update the state.""" self.async_schedule_update_ha_state(True) self._async_unsub_dispatcher_connect = async_dispatcher_connect( self.hass, TOPIC_UPDATE, update) async def async_will_remove_from_hass(self): """Disconnect dispatcher listener when removed.""" if self._async_unsub_dispatcher_connect: self._async_unsub_dispatcher_connect() async def async_update(self): """Update the state.""" data = self.openuv.data[DATA_UV]['result'] if self._sensor_type == TYPE_CURRENT_OZONE_LEVEL: self._state = data['ozone'] elif self._sensor_type == TYPE_CURRENT_UV_INDEX: self._state = data['uv'] elif self._sensor_type == TYPE_CURRENT_UV_LEVEL: if data['uv'] >= 11: self._state = UV_LEVEL_EXTREME elif data['uv'] >= 8: self._state = UV_LEVEL_VHIGH elif data['uv'] >= 6: self._state = UV_LEVEL_HIGH elif data['uv'] >= 3: self._state = UV_LEVEL_MODERATE else: self._state = UV_LEVEL_LOW elif self._sensor_type == TYPE_MAX_UV_INDEX: self._state = data['uv_max'] self._attrs.update({ ATTR_MAX_UV_TIME: as_local(parse_datetime(data['uv_max_time'])) }) elif self._sensor_type in (TYPE_SAFE_EXPOSURE_TIME_1, TYPE_SAFE_EXPOSURE_TIME_2, TYPE_SAFE_EXPOSURE_TIME_3, TYPE_SAFE_EXPOSURE_TIME_4, TYPE_SAFE_EXPOSURE_TIME_5, TYPE_SAFE_EXPOSURE_TIME_6): self._state = data['safe_exposure_time'][EXPOSURE_TYPE_MAP[ self._sensor_type]]
"""Tests for the Z-Wave init.""" import asyncio from collections import OrderedDict from datetime import datetime import unittest from unittest.mock import MagicMock, patch import pytest from pytz import utc import voluptuous as vol from homeassistant.bootstrap import async_setup_component from homeassistant.components import zwave from homeassistant.components.zwave import ( CONF_DEVICE_CONFIG_GLOB, CONFIG_SCHEMA, DATA_NETWORK, const) from homeassistant.components.zwave.binary_sensor import get_device from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.device_registry import ( async_get_registry as get_dev_reg) from homeassistant.setup import setup_component from tests.common import ( async_fire_time_changed, get_test_home_assistant, mock_coro, mock_registry) from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue async def test_valid_device_config(hass, mock_openzwave): """Test valid device config.""" device_config = { 'light.kitchen': { 'ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert result async def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = { 'light.kitchen': { 'some_ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert not result def test_config_access_error(): """Test threading error accessing config values.""" node = MagicMock() def side_effect(): raise RuntimeError node.values.values.side_effect = side_effect result = zwave.get_config_value(node, 1) assert result is None async def test_network_options(hass, mock_openzwave): """Test network options.""" result = await async_setup_component(hass, 'zwave', { 'zwave': { 'usb_path': 'mock_usb_path', 'config_path': 'mock_config_path', }}) await hass.async_block_till_done() assert result network = hass.data[zwave.DATA_NETWORK] assert network.options.device == 'mock_usb_path' assert network.options.config_path == 'mock_config_path' async def test_network_key_validation(hass, mock_openzwave): """Test network key validation.""" test_values = [ ('0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,' '0x0E,0x0F,0x10'), ] for value in test_values: result = zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) assert result['zwave']['network_key'] == value async def test_erronous_network_key_fails_validation(hass, mock_openzwave): """Test failing erronous network key validation.""" test_values = [ ('0x 01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0X01,0X02,0X03,0X04,0X05,0X06,0X07,0X08,0X09,0X0A,0X0B,0X0C,0X0D,' '0X0E,0X0F,0X10'), 'invalid', '1234567', 1234567 ] for value in test_values: with pytest.raises(vol.Invalid): zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) async def test_auto_heal_midnight(hass, mock_openzwave): """Test network auto-heal at midnight.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': True, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert network.heal.called assert len(network.heal.mock_calls) == 1 async def test_auto_heal_disabled(hass, mock_openzwave): """Test network auto-heal disabled.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': False, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert not network.heal.called async def test_setup_platform(hass, mock_openzwave): """Test invalid device config.""" mock_device = MagicMock() hass.data[DATA_NETWORK] = MagicMock() hass.data[zwave.DATA_DEVICES] = {456: mock_device} async_add_entities = MagicMock() result = await zwave.async_setup_platform( hass, None, async_add_entities, None) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 123}) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 456}) assert result assert async_add_entities.called assert len(async_add_entities.mock_calls) == 1 assert async_add_entities.mock_calls[0][1][0] == [mock_device] async def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): """Test device entity base class.""" node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.value_added() device.update_properties() await hass.async_block_till_done() assert not device.should_poll assert device.unique_id == "10-11" assert device.name == 'Mock Node Sensor' assert device.device_state_attributes[zwave.ATTR_POWER] == 50.123 async def test_node_removed(hass, mock_openzwave): """Test node removed in base class.""" # Create a mock node & node entity node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.entity_id = 'zwave.mock_node' device.value_added() device.update_properties() await hass.async_block_till_done() # Save it to the entity registry registry = mock_registry(hass) registry.async_get_or_create('zwave', 'zwave', device.unique_id) device.entity_id = registry.async_get_entity_id( 'zwave', 'zwave', device.unique_id) # Create dummy entity registry entries for other integrations hue_entity = registry.async_get_or_create('light', 'hue', 1234) zha_entity = registry.async_get_or_create('sensor', 'zha', 5678) # Verify our Z-Wave entity is registered assert registry.async_is_registered(device.entity_id) # Remove it entity_id = device.entity_id await device.node_removed() # Verify registry entry for our Z-Wave node is gone assert not registry.async_is_registered(entity_id) # Verify registry entries for our other entities remain assert registry.async_is_registered(hue_entity.entity_id) assert registry.async_is_registered(zha_entity.entity_id) async def test_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node').state == 'unknown' async def test_unparsed_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode( node_id=14, manufacturer_name=None, name=None, is_ready=False) sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert len(sleeps) == const.NODE_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1:] == \ (14, const.NODE_READY_WAIT_SECS) assert hass.states.get('zwave.unknown_node_14').state == 'unknown' async def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': { 'device_config': { 'zwave.mock_node': { 'ignored': True, }}}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None async def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' async def test_value_entities(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = {} def mock_connect(receiver, signal, *args, **kwargs): mock_receivers[signal] = receiver with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert mock_receivers hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_ALL_NODES_QUERIED]) node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) zwave_network.nodes = {node.node_id: node} value = MockValue( data=False, node=node, index=12, instance=1, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values = {'primary': value, value.value_id: value} value2 = MockValue( data=False, node=node, index=12, instance=2, label="Mock Value B", command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values[value2.value_id] = value2 hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_NODE_ADDED], node) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value2) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' assert hass.states.get( 'binary_sensor.mock_node_mock_value_b').state == 'off' ent_reg = await async_get_registry(hass) dev_reg = await get_dev_reg(hass) entry = ent_reg.async_get('zwave.mock_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) node_dev_id = entry.device_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) assert entry.name is None assert entry.device_id == node_dev_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value2.object_id) assert entry.name is None assert entry.device_id != node_dev_id device_id_b = entry.device_id device = dev_reg.async_get(node_dev_id) assert device is not None assert device.name == node.name old_device = device device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming without updating await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_NAME: "Demo Node", }) await hass.async_block_till_done() assert node.name == "Demo Node" entry = ent_reg.async_get('zwave.mock_node') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Node", }) await hass.async_block_till_done() assert node.name == "New Node" entry = ent_reg.async_get('zwave.new_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) entry = ent_reg.async_get('binary_sensor.new_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) await hass.services.async_call('zwave', 'rename_value', { const.ATTR_NODE_ID: node.node_id, const.ATTR_VALUE_ID: value.object_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Label", }) await hass.async_block_till_done() entry = ent_reg.async_get('binary_sensor.new_node_new_label') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) async def test_value_discovery_existing_entity(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_THERMOSTAT) setpoint = MockValue( data=22.0, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, setpoint) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] is None def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): temperature = MockValue( data=23.5, node=node, index=1, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, temperature) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] == 23.5 async def test_power_schemes(hass, mock_openzwave): """Test power attribute.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SWITCH_BINARY) switch = MockValue( data=True, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SWITCH_BINARY, genre=const.GENRE_USER, type=const.TYPE_BOOL) hass.async_add_job(mock_receivers[0], node, switch) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').state == 'on' assert 'power_consumption' not in hass.states.get( 'switch.mock_node_mock_value').attributes def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): power = MockValue( data=23.5, node=node, index=const.INDEX_SENSOR_MULTILEVEL_POWER, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL) hass.async_add_job(mock_receivers[0], node, power) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').attributes[ 'power_consumption'] == 23.5 async def test_network_ready(hass, mock_openzwave): """Test Node network ready event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete_some_dead(hass, mock_openzwave): """Test Node network complete some dead event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE_SOME_DEAD, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 class TestZWaveDeviceEntityValues(unittest.TestCase): """Tests for the ZWaveDeviceEntityValues helper.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() self.registry = mock_registry(self.hass) setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.node = MockNode() self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: ['mock_primary_class'], }, 'secondary': { const.DISC_COMMAND_CLASS: ['mock_secondary_class'], }, 'optional': { const.DISC_COMMAND_CLASS: ['mock_optional_class'], const.DISC_OPTIONAL: True, }}} self.primary = MockValue( command_class='mock_primary_class', node=self.node, value_id=1000) self.secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.duplicate_secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.optional = MockValue( command_class='mock_optional_class', node=self.node) self.no_match_value = MockValue( command_class='mock_bad_class', node=self.node) self.entity_id = 'mock_component.mock_node_mock_value' self.zwave_config = {'zwave': {}} self.device_config = {self.entity_id: {}} def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) assert values.primary is self.primary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) self.hass.block_till_done() assert values.secondary is self.secondary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config discovery.async_load_platform.reset_mock() values.check_value(self.optional) values.check_value(self.duplicate_secondary) values.check_value(self.no_match_value) self.hass.block_till_done() assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called assert len(values._entity.value_added.mock_calls) == 1 assert values._entity.value_changed.called assert len(values._entity.value_changed.mock_calls) == 1 @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, self.optional.value_id: self.optional, self.no_match_value.value_id: self.no_match_value, } values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert values.primary is self.primary assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config assert not self.primary.enable_poll.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_node_schema_mismatch(self, discovery, import_module): """Test node schema mismatch.""" self.node.generic = 'no_match' self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.mock_schema[const.DISC_GENERIC_DEVICE_CLASS] = ['generic_match'] values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.manufacturer_id = '010f' self.node.product_type = '0b00' self.primary.command_class = const.COMMAND_CLASS_SENSOR_ALARM self.entity_id = 'binary_sensor.mock_node_mock_value' self.device_config = {self.entity_id: {}} self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} with patch.object(zwave, 'async_dispatcher_send') as \ mock_dispatch_send: values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert mock_dispatch_send.called assert len(mock_dispatch_send.mock_calls) == 1 args = mock_dispatch_send.mock_calls[0][1] assert args[1] == 'zwave_new_binary_sensor' @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_ignore(self, discovery, import_module): """Test ignore workaround.""" self.node.manufacturer_id = '010f' self.node.product_type = '0301' self.primary.command_class = const.COMMAND_CLASS_SWITCH_BINARY self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore(self, discovery, import_module): """Test ignore config.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_IGNORED: True }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore_with_registry(self, discovery, import_module): """Test ignore config. The case when the device is in entity registry. """ self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {'mock_component.registry_id': { zwave.CONF_IGNORED: True }} with patch.object(self.registry, 'async_schedule_save'): self.registry.async_get_or_create( 'mock_component', zwave.DOMAIN, '567-1000', suggested_object_id='registry_id') zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_platform_ignore(self, discovery, import_module): """Test platform ignore device.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } platform = MagicMock() import_module.return_value = platform platform.get_device.return_value = None zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_config_polling_intensity(self, discovery, import_module): """Test polling intensity.""" mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_POLLING_INTENSITY: 123, }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert discovery.async_load_platform.called assert self.primary.enable_poll.called assert len(self.primary.enable_poll.mock_calls) == 1 assert self.primary.enable_poll.mock_calls[0][1][0] == 123 class TestZwave(unittest.TestCase): """Test zwave init.""" def test_device_config_glob_is_ordered(self): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): """Tests for zwave services.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() # Initialize zwave setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.zwave_network = self.hass.data[DATA_NETWORK] self.zwave_network.state = MockNetwork.STATE_READY self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.block_till_done() def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() self.hass.stop() def test_add_node(self): """Test zwave add_node service.""" self.hass.services.call('zwave', 'add_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller .add_node.mock_calls) == 1 assert len(self.zwave_network.controller .add_node.mock_calls[0][1]) == 0 def test_add_node_secure(self): """Test zwave add_node_secure service.""" self.hass.services.call('zwave', 'add_node_secure', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller.add_node.mock_calls) == 1 assert (self.zwave_network.controller .add_node.mock_calls[0][1][0] is True) def test_remove_node(self): """Test zwave remove_node service.""" self.hass.services.call('zwave', 'remove_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.remove_node.called assert len(self.zwave_network.controller.remove_node.mock_calls) == 1 def test_cancel_command(self): """Test zwave cancel_command service.""" self.hass.services.call('zwave', 'cancel_command', {}) self.hass.block_till_done() assert self.zwave_network.controller.cancel_command.called assert len(self.zwave_network.controller .cancel_command.mock_calls) == 1 def test_heal_network(self): """Test zwave heal_network service.""" self.hass.services.call('zwave', 'heal_network', {}) self.hass.block_till_done() assert self.zwave_network.heal.called assert len(self.zwave_network.heal.mock_calls) == 1 def test_soft_reset(self): """Test zwave soft_reset service.""" self.hass.services.call('zwave', 'soft_reset', {}) self.hass.block_till_done() assert self.zwave_network.controller.soft_reset.called assert len(self.zwave_network.controller.soft_reset.mock_calls) == 1 def test_test_network(self): """Test zwave test_network service.""" self.hass.services.call('zwave', 'test_network', {}) self.hass.block_till_done() assert self.zwave_network.test.called assert len(self.zwave_network.test.mock_calls) == 1 def test_stop_network(self): """Test zwave stop_network service.""" with patch.object(self.hass.bus, 'fire') as mock_fire: self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() assert self.zwave_network.stop.called assert len(self.zwave_network.stop.mock_calls) == 1 assert mock_fire.called assert len(mock_fire.mock_calls) == 1 assert mock_fire.mock_calls[0][1][0] == const.EVENT_NETWORK_STOP def test_rename_node(self): """Test zwave rename_node service.""" self.zwave_network.nodes = {11: MagicMock()} self.hass.services.call('zwave', 'rename_node', { const.ATTR_NODE_ID: 11, const.ATTR_NAME: 'test_name', }) self.hass.block_till_done() assert self.zwave_network.nodes[11].name == 'test_name' def test_rename_value(self): """Test zwave rename_value service.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, label="Old Label") node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.label == "Old Label" self.hass.services.call('zwave', 'rename_value', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_NAME: "New Label", }) self.hass.block_till_done() assert value.label == "New Label" def test_set_poll_intensity_enable(self): """Test zwave set_poll_intensity service, successful set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 2 assert enable_poll.mock_calls[0][1][0] == 4 def test_set_poll_intensity_enable_failed(self): """Test zwave set_poll_intensity service, failed set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) value.enable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 1 def test_set_poll_intensity_disable(self): """Test zwave set_poll_intensity service, successful disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 2 def test_set_poll_intensity_disable_failed(self): """Test zwave set_poll_intensity service, failed disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) value.disable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 1 def test_remove_failed_node(self): """Test zwave remove_failed_node service.""" self.hass.services.call('zwave', 'remove_failed_node', { const.ATTR_NODE_ID: 12, }) self.hass.block_till_done() remove_failed_node = self.zwave_network.controller.remove_failed_node assert remove_failed_node.called assert len(remove_failed_node.mock_calls) == 1 assert remove_failed_node.mock_calls[0][1][0] == 12 def test_replace_failed_node(self): """Test zwave replace_failed_node service.""" self.hass.services.call('zwave', 'replace_failed_node', { const.ATTR_NODE_ID: 13, }) self.hass.block_till_done() replace_failed_node = self.zwave_network.controller.replace_failed_node assert replace_failed_node.called assert len(replace_failed_node.mock_calls) == 1 assert replace_failed_node.mock_calls[0][1][0] == 13 def test_set_config_parameter(self): """Test zwave set_config_parameter service.""" value_byte = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BYTE, ) value_list = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['item1', 'item2', 'item3'], ) value_button = MockValue( index=14, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BUTTON, ) value_list_int = MockValue( index=15, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['1', '2', '3'], ) value_bool = MockValue( index=16, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BOOL, ) node = MockNode(node_id=14) node.get_values.return_value = { 12: value_byte, 13: value_list, 14: value_button, 15: value_list_int, 16: value_bool } self.zwave_network.nodes = {14: node} # Byte self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 12, const.ATTR_CONFIG_VALUE: 7, }) self.hass.block_till_done() assert value_byte.data == 7 # List self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, const.ATTR_CONFIG_VALUE: 'item3', }) self.hass.block_till_done() assert value_list.data == 'item3' # Button self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 14, const.ATTR_CONFIG_VALUE: True, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called assert self.zwave_network.manager.releaseButton.called # List of Ints self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 15, const.ATTR_CONFIG_VALUE: 3, }) self.hass.block_till_done() assert value_list_int.data == '3' # Boolean Truthy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'True', }) self.hass.block_till_done() assert value_bool.data == 1 # Boolean Falsy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'False', }) self.hass.block_till_done() assert value_bool.data == 0 # Different Parameter Size self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 19, const.ATTR_CONFIG_VALUE: 0x01020304, const.ATTR_CONFIG_SIZE: 4 }) self.hass.block_till_done() assert node.set_config_param.called assert len(node.set_config_param.mock_calls) == 1 assert node.set_config_param.mock_calls[0][1][0] == 19 assert node.set_config_param.mock_calls[0][1][1] == 0x01020304 assert node.set_config_param.mock_calls[0][1][2] == 4 node.set_config_param.reset_mock() def test_print_config_parameter(self): """Test zwave print_config_parameter service.""" value1 = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, data=1234, ) value2 = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, data=2345, ) node = MockNode(node_id=14) node.values = {12: value1, 13: value2} self.zwave_network.nodes = {14: node} with patch.object(zwave, '_LOGGER') as mock_logger: self.hass.services.call('zwave', 'print_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, }) self.hass.block_till_done() assert mock_logger.info.called assert len(mock_logger.info.mock_calls) == 1 assert mock_logger.info.mock_calls[0][1][1] == 13 assert mock_logger.info.mock_calls[0][1][2] == 14 assert mock_logger.info.mock_calls[0][1][3] == 2345 def test_print_node(self): """Test zwave print_node_parameter service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} with self.assertLogs(level='DEBUG') as mock_logger: self.hass.services.call('zwave', 'print_node', { const.ATTR_NODE_ID: 14 }) self.hass.block_till_done() assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 15, }) self.hass.block_till_done() assert value.data == 15 node.can_wake_up_value = False self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 20, }) self.hass.block_till_done() assert value.data == 15 def test_reset_node_meters(self): """Test zwave reset_node_meters service.""" value = MockValue( instance=1, index=8, data=99.5, command_class=const.COMMAND_CLASS_METER, ) reset_value = MockValue( instance=1, index=33, command_class=const.COMMAND_CLASS_METER, ) node = MockNode(node_id=14) node.values = {8: value, 33: reset_value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, const.ATTR_INSTANCE: 2, }) self.hass.block_till_done() assert not self.zwave_network.manager.pressButton.called assert not self.zwave_network.manager.releaseButton.called self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called value_id, = self.zwave_network.manager.pressButton.mock_calls.pop(0)[1] assert value_id == reset_value.value_id assert self.zwave_network.manager.releaseButton.called value_id, = ( self.zwave_network.manager.releaseButton.mock_calls.pop(0)[1]) assert value_id == reset_value.value_id def test_add_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'add', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.add_association.called assert len(group.add_association.mock_calls) == 1 assert group.add_association.mock_calls[0][1][0] == 24 assert group.add_association.mock_calls[0][1][1] == 5 def test_remove_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'remove', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.remove_association.called assert len(group.remove_association.mock_calls) == 1 assert group.remove_association.mock_calls[0][1][0] == 24 assert group.remove_association.mock_calls[0][1][1] == 5 def test_refresh_entity(self): """Test zwave refresh_entity service.""" node = MockNode() value = MockValue(data=False, node=node, command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50, node=node, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = get_device(node=node, values=values, node_config={}) device.hass = self.hass device.entity_id = 'binary_sensor.mock_entity_id' self.hass.add_job(device.async_added_to_hass()) self.hass.block_till_done() self.hass.services.call('zwave', 'refresh_entity', { ATTR_ENTITY_ID: 'binary_sensor.mock_entity_id', }) self.hass.block_till_done() assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 assert sorted([node.refresh_value.mock_calls[0][1][0], node.refresh_value.mock_calls[1][1][0]]) == \ sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert node.refresh_info.called assert len(node.refresh_info.mock_calls) == 1 def test_set_node_value(self): """Test zwave set_node_value service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=4 ) node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR]) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12, const.ATTR_CONFIG_VALUE: 2, }) self.hass.block_till_done() assert self.zwave_network.nodes[14].values[12].data == 2 def test_refresh_node_value(self): """Test zwave refresh_node_value service.""" node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR], network=self.zwave_network) value = MockValue( node=node, index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=2 ) value.refresh = MagicMock() node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12 }) self.hass.block_till_done() assert value.refresh.called def test_heal_node(self): """Test zwave heal_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'heal_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.heal.called assert len(node.heal.mock_calls) == 1 def test_test_node(self): """Test the zwave test_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'test_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.test.called assert len(node.test.mock_calls) == 1
jabesq/home-assistant
tests/components/zwave/test_init.py
homeassistant/components/openuv/sensor.py
""" Support for MQTT Template lights. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/light.mqtt_template/ """ import logging import voluptuous as vol from homeassistant.core import callback from homeassistant.components import mqtt from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_FLASH, ATTR_HS_COLOR, ATTR_TRANSITION, ATTR_WHITE_VALUE, Light, SUPPORT_BRIGHTNESS, SUPPORT_COLOR_TEMP, SUPPORT_EFFECT, SUPPORT_FLASH, SUPPORT_COLOR, SUPPORT_TRANSITION, SUPPORT_WHITE_VALUE) from homeassistant.const import ( CONF_DEVICE, CONF_NAME, CONF_OPTIMISTIC, STATE_ON, STATE_OFF) from homeassistant.components.mqtt import ( CONF_COMMAND_TOPIC, CONF_QOS, CONF_RETAIN, CONF_STATE_TOPIC, CONF_UNIQUE_ID, MqttAttributes, MqttAvailability, MqttDiscoveryUpdate, MqttEntityDeviceInfo, subscription) import homeassistant.helpers.config_validation as cv import homeassistant.util.color as color_util from homeassistant.helpers.restore_state import RestoreEntity from . import MQTT_LIGHT_SCHEMA_SCHEMA _LOGGER = logging.getLogger(__name__) DOMAIN = 'mqtt_template' DEFAULT_NAME = 'MQTT Template Light' DEFAULT_OPTIMISTIC = False CONF_BLUE_TEMPLATE = 'blue_template' CONF_BRIGHTNESS_TEMPLATE = 'brightness_template' CONF_COLOR_TEMP_TEMPLATE = 'color_temp_template' CONF_COMMAND_OFF_TEMPLATE = 'command_off_template' CONF_COMMAND_ON_TEMPLATE = 'command_on_template' CONF_EFFECT_LIST = 'effect_list' CONF_EFFECT_TEMPLATE = 'effect_template' CONF_GREEN_TEMPLATE = 'green_template' CONF_RED_TEMPLATE = 'red_template' CONF_STATE_TEMPLATE = 'state_template' CONF_WHITE_VALUE_TEMPLATE = 'white_value_template' PLATFORM_SCHEMA_TEMPLATE = mqtt.MQTT_RW_PLATFORM_SCHEMA.extend({ vol.Optional(CONF_BLUE_TEMPLATE): cv.template, vol.Optional(CONF_BRIGHTNESS_TEMPLATE): cv.template, vol.Optional(CONF_COLOR_TEMP_TEMPLATE): cv.template, vol.Required(CONF_COMMAND_OFF_TEMPLATE): cv.template, vol.Required(CONF_COMMAND_ON_TEMPLATE): cv.template, vol.Optional(CONF_DEVICE): mqtt.MQTT_ENTITY_DEVICE_INFO_SCHEMA, vol.Optional(CONF_EFFECT_LIST): vol.All(cv.ensure_list, [cv.string]), vol.Optional(CONF_EFFECT_TEMPLATE): cv.template, vol.Optional(CONF_GREEN_TEMPLATE): cv.template, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_OPTIMISTIC, default=DEFAULT_OPTIMISTIC): cv.boolean, vol.Optional(CONF_RED_TEMPLATE): cv.template, vol.Optional(CONF_STATE_TEMPLATE): cv.template, vol.Optional(CONF_UNIQUE_ID): cv.string, vol.Optional(CONF_WHITE_VALUE_TEMPLATE): cv.template, }).extend(mqtt.MQTT_AVAILABILITY_SCHEMA.schema).extend( mqtt.MQTT_JSON_ATTRS_SCHEMA.schema).extend(MQTT_LIGHT_SCHEMA_SCHEMA.schema) async def async_setup_entity_template(config, async_add_entities, config_entry, discovery_hash): """Set up a MQTT Template light.""" async_add_entities([MqttTemplate(config, config_entry, discovery_hash)]) # pylint: disable=too-many-ancestors class MqttTemplate(MqttAttributes, MqttAvailability, MqttDiscoveryUpdate, MqttEntityDeviceInfo, Light, RestoreEntity): """Representation of a MQTT Template light.""" def __init__(self, config, config_entry, discovery_hash): """Initialize a MQTT Template light.""" self._state = False self._sub_state = None self._topics = None self._templates = None self._optimistic = False # features self._brightness = None self._color_temp = None self._white_value = None self._hs = None self._effect = None self._unique_id = config.get(CONF_UNIQUE_ID) # Load config self._setup_from_config(config) device_config = config.get(CONF_DEVICE) MqttAttributes.__init__(self, config) MqttAvailability.__init__(self, config) MqttDiscoveryUpdate.__init__(self, discovery_hash, self.discovery_update) MqttEntityDeviceInfo.__init__(self, device_config, config_entry) async def async_added_to_hass(self): """Subscribe to MQTT events.""" await super().async_added_to_hass() await self._subscribe_topics() async def discovery_update(self, discovery_payload): """Handle updated discovery message.""" config = PLATFORM_SCHEMA_TEMPLATE(discovery_payload) self._setup_from_config(config) await self.attributes_discovery_update(config) await self.availability_discovery_update(config) await self.device_info_discovery_update(config) await self._subscribe_topics() self.async_write_ha_state() def _setup_from_config(self, config): """(Re)Setup the entity.""" self._config = config self._topics = { key: config.get(key) for key in ( CONF_STATE_TOPIC, CONF_COMMAND_TOPIC ) } self._templates = { key: config.get(key) for key in ( CONF_BLUE_TEMPLATE, CONF_BRIGHTNESS_TEMPLATE, CONF_COLOR_TEMP_TEMPLATE, CONF_COMMAND_OFF_TEMPLATE, CONF_COMMAND_ON_TEMPLATE, CONF_EFFECT_TEMPLATE, CONF_GREEN_TEMPLATE, CONF_RED_TEMPLATE, CONF_STATE_TEMPLATE, CONF_WHITE_VALUE_TEMPLATE, ) } optimistic = config[CONF_OPTIMISTIC] self._optimistic = optimistic \ or self._topics[CONF_STATE_TOPIC] is None \ or self._templates[CONF_STATE_TEMPLATE] is None # features if self._templates[CONF_BRIGHTNESS_TEMPLATE] is not None: self._brightness = 255 else: self._brightness = None if self._templates[CONF_COLOR_TEMP_TEMPLATE] is not None: self._color_temp = 255 else: self._color_temp = None if self._templates[CONF_WHITE_VALUE_TEMPLATE] is not None: self._white_value = 255 else: self._white_value = None if (self._templates[CONF_RED_TEMPLATE] is not None and self._templates[CONF_GREEN_TEMPLATE] is not None and self._templates[CONF_BLUE_TEMPLATE] is not None): self._hs = [0, 0] else: self._hs = None self._effect = None async def _subscribe_topics(self): """(Re)Subscribe to topics.""" for tpl in self._templates.values(): if tpl is not None: tpl.hass = self.hass last_state = await self.async_get_last_state() @callback def state_received(msg): """Handle new MQTT messages.""" state = self._templates[CONF_STATE_TEMPLATE].\ async_render_with_possible_json_value(msg.payload) if state == STATE_ON: self._state = True elif state == STATE_OFF: self._state = False else: _LOGGER.warning("Invalid state value received") if self._brightness is not None: try: self._brightness = int( self._templates[CONF_BRIGHTNESS_TEMPLATE]. async_render_with_possible_json_value(msg.payload) ) except ValueError: _LOGGER.warning("Invalid brightness value received") if self._color_temp is not None: try: self._color_temp = int( self._templates[CONF_COLOR_TEMP_TEMPLATE]. async_render_with_possible_json_value(msg.payload) ) except ValueError: _LOGGER.warning("Invalid color temperature value received") if self._hs is not None: try: red = int( self._templates[CONF_RED_TEMPLATE]. async_render_with_possible_json_value(msg.payload)) green = int( self._templates[CONF_GREEN_TEMPLATE]. async_render_with_possible_json_value(msg.payload)) blue = int( self._templates[CONF_BLUE_TEMPLATE]. async_render_with_possible_json_value(msg.payload)) self._hs = color_util.color_RGB_to_hs(red, green, blue) except ValueError: _LOGGER.warning("Invalid color value received") if self._white_value is not None: try: self._white_value = int( self._templates[CONF_WHITE_VALUE_TEMPLATE]. async_render_with_possible_json_value(msg.payload) ) except ValueError: _LOGGER.warning('Invalid white value received') if self._templates[CONF_EFFECT_TEMPLATE] is not None: effect = self._templates[CONF_EFFECT_TEMPLATE].\ async_render_with_possible_json_value(msg.payload) if effect in self._config.get(CONF_EFFECT_LIST): self._effect = effect else: _LOGGER.warning("Unsupported effect value received") self.async_write_ha_state() if self._topics[CONF_STATE_TOPIC] is not None: self._sub_state = await subscription.async_subscribe_topics( self.hass, self._sub_state, {'state_topic': {'topic': self._topics[CONF_STATE_TOPIC], 'msg_callback': state_received, 'qos': self._config[CONF_QOS]}}) if self._optimistic and last_state: self._state = last_state.state == STATE_ON if last_state.attributes.get(ATTR_BRIGHTNESS): self._brightness = last_state.attributes.get(ATTR_BRIGHTNESS) if last_state.attributes.get(ATTR_HS_COLOR): self._hs = last_state.attributes.get(ATTR_HS_COLOR) if last_state.attributes.get(ATTR_COLOR_TEMP): self._color_temp = last_state.attributes.get(ATTR_COLOR_TEMP) if last_state.attributes.get(ATTR_EFFECT): self._effect = last_state.attributes.get(ATTR_EFFECT) if last_state.attributes.get(ATTR_WHITE_VALUE): self._white_value = last_state.attributes.get(ATTR_WHITE_VALUE) async def async_will_remove_from_hass(self): """Unsubscribe when removed.""" self._sub_state = await subscription.async_unsubscribe_topics( self.hass, self._sub_state) await MqttAttributes.async_will_remove_from_hass(self) await MqttAvailability.async_will_remove_from_hass(self) @property def brightness(self): """Return the brightness of this light between 0..255.""" return self._brightness @property def color_temp(self): """Return the color temperature in mired.""" return self._color_temp @property def hs_color(self): """Return the hs color value [int, int].""" return self._hs @property def white_value(self): """Return the white property.""" return self._white_value @property def should_poll(self): """Return True if entity has to be polled for state. False if entity pushes its state to HA. """ return False @property def name(self): """Return the name of the entity.""" return self._config[CONF_NAME] @property def unique_id(self): """Return a unique ID.""" return self._unique_id @property def is_on(self): """Return True if entity is on.""" return self._state @property def assumed_state(self): """Return True if unable to access real state of the entity.""" return self._optimistic @property def effect_list(self): """Return the list of supported effects.""" return self._config.get(CONF_EFFECT_LIST) @property def effect(self): """Return the current effect.""" return self._effect async def async_turn_on(self, **kwargs): """Turn the entity on. This method is a coroutine. """ values = {'state': True} if self._optimistic: self._state = True if ATTR_BRIGHTNESS in kwargs: values['brightness'] = int(kwargs[ATTR_BRIGHTNESS]) if self._optimistic: self._brightness = kwargs[ATTR_BRIGHTNESS] if ATTR_COLOR_TEMP in kwargs: values['color_temp'] = int(kwargs[ATTR_COLOR_TEMP]) if self._optimistic: self._color_temp = kwargs[ATTR_COLOR_TEMP] if ATTR_HS_COLOR in kwargs: hs_color = kwargs[ATTR_HS_COLOR] # If there's a brightness topic set, we don't want to scale the RGB # values given using the brightness. if self._templates[CONF_BRIGHTNESS_TEMPLATE] is not None: brightness = 255 else: brightness = kwargs.get( ATTR_BRIGHTNESS, self._brightness if self._brightness else 255) rgb = color_util.color_hsv_to_RGB( hs_color[0], hs_color[1], brightness / 255 * 100) values['red'] = rgb[0] values['green'] = rgb[1] values['blue'] = rgb[2] if self._optimistic: self._hs = kwargs[ATTR_HS_COLOR] if ATTR_WHITE_VALUE in kwargs: values['white_value'] = int(kwargs[ATTR_WHITE_VALUE]) if self._optimistic: self._white_value = kwargs[ATTR_WHITE_VALUE] if ATTR_EFFECT in kwargs: values['effect'] = kwargs.get(ATTR_EFFECT) if ATTR_FLASH in kwargs: values['flash'] = kwargs.get(ATTR_FLASH) if ATTR_TRANSITION in kwargs: values['transition'] = int(kwargs[ATTR_TRANSITION]) mqtt.async_publish( self.hass, self._topics[CONF_COMMAND_TOPIC], self._templates[CONF_COMMAND_ON_TEMPLATE].async_render(**values), self._config[CONF_QOS], self._config[CONF_RETAIN] ) if self._optimistic: self.async_write_ha_state() async def async_turn_off(self, **kwargs): """Turn the entity off. This method is a coroutine. """ values = {'state': False} if self._optimistic: self._state = False if ATTR_TRANSITION in kwargs: values['transition'] = int(kwargs[ATTR_TRANSITION]) mqtt.async_publish( self.hass, self._topics[CONF_COMMAND_TOPIC], self._templates[CONF_COMMAND_OFF_TEMPLATE].async_render(**values), self._config[CONF_QOS], self._config[CONF_RETAIN] ) if self._optimistic: self.async_write_ha_state() @property def supported_features(self): """Flag supported features.""" features = (SUPPORT_FLASH | SUPPORT_TRANSITION) if self._brightness is not None: features = features | SUPPORT_BRIGHTNESS if self._hs is not None: features = features | SUPPORT_COLOR if self._config.get(CONF_EFFECT_LIST) is not None: features = features | SUPPORT_EFFECT if self._color_temp is not None: features = features | SUPPORT_COLOR_TEMP if self._white_value is not None: features = features | SUPPORT_WHITE_VALUE return features
"""Tests for the Z-Wave init.""" import asyncio from collections import OrderedDict from datetime import datetime import unittest from unittest.mock import MagicMock, patch import pytest from pytz import utc import voluptuous as vol from homeassistant.bootstrap import async_setup_component from homeassistant.components import zwave from homeassistant.components.zwave import ( CONF_DEVICE_CONFIG_GLOB, CONFIG_SCHEMA, DATA_NETWORK, const) from homeassistant.components.zwave.binary_sensor import get_device from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.device_registry import ( async_get_registry as get_dev_reg) from homeassistant.setup import setup_component from tests.common import ( async_fire_time_changed, get_test_home_assistant, mock_coro, mock_registry) from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue async def test_valid_device_config(hass, mock_openzwave): """Test valid device config.""" device_config = { 'light.kitchen': { 'ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert result async def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = { 'light.kitchen': { 'some_ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert not result def test_config_access_error(): """Test threading error accessing config values.""" node = MagicMock() def side_effect(): raise RuntimeError node.values.values.side_effect = side_effect result = zwave.get_config_value(node, 1) assert result is None async def test_network_options(hass, mock_openzwave): """Test network options.""" result = await async_setup_component(hass, 'zwave', { 'zwave': { 'usb_path': 'mock_usb_path', 'config_path': 'mock_config_path', }}) await hass.async_block_till_done() assert result network = hass.data[zwave.DATA_NETWORK] assert network.options.device == 'mock_usb_path' assert network.options.config_path == 'mock_config_path' async def test_network_key_validation(hass, mock_openzwave): """Test network key validation.""" test_values = [ ('0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,' '0x0E,0x0F,0x10'), ] for value in test_values: result = zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) assert result['zwave']['network_key'] == value async def test_erronous_network_key_fails_validation(hass, mock_openzwave): """Test failing erronous network key validation.""" test_values = [ ('0x 01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0X01,0X02,0X03,0X04,0X05,0X06,0X07,0X08,0X09,0X0A,0X0B,0X0C,0X0D,' '0X0E,0X0F,0X10'), 'invalid', '1234567', 1234567 ] for value in test_values: with pytest.raises(vol.Invalid): zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) async def test_auto_heal_midnight(hass, mock_openzwave): """Test network auto-heal at midnight.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': True, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert network.heal.called assert len(network.heal.mock_calls) == 1 async def test_auto_heal_disabled(hass, mock_openzwave): """Test network auto-heal disabled.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': False, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert not network.heal.called async def test_setup_platform(hass, mock_openzwave): """Test invalid device config.""" mock_device = MagicMock() hass.data[DATA_NETWORK] = MagicMock() hass.data[zwave.DATA_DEVICES] = {456: mock_device} async_add_entities = MagicMock() result = await zwave.async_setup_platform( hass, None, async_add_entities, None) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 123}) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 456}) assert result assert async_add_entities.called assert len(async_add_entities.mock_calls) == 1 assert async_add_entities.mock_calls[0][1][0] == [mock_device] async def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): """Test device entity base class.""" node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.value_added() device.update_properties() await hass.async_block_till_done() assert not device.should_poll assert device.unique_id == "10-11" assert device.name == 'Mock Node Sensor' assert device.device_state_attributes[zwave.ATTR_POWER] == 50.123 async def test_node_removed(hass, mock_openzwave): """Test node removed in base class.""" # Create a mock node & node entity node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.entity_id = 'zwave.mock_node' device.value_added() device.update_properties() await hass.async_block_till_done() # Save it to the entity registry registry = mock_registry(hass) registry.async_get_or_create('zwave', 'zwave', device.unique_id) device.entity_id = registry.async_get_entity_id( 'zwave', 'zwave', device.unique_id) # Create dummy entity registry entries for other integrations hue_entity = registry.async_get_or_create('light', 'hue', 1234) zha_entity = registry.async_get_or_create('sensor', 'zha', 5678) # Verify our Z-Wave entity is registered assert registry.async_is_registered(device.entity_id) # Remove it entity_id = device.entity_id await device.node_removed() # Verify registry entry for our Z-Wave node is gone assert not registry.async_is_registered(entity_id) # Verify registry entries for our other entities remain assert registry.async_is_registered(hue_entity.entity_id) assert registry.async_is_registered(zha_entity.entity_id) async def test_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node').state == 'unknown' async def test_unparsed_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode( node_id=14, manufacturer_name=None, name=None, is_ready=False) sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert len(sleeps) == const.NODE_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1:] == \ (14, const.NODE_READY_WAIT_SECS) assert hass.states.get('zwave.unknown_node_14').state == 'unknown' async def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': { 'device_config': { 'zwave.mock_node': { 'ignored': True, }}}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None async def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' async def test_value_entities(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = {} def mock_connect(receiver, signal, *args, **kwargs): mock_receivers[signal] = receiver with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert mock_receivers hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_ALL_NODES_QUERIED]) node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) zwave_network.nodes = {node.node_id: node} value = MockValue( data=False, node=node, index=12, instance=1, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values = {'primary': value, value.value_id: value} value2 = MockValue( data=False, node=node, index=12, instance=2, label="Mock Value B", command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values[value2.value_id] = value2 hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_NODE_ADDED], node) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value2) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' assert hass.states.get( 'binary_sensor.mock_node_mock_value_b').state == 'off' ent_reg = await async_get_registry(hass) dev_reg = await get_dev_reg(hass) entry = ent_reg.async_get('zwave.mock_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) node_dev_id = entry.device_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) assert entry.name is None assert entry.device_id == node_dev_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value2.object_id) assert entry.name is None assert entry.device_id != node_dev_id device_id_b = entry.device_id device = dev_reg.async_get(node_dev_id) assert device is not None assert device.name == node.name old_device = device device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming without updating await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_NAME: "Demo Node", }) await hass.async_block_till_done() assert node.name == "Demo Node" entry = ent_reg.async_get('zwave.mock_node') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Node", }) await hass.async_block_till_done() assert node.name == "New Node" entry = ent_reg.async_get('zwave.new_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) entry = ent_reg.async_get('binary_sensor.new_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) await hass.services.async_call('zwave', 'rename_value', { const.ATTR_NODE_ID: node.node_id, const.ATTR_VALUE_ID: value.object_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Label", }) await hass.async_block_till_done() entry = ent_reg.async_get('binary_sensor.new_node_new_label') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) async def test_value_discovery_existing_entity(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_THERMOSTAT) setpoint = MockValue( data=22.0, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, setpoint) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] is None def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): temperature = MockValue( data=23.5, node=node, index=1, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, temperature) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] == 23.5 async def test_power_schemes(hass, mock_openzwave): """Test power attribute.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SWITCH_BINARY) switch = MockValue( data=True, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SWITCH_BINARY, genre=const.GENRE_USER, type=const.TYPE_BOOL) hass.async_add_job(mock_receivers[0], node, switch) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').state == 'on' assert 'power_consumption' not in hass.states.get( 'switch.mock_node_mock_value').attributes def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): power = MockValue( data=23.5, node=node, index=const.INDEX_SENSOR_MULTILEVEL_POWER, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL) hass.async_add_job(mock_receivers[0], node, power) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').attributes[ 'power_consumption'] == 23.5 async def test_network_ready(hass, mock_openzwave): """Test Node network ready event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete_some_dead(hass, mock_openzwave): """Test Node network complete some dead event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE_SOME_DEAD, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 class TestZWaveDeviceEntityValues(unittest.TestCase): """Tests for the ZWaveDeviceEntityValues helper.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() self.registry = mock_registry(self.hass) setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.node = MockNode() self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: ['mock_primary_class'], }, 'secondary': { const.DISC_COMMAND_CLASS: ['mock_secondary_class'], }, 'optional': { const.DISC_COMMAND_CLASS: ['mock_optional_class'], const.DISC_OPTIONAL: True, }}} self.primary = MockValue( command_class='mock_primary_class', node=self.node, value_id=1000) self.secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.duplicate_secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.optional = MockValue( command_class='mock_optional_class', node=self.node) self.no_match_value = MockValue( command_class='mock_bad_class', node=self.node) self.entity_id = 'mock_component.mock_node_mock_value' self.zwave_config = {'zwave': {}} self.device_config = {self.entity_id: {}} def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) assert values.primary is self.primary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) self.hass.block_till_done() assert values.secondary is self.secondary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config discovery.async_load_platform.reset_mock() values.check_value(self.optional) values.check_value(self.duplicate_secondary) values.check_value(self.no_match_value) self.hass.block_till_done() assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called assert len(values._entity.value_added.mock_calls) == 1 assert values._entity.value_changed.called assert len(values._entity.value_changed.mock_calls) == 1 @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, self.optional.value_id: self.optional, self.no_match_value.value_id: self.no_match_value, } values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert values.primary is self.primary assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config assert not self.primary.enable_poll.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_node_schema_mismatch(self, discovery, import_module): """Test node schema mismatch.""" self.node.generic = 'no_match' self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.mock_schema[const.DISC_GENERIC_DEVICE_CLASS] = ['generic_match'] values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.manufacturer_id = '010f' self.node.product_type = '0b00' self.primary.command_class = const.COMMAND_CLASS_SENSOR_ALARM self.entity_id = 'binary_sensor.mock_node_mock_value' self.device_config = {self.entity_id: {}} self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} with patch.object(zwave, 'async_dispatcher_send') as \ mock_dispatch_send: values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert mock_dispatch_send.called assert len(mock_dispatch_send.mock_calls) == 1 args = mock_dispatch_send.mock_calls[0][1] assert args[1] == 'zwave_new_binary_sensor' @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_ignore(self, discovery, import_module): """Test ignore workaround.""" self.node.manufacturer_id = '010f' self.node.product_type = '0301' self.primary.command_class = const.COMMAND_CLASS_SWITCH_BINARY self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore(self, discovery, import_module): """Test ignore config.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_IGNORED: True }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore_with_registry(self, discovery, import_module): """Test ignore config. The case when the device is in entity registry. """ self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {'mock_component.registry_id': { zwave.CONF_IGNORED: True }} with patch.object(self.registry, 'async_schedule_save'): self.registry.async_get_or_create( 'mock_component', zwave.DOMAIN, '567-1000', suggested_object_id='registry_id') zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_platform_ignore(self, discovery, import_module): """Test platform ignore device.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } platform = MagicMock() import_module.return_value = platform platform.get_device.return_value = None zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_config_polling_intensity(self, discovery, import_module): """Test polling intensity.""" mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_POLLING_INTENSITY: 123, }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert discovery.async_load_platform.called assert self.primary.enable_poll.called assert len(self.primary.enable_poll.mock_calls) == 1 assert self.primary.enable_poll.mock_calls[0][1][0] == 123 class TestZwave(unittest.TestCase): """Test zwave init.""" def test_device_config_glob_is_ordered(self): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): """Tests for zwave services.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() # Initialize zwave setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.zwave_network = self.hass.data[DATA_NETWORK] self.zwave_network.state = MockNetwork.STATE_READY self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.block_till_done() def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() self.hass.stop() def test_add_node(self): """Test zwave add_node service.""" self.hass.services.call('zwave', 'add_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller .add_node.mock_calls) == 1 assert len(self.zwave_network.controller .add_node.mock_calls[0][1]) == 0 def test_add_node_secure(self): """Test zwave add_node_secure service.""" self.hass.services.call('zwave', 'add_node_secure', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller.add_node.mock_calls) == 1 assert (self.zwave_network.controller .add_node.mock_calls[0][1][0] is True) def test_remove_node(self): """Test zwave remove_node service.""" self.hass.services.call('zwave', 'remove_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.remove_node.called assert len(self.zwave_network.controller.remove_node.mock_calls) == 1 def test_cancel_command(self): """Test zwave cancel_command service.""" self.hass.services.call('zwave', 'cancel_command', {}) self.hass.block_till_done() assert self.zwave_network.controller.cancel_command.called assert len(self.zwave_network.controller .cancel_command.mock_calls) == 1 def test_heal_network(self): """Test zwave heal_network service.""" self.hass.services.call('zwave', 'heal_network', {}) self.hass.block_till_done() assert self.zwave_network.heal.called assert len(self.zwave_network.heal.mock_calls) == 1 def test_soft_reset(self): """Test zwave soft_reset service.""" self.hass.services.call('zwave', 'soft_reset', {}) self.hass.block_till_done() assert self.zwave_network.controller.soft_reset.called assert len(self.zwave_network.controller.soft_reset.mock_calls) == 1 def test_test_network(self): """Test zwave test_network service.""" self.hass.services.call('zwave', 'test_network', {}) self.hass.block_till_done() assert self.zwave_network.test.called assert len(self.zwave_network.test.mock_calls) == 1 def test_stop_network(self): """Test zwave stop_network service.""" with patch.object(self.hass.bus, 'fire') as mock_fire: self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() assert self.zwave_network.stop.called assert len(self.zwave_network.stop.mock_calls) == 1 assert mock_fire.called assert len(mock_fire.mock_calls) == 1 assert mock_fire.mock_calls[0][1][0] == const.EVENT_NETWORK_STOP def test_rename_node(self): """Test zwave rename_node service.""" self.zwave_network.nodes = {11: MagicMock()} self.hass.services.call('zwave', 'rename_node', { const.ATTR_NODE_ID: 11, const.ATTR_NAME: 'test_name', }) self.hass.block_till_done() assert self.zwave_network.nodes[11].name == 'test_name' def test_rename_value(self): """Test zwave rename_value service.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, label="Old Label") node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.label == "Old Label" self.hass.services.call('zwave', 'rename_value', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_NAME: "New Label", }) self.hass.block_till_done() assert value.label == "New Label" def test_set_poll_intensity_enable(self): """Test zwave set_poll_intensity service, successful set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 2 assert enable_poll.mock_calls[0][1][0] == 4 def test_set_poll_intensity_enable_failed(self): """Test zwave set_poll_intensity service, failed set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) value.enable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 1 def test_set_poll_intensity_disable(self): """Test zwave set_poll_intensity service, successful disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 2 def test_set_poll_intensity_disable_failed(self): """Test zwave set_poll_intensity service, failed disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) value.disable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 1 def test_remove_failed_node(self): """Test zwave remove_failed_node service.""" self.hass.services.call('zwave', 'remove_failed_node', { const.ATTR_NODE_ID: 12, }) self.hass.block_till_done() remove_failed_node = self.zwave_network.controller.remove_failed_node assert remove_failed_node.called assert len(remove_failed_node.mock_calls) == 1 assert remove_failed_node.mock_calls[0][1][0] == 12 def test_replace_failed_node(self): """Test zwave replace_failed_node service.""" self.hass.services.call('zwave', 'replace_failed_node', { const.ATTR_NODE_ID: 13, }) self.hass.block_till_done() replace_failed_node = self.zwave_network.controller.replace_failed_node assert replace_failed_node.called assert len(replace_failed_node.mock_calls) == 1 assert replace_failed_node.mock_calls[0][1][0] == 13 def test_set_config_parameter(self): """Test zwave set_config_parameter service.""" value_byte = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BYTE, ) value_list = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['item1', 'item2', 'item3'], ) value_button = MockValue( index=14, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BUTTON, ) value_list_int = MockValue( index=15, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['1', '2', '3'], ) value_bool = MockValue( index=16, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BOOL, ) node = MockNode(node_id=14) node.get_values.return_value = { 12: value_byte, 13: value_list, 14: value_button, 15: value_list_int, 16: value_bool } self.zwave_network.nodes = {14: node} # Byte self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 12, const.ATTR_CONFIG_VALUE: 7, }) self.hass.block_till_done() assert value_byte.data == 7 # List self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, const.ATTR_CONFIG_VALUE: 'item3', }) self.hass.block_till_done() assert value_list.data == 'item3' # Button self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 14, const.ATTR_CONFIG_VALUE: True, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called assert self.zwave_network.manager.releaseButton.called # List of Ints self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 15, const.ATTR_CONFIG_VALUE: 3, }) self.hass.block_till_done() assert value_list_int.data == '3' # Boolean Truthy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'True', }) self.hass.block_till_done() assert value_bool.data == 1 # Boolean Falsy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'False', }) self.hass.block_till_done() assert value_bool.data == 0 # Different Parameter Size self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 19, const.ATTR_CONFIG_VALUE: 0x01020304, const.ATTR_CONFIG_SIZE: 4 }) self.hass.block_till_done() assert node.set_config_param.called assert len(node.set_config_param.mock_calls) == 1 assert node.set_config_param.mock_calls[0][1][0] == 19 assert node.set_config_param.mock_calls[0][1][1] == 0x01020304 assert node.set_config_param.mock_calls[0][1][2] == 4 node.set_config_param.reset_mock() def test_print_config_parameter(self): """Test zwave print_config_parameter service.""" value1 = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, data=1234, ) value2 = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, data=2345, ) node = MockNode(node_id=14) node.values = {12: value1, 13: value2} self.zwave_network.nodes = {14: node} with patch.object(zwave, '_LOGGER') as mock_logger: self.hass.services.call('zwave', 'print_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, }) self.hass.block_till_done() assert mock_logger.info.called assert len(mock_logger.info.mock_calls) == 1 assert mock_logger.info.mock_calls[0][1][1] == 13 assert mock_logger.info.mock_calls[0][1][2] == 14 assert mock_logger.info.mock_calls[0][1][3] == 2345 def test_print_node(self): """Test zwave print_node_parameter service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} with self.assertLogs(level='DEBUG') as mock_logger: self.hass.services.call('zwave', 'print_node', { const.ATTR_NODE_ID: 14 }) self.hass.block_till_done() assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 15, }) self.hass.block_till_done() assert value.data == 15 node.can_wake_up_value = False self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 20, }) self.hass.block_till_done() assert value.data == 15 def test_reset_node_meters(self): """Test zwave reset_node_meters service.""" value = MockValue( instance=1, index=8, data=99.5, command_class=const.COMMAND_CLASS_METER, ) reset_value = MockValue( instance=1, index=33, command_class=const.COMMAND_CLASS_METER, ) node = MockNode(node_id=14) node.values = {8: value, 33: reset_value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, const.ATTR_INSTANCE: 2, }) self.hass.block_till_done() assert not self.zwave_network.manager.pressButton.called assert not self.zwave_network.manager.releaseButton.called self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called value_id, = self.zwave_network.manager.pressButton.mock_calls.pop(0)[1] assert value_id == reset_value.value_id assert self.zwave_network.manager.releaseButton.called value_id, = ( self.zwave_network.manager.releaseButton.mock_calls.pop(0)[1]) assert value_id == reset_value.value_id def test_add_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'add', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.add_association.called assert len(group.add_association.mock_calls) == 1 assert group.add_association.mock_calls[0][1][0] == 24 assert group.add_association.mock_calls[0][1][1] == 5 def test_remove_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'remove', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.remove_association.called assert len(group.remove_association.mock_calls) == 1 assert group.remove_association.mock_calls[0][1][0] == 24 assert group.remove_association.mock_calls[0][1][1] == 5 def test_refresh_entity(self): """Test zwave refresh_entity service.""" node = MockNode() value = MockValue(data=False, node=node, command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50, node=node, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = get_device(node=node, values=values, node_config={}) device.hass = self.hass device.entity_id = 'binary_sensor.mock_entity_id' self.hass.add_job(device.async_added_to_hass()) self.hass.block_till_done() self.hass.services.call('zwave', 'refresh_entity', { ATTR_ENTITY_ID: 'binary_sensor.mock_entity_id', }) self.hass.block_till_done() assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 assert sorted([node.refresh_value.mock_calls[0][1][0], node.refresh_value.mock_calls[1][1][0]]) == \ sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert node.refresh_info.called assert len(node.refresh_info.mock_calls) == 1 def test_set_node_value(self): """Test zwave set_node_value service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=4 ) node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR]) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12, const.ATTR_CONFIG_VALUE: 2, }) self.hass.block_till_done() assert self.zwave_network.nodes[14].values[12].data == 2 def test_refresh_node_value(self): """Test zwave refresh_node_value service.""" node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR], network=self.zwave_network) value = MockValue( node=node, index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=2 ) value.refresh = MagicMock() node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12 }) self.hass.block_till_done() assert value.refresh.called def test_heal_node(self): """Test zwave heal_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'heal_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.heal.called assert len(node.heal.mock_calls) == 1 def test_test_node(self): """Test the zwave test_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'test_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.test.called assert len(node.test.mock_calls) == 1
jabesq/home-assistant
tests/components/zwave/test_init.py
homeassistant/components/mqtt/light/schema_template.py
"""Permission constants for the websocket API. Separate file to avoid circular imports. """ from homeassistant.const import ( EVENT_COMPONENT_LOADED, EVENT_SERVICE_REGISTERED, EVENT_SERVICE_REMOVED, EVENT_STATE_CHANGED, EVENT_THEMES_UPDATED) from homeassistant.components.persistent_notification import ( EVENT_PERSISTENT_NOTIFICATIONS_UPDATED) from homeassistant.components.lovelace import EVENT_LOVELACE_UPDATED from homeassistant.helpers.area_registry import EVENT_AREA_REGISTRY_UPDATED from homeassistant.helpers.device_registry import EVENT_DEVICE_REGISTRY_UPDATED from homeassistant.helpers.entity_registry import EVENT_ENTITY_REGISTRY_UPDATED from homeassistant.components.frontend import EVENT_PANELS_UPDATED # These are events that do not contain any sensitive data # Except for state_changed, which is handled accordingly. SUBSCRIBE_WHITELIST = { EVENT_COMPONENT_LOADED, EVENT_PANELS_UPDATED, EVENT_PERSISTENT_NOTIFICATIONS_UPDATED, EVENT_SERVICE_REGISTERED, EVENT_SERVICE_REMOVED, EVENT_STATE_CHANGED, EVENT_THEMES_UPDATED, EVENT_AREA_REGISTRY_UPDATED, EVENT_DEVICE_REGISTRY_UPDATED, EVENT_ENTITY_REGISTRY_UPDATED, EVENT_LOVELACE_UPDATED, }
"""Tests for the Z-Wave init.""" import asyncio from collections import OrderedDict from datetime import datetime import unittest from unittest.mock import MagicMock, patch import pytest from pytz import utc import voluptuous as vol from homeassistant.bootstrap import async_setup_component from homeassistant.components import zwave from homeassistant.components.zwave import ( CONF_DEVICE_CONFIG_GLOB, CONFIG_SCHEMA, DATA_NETWORK, const) from homeassistant.components.zwave.binary_sensor import get_device from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.device_registry import ( async_get_registry as get_dev_reg) from homeassistant.setup import setup_component from tests.common import ( async_fire_time_changed, get_test_home_assistant, mock_coro, mock_registry) from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue async def test_valid_device_config(hass, mock_openzwave): """Test valid device config.""" device_config = { 'light.kitchen': { 'ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert result async def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = { 'light.kitchen': { 'some_ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert not result def test_config_access_error(): """Test threading error accessing config values.""" node = MagicMock() def side_effect(): raise RuntimeError node.values.values.side_effect = side_effect result = zwave.get_config_value(node, 1) assert result is None async def test_network_options(hass, mock_openzwave): """Test network options.""" result = await async_setup_component(hass, 'zwave', { 'zwave': { 'usb_path': 'mock_usb_path', 'config_path': 'mock_config_path', }}) await hass.async_block_till_done() assert result network = hass.data[zwave.DATA_NETWORK] assert network.options.device == 'mock_usb_path' assert network.options.config_path == 'mock_config_path' async def test_network_key_validation(hass, mock_openzwave): """Test network key validation.""" test_values = [ ('0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,' '0x0E,0x0F,0x10'), ] for value in test_values: result = zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) assert result['zwave']['network_key'] == value async def test_erronous_network_key_fails_validation(hass, mock_openzwave): """Test failing erronous network key validation.""" test_values = [ ('0x 01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0X01,0X02,0X03,0X04,0X05,0X06,0X07,0X08,0X09,0X0A,0X0B,0X0C,0X0D,' '0X0E,0X0F,0X10'), 'invalid', '1234567', 1234567 ] for value in test_values: with pytest.raises(vol.Invalid): zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) async def test_auto_heal_midnight(hass, mock_openzwave): """Test network auto-heal at midnight.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': True, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert network.heal.called assert len(network.heal.mock_calls) == 1 async def test_auto_heal_disabled(hass, mock_openzwave): """Test network auto-heal disabled.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': False, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert not network.heal.called async def test_setup_platform(hass, mock_openzwave): """Test invalid device config.""" mock_device = MagicMock() hass.data[DATA_NETWORK] = MagicMock() hass.data[zwave.DATA_DEVICES] = {456: mock_device} async_add_entities = MagicMock() result = await zwave.async_setup_platform( hass, None, async_add_entities, None) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 123}) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 456}) assert result assert async_add_entities.called assert len(async_add_entities.mock_calls) == 1 assert async_add_entities.mock_calls[0][1][0] == [mock_device] async def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): """Test device entity base class.""" node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.value_added() device.update_properties() await hass.async_block_till_done() assert not device.should_poll assert device.unique_id == "10-11" assert device.name == 'Mock Node Sensor' assert device.device_state_attributes[zwave.ATTR_POWER] == 50.123 async def test_node_removed(hass, mock_openzwave): """Test node removed in base class.""" # Create a mock node & node entity node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.entity_id = 'zwave.mock_node' device.value_added() device.update_properties() await hass.async_block_till_done() # Save it to the entity registry registry = mock_registry(hass) registry.async_get_or_create('zwave', 'zwave', device.unique_id) device.entity_id = registry.async_get_entity_id( 'zwave', 'zwave', device.unique_id) # Create dummy entity registry entries for other integrations hue_entity = registry.async_get_or_create('light', 'hue', 1234) zha_entity = registry.async_get_or_create('sensor', 'zha', 5678) # Verify our Z-Wave entity is registered assert registry.async_is_registered(device.entity_id) # Remove it entity_id = device.entity_id await device.node_removed() # Verify registry entry for our Z-Wave node is gone assert not registry.async_is_registered(entity_id) # Verify registry entries for our other entities remain assert registry.async_is_registered(hue_entity.entity_id) assert registry.async_is_registered(zha_entity.entity_id) async def test_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node').state == 'unknown' async def test_unparsed_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode( node_id=14, manufacturer_name=None, name=None, is_ready=False) sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert len(sleeps) == const.NODE_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1:] == \ (14, const.NODE_READY_WAIT_SECS) assert hass.states.get('zwave.unknown_node_14').state == 'unknown' async def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': { 'device_config': { 'zwave.mock_node': { 'ignored': True, }}}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None async def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' async def test_value_entities(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = {} def mock_connect(receiver, signal, *args, **kwargs): mock_receivers[signal] = receiver with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert mock_receivers hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_ALL_NODES_QUERIED]) node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) zwave_network.nodes = {node.node_id: node} value = MockValue( data=False, node=node, index=12, instance=1, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values = {'primary': value, value.value_id: value} value2 = MockValue( data=False, node=node, index=12, instance=2, label="Mock Value B", command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values[value2.value_id] = value2 hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_NODE_ADDED], node) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value2) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' assert hass.states.get( 'binary_sensor.mock_node_mock_value_b').state == 'off' ent_reg = await async_get_registry(hass) dev_reg = await get_dev_reg(hass) entry = ent_reg.async_get('zwave.mock_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) node_dev_id = entry.device_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) assert entry.name is None assert entry.device_id == node_dev_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value2.object_id) assert entry.name is None assert entry.device_id != node_dev_id device_id_b = entry.device_id device = dev_reg.async_get(node_dev_id) assert device is not None assert device.name == node.name old_device = device device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming without updating await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_NAME: "Demo Node", }) await hass.async_block_till_done() assert node.name == "Demo Node" entry = ent_reg.async_get('zwave.mock_node') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Node", }) await hass.async_block_till_done() assert node.name == "New Node" entry = ent_reg.async_get('zwave.new_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) entry = ent_reg.async_get('binary_sensor.new_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) await hass.services.async_call('zwave', 'rename_value', { const.ATTR_NODE_ID: node.node_id, const.ATTR_VALUE_ID: value.object_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Label", }) await hass.async_block_till_done() entry = ent_reg.async_get('binary_sensor.new_node_new_label') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) async def test_value_discovery_existing_entity(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_THERMOSTAT) setpoint = MockValue( data=22.0, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, setpoint) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] is None def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): temperature = MockValue( data=23.5, node=node, index=1, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, temperature) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] == 23.5 async def test_power_schemes(hass, mock_openzwave): """Test power attribute.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SWITCH_BINARY) switch = MockValue( data=True, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SWITCH_BINARY, genre=const.GENRE_USER, type=const.TYPE_BOOL) hass.async_add_job(mock_receivers[0], node, switch) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').state == 'on' assert 'power_consumption' not in hass.states.get( 'switch.mock_node_mock_value').attributes def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): power = MockValue( data=23.5, node=node, index=const.INDEX_SENSOR_MULTILEVEL_POWER, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL) hass.async_add_job(mock_receivers[0], node, power) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').attributes[ 'power_consumption'] == 23.5 async def test_network_ready(hass, mock_openzwave): """Test Node network ready event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete_some_dead(hass, mock_openzwave): """Test Node network complete some dead event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE_SOME_DEAD, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 class TestZWaveDeviceEntityValues(unittest.TestCase): """Tests for the ZWaveDeviceEntityValues helper.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() self.registry = mock_registry(self.hass) setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.node = MockNode() self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: ['mock_primary_class'], }, 'secondary': { const.DISC_COMMAND_CLASS: ['mock_secondary_class'], }, 'optional': { const.DISC_COMMAND_CLASS: ['mock_optional_class'], const.DISC_OPTIONAL: True, }}} self.primary = MockValue( command_class='mock_primary_class', node=self.node, value_id=1000) self.secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.duplicate_secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.optional = MockValue( command_class='mock_optional_class', node=self.node) self.no_match_value = MockValue( command_class='mock_bad_class', node=self.node) self.entity_id = 'mock_component.mock_node_mock_value' self.zwave_config = {'zwave': {}} self.device_config = {self.entity_id: {}} def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) assert values.primary is self.primary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) self.hass.block_till_done() assert values.secondary is self.secondary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config discovery.async_load_platform.reset_mock() values.check_value(self.optional) values.check_value(self.duplicate_secondary) values.check_value(self.no_match_value) self.hass.block_till_done() assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called assert len(values._entity.value_added.mock_calls) == 1 assert values._entity.value_changed.called assert len(values._entity.value_changed.mock_calls) == 1 @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, self.optional.value_id: self.optional, self.no_match_value.value_id: self.no_match_value, } values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert values.primary is self.primary assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config assert not self.primary.enable_poll.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_node_schema_mismatch(self, discovery, import_module): """Test node schema mismatch.""" self.node.generic = 'no_match' self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.mock_schema[const.DISC_GENERIC_DEVICE_CLASS] = ['generic_match'] values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.manufacturer_id = '010f' self.node.product_type = '0b00' self.primary.command_class = const.COMMAND_CLASS_SENSOR_ALARM self.entity_id = 'binary_sensor.mock_node_mock_value' self.device_config = {self.entity_id: {}} self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} with patch.object(zwave, 'async_dispatcher_send') as \ mock_dispatch_send: values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert mock_dispatch_send.called assert len(mock_dispatch_send.mock_calls) == 1 args = mock_dispatch_send.mock_calls[0][1] assert args[1] == 'zwave_new_binary_sensor' @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_ignore(self, discovery, import_module): """Test ignore workaround.""" self.node.manufacturer_id = '010f' self.node.product_type = '0301' self.primary.command_class = const.COMMAND_CLASS_SWITCH_BINARY self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore(self, discovery, import_module): """Test ignore config.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_IGNORED: True }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore_with_registry(self, discovery, import_module): """Test ignore config. The case when the device is in entity registry. """ self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {'mock_component.registry_id': { zwave.CONF_IGNORED: True }} with patch.object(self.registry, 'async_schedule_save'): self.registry.async_get_or_create( 'mock_component', zwave.DOMAIN, '567-1000', suggested_object_id='registry_id') zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_platform_ignore(self, discovery, import_module): """Test platform ignore device.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } platform = MagicMock() import_module.return_value = platform platform.get_device.return_value = None zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_config_polling_intensity(self, discovery, import_module): """Test polling intensity.""" mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_POLLING_INTENSITY: 123, }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert discovery.async_load_platform.called assert self.primary.enable_poll.called assert len(self.primary.enable_poll.mock_calls) == 1 assert self.primary.enable_poll.mock_calls[0][1][0] == 123 class TestZwave(unittest.TestCase): """Test zwave init.""" def test_device_config_glob_is_ordered(self): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): """Tests for zwave services.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() # Initialize zwave setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.zwave_network = self.hass.data[DATA_NETWORK] self.zwave_network.state = MockNetwork.STATE_READY self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.block_till_done() def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() self.hass.stop() def test_add_node(self): """Test zwave add_node service.""" self.hass.services.call('zwave', 'add_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller .add_node.mock_calls) == 1 assert len(self.zwave_network.controller .add_node.mock_calls[0][1]) == 0 def test_add_node_secure(self): """Test zwave add_node_secure service.""" self.hass.services.call('zwave', 'add_node_secure', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller.add_node.mock_calls) == 1 assert (self.zwave_network.controller .add_node.mock_calls[0][1][0] is True) def test_remove_node(self): """Test zwave remove_node service.""" self.hass.services.call('zwave', 'remove_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.remove_node.called assert len(self.zwave_network.controller.remove_node.mock_calls) == 1 def test_cancel_command(self): """Test zwave cancel_command service.""" self.hass.services.call('zwave', 'cancel_command', {}) self.hass.block_till_done() assert self.zwave_network.controller.cancel_command.called assert len(self.zwave_network.controller .cancel_command.mock_calls) == 1 def test_heal_network(self): """Test zwave heal_network service.""" self.hass.services.call('zwave', 'heal_network', {}) self.hass.block_till_done() assert self.zwave_network.heal.called assert len(self.zwave_network.heal.mock_calls) == 1 def test_soft_reset(self): """Test zwave soft_reset service.""" self.hass.services.call('zwave', 'soft_reset', {}) self.hass.block_till_done() assert self.zwave_network.controller.soft_reset.called assert len(self.zwave_network.controller.soft_reset.mock_calls) == 1 def test_test_network(self): """Test zwave test_network service.""" self.hass.services.call('zwave', 'test_network', {}) self.hass.block_till_done() assert self.zwave_network.test.called assert len(self.zwave_network.test.mock_calls) == 1 def test_stop_network(self): """Test zwave stop_network service.""" with patch.object(self.hass.bus, 'fire') as mock_fire: self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() assert self.zwave_network.stop.called assert len(self.zwave_network.stop.mock_calls) == 1 assert mock_fire.called assert len(mock_fire.mock_calls) == 1 assert mock_fire.mock_calls[0][1][0] == const.EVENT_NETWORK_STOP def test_rename_node(self): """Test zwave rename_node service.""" self.zwave_network.nodes = {11: MagicMock()} self.hass.services.call('zwave', 'rename_node', { const.ATTR_NODE_ID: 11, const.ATTR_NAME: 'test_name', }) self.hass.block_till_done() assert self.zwave_network.nodes[11].name == 'test_name' def test_rename_value(self): """Test zwave rename_value service.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, label="Old Label") node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.label == "Old Label" self.hass.services.call('zwave', 'rename_value', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_NAME: "New Label", }) self.hass.block_till_done() assert value.label == "New Label" def test_set_poll_intensity_enable(self): """Test zwave set_poll_intensity service, successful set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 2 assert enable_poll.mock_calls[0][1][0] == 4 def test_set_poll_intensity_enable_failed(self): """Test zwave set_poll_intensity service, failed set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) value.enable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 1 def test_set_poll_intensity_disable(self): """Test zwave set_poll_intensity service, successful disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 2 def test_set_poll_intensity_disable_failed(self): """Test zwave set_poll_intensity service, failed disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) value.disable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 1 def test_remove_failed_node(self): """Test zwave remove_failed_node service.""" self.hass.services.call('zwave', 'remove_failed_node', { const.ATTR_NODE_ID: 12, }) self.hass.block_till_done() remove_failed_node = self.zwave_network.controller.remove_failed_node assert remove_failed_node.called assert len(remove_failed_node.mock_calls) == 1 assert remove_failed_node.mock_calls[0][1][0] == 12 def test_replace_failed_node(self): """Test zwave replace_failed_node service.""" self.hass.services.call('zwave', 'replace_failed_node', { const.ATTR_NODE_ID: 13, }) self.hass.block_till_done() replace_failed_node = self.zwave_network.controller.replace_failed_node assert replace_failed_node.called assert len(replace_failed_node.mock_calls) == 1 assert replace_failed_node.mock_calls[0][1][0] == 13 def test_set_config_parameter(self): """Test zwave set_config_parameter service.""" value_byte = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BYTE, ) value_list = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['item1', 'item2', 'item3'], ) value_button = MockValue( index=14, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BUTTON, ) value_list_int = MockValue( index=15, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['1', '2', '3'], ) value_bool = MockValue( index=16, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BOOL, ) node = MockNode(node_id=14) node.get_values.return_value = { 12: value_byte, 13: value_list, 14: value_button, 15: value_list_int, 16: value_bool } self.zwave_network.nodes = {14: node} # Byte self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 12, const.ATTR_CONFIG_VALUE: 7, }) self.hass.block_till_done() assert value_byte.data == 7 # List self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, const.ATTR_CONFIG_VALUE: 'item3', }) self.hass.block_till_done() assert value_list.data == 'item3' # Button self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 14, const.ATTR_CONFIG_VALUE: True, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called assert self.zwave_network.manager.releaseButton.called # List of Ints self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 15, const.ATTR_CONFIG_VALUE: 3, }) self.hass.block_till_done() assert value_list_int.data == '3' # Boolean Truthy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'True', }) self.hass.block_till_done() assert value_bool.data == 1 # Boolean Falsy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'False', }) self.hass.block_till_done() assert value_bool.data == 0 # Different Parameter Size self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 19, const.ATTR_CONFIG_VALUE: 0x01020304, const.ATTR_CONFIG_SIZE: 4 }) self.hass.block_till_done() assert node.set_config_param.called assert len(node.set_config_param.mock_calls) == 1 assert node.set_config_param.mock_calls[0][1][0] == 19 assert node.set_config_param.mock_calls[0][1][1] == 0x01020304 assert node.set_config_param.mock_calls[0][1][2] == 4 node.set_config_param.reset_mock() def test_print_config_parameter(self): """Test zwave print_config_parameter service.""" value1 = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, data=1234, ) value2 = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, data=2345, ) node = MockNode(node_id=14) node.values = {12: value1, 13: value2} self.zwave_network.nodes = {14: node} with patch.object(zwave, '_LOGGER') as mock_logger: self.hass.services.call('zwave', 'print_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, }) self.hass.block_till_done() assert mock_logger.info.called assert len(mock_logger.info.mock_calls) == 1 assert mock_logger.info.mock_calls[0][1][1] == 13 assert mock_logger.info.mock_calls[0][1][2] == 14 assert mock_logger.info.mock_calls[0][1][3] == 2345 def test_print_node(self): """Test zwave print_node_parameter service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} with self.assertLogs(level='DEBUG') as mock_logger: self.hass.services.call('zwave', 'print_node', { const.ATTR_NODE_ID: 14 }) self.hass.block_till_done() assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 15, }) self.hass.block_till_done() assert value.data == 15 node.can_wake_up_value = False self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 20, }) self.hass.block_till_done() assert value.data == 15 def test_reset_node_meters(self): """Test zwave reset_node_meters service.""" value = MockValue( instance=1, index=8, data=99.5, command_class=const.COMMAND_CLASS_METER, ) reset_value = MockValue( instance=1, index=33, command_class=const.COMMAND_CLASS_METER, ) node = MockNode(node_id=14) node.values = {8: value, 33: reset_value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, const.ATTR_INSTANCE: 2, }) self.hass.block_till_done() assert not self.zwave_network.manager.pressButton.called assert not self.zwave_network.manager.releaseButton.called self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called value_id, = self.zwave_network.manager.pressButton.mock_calls.pop(0)[1] assert value_id == reset_value.value_id assert self.zwave_network.manager.releaseButton.called value_id, = ( self.zwave_network.manager.releaseButton.mock_calls.pop(0)[1]) assert value_id == reset_value.value_id def test_add_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'add', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.add_association.called assert len(group.add_association.mock_calls) == 1 assert group.add_association.mock_calls[0][1][0] == 24 assert group.add_association.mock_calls[0][1][1] == 5 def test_remove_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'remove', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.remove_association.called assert len(group.remove_association.mock_calls) == 1 assert group.remove_association.mock_calls[0][1][0] == 24 assert group.remove_association.mock_calls[0][1][1] == 5 def test_refresh_entity(self): """Test zwave refresh_entity service.""" node = MockNode() value = MockValue(data=False, node=node, command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50, node=node, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = get_device(node=node, values=values, node_config={}) device.hass = self.hass device.entity_id = 'binary_sensor.mock_entity_id' self.hass.add_job(device.async_added_to_hass()) self.hass.block_till_done() self.hass.services.call('zwave', 'refresh_entity', { ATTR_ENTITY_ID: 'binary_sensor.mock_entity_id', }) self.hass.block_till_done() assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 assert sorted([node.refresh_value.mock_calls[0][1][0], node.refresh_value.mock_calls[1][1][0]]) == \ sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert node.refresh_info.called assert len(node.refresh_info.mock_calls) == 1 def test_set_node_value(self): """Test zwave set_node_value service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=4 ) node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR]) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12, const.ATTR_CONFIG_VALUE: 2, }) self.hass.block_till_done() assert self.zwave_network.nodes[14].values[12].data == 2 def test_refresh_node_value(self): """Test zwave refresh_node_value service.""" node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR], network=self.zwave_network) value = MockValue( node=node, index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=2 ) value.refresh = MagicMock() node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12 }) self.hass.block_till_done() assert value.refresh.called def test_heal_node(self): """Test zwave heal_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'heal_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.heal.called assert len(node.heal.mock_calls) == 1 def test_test_node(self): """Test the zwave test_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'test_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.test.called assert len(node.test.mock_calls) == 1
jabesq/home-assistant
tests/components/zwave/test_init.py
homeassistant/components/websocket_api/permissions.py
"""Support for Tellstick sensors.""" import logging from collections import namedtuple import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import TEMP_CELSIUS, CONF_ID, CONF_NAME from homeassistant.helpers.entity import Entity import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) DatatypeDescription = namedtuple('DatatypeDescription', ['name', 'unit']) CONF_DATATYPE_MASK = 'datatype_mask' CONF_ONLY_NAMED = 'only_named' CONF_TEMPERATURE_SCALE = 'temperature_scale' DEFAULT_DATATYPE_MASK = 127 DEFAULT_TEMPERATURE_SCALE = TEMP_CELSIUS PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_TEMPERATURE_SCALE, default=DEFAULT_TEMPERATURE_SCALE): cv.string, vol.Optional(CONF_DATATYPE_MASK, default=DEFAULT_DATATYPE_MASK): cv.positive_int, vol.Optional(CONF_ONLY_NAMED, default=[]): vol.All(cv.ensure_list, [vol.Schema({ vol.Required(CONF_ID): cv.positive_int, vol.Required(CONF_NAME): cv.string, })]) }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Tellstick sensors.""" from tellcore import telldus import tellcore.constants as tellcore_constants sensor_value_descriptions = { tellcore_constants.TELLSTICK_TEMPERATURE: DatatypeDescription('temperature', config.get(CONF_TEMPERATURE_SCALE)), tellcore_constants.TELLSTICK_HUMIDITY: DatatypeDescription('humidity', '%'), tellcore_constants.TELLSTICK_RAINRATE: DatatypeDescription('rain rate', ''), tellcore_constants.TELLSTICK_RAINTOTAL: DatatypeDescription('rain total', ''), tellcore_constants.TELLSTICK_WINDDIRECTION: DatatypeDescription('wind direction', ''), tellcore_constants.TELLSTICK_WINDAVERAGE: DatatypeDescription('wind average', ''), tellcore_constants.TELLSTICK_WINDGUST: DatatypeDescription('wind gust', '') } try: tellcore_lib = telldus.TelldusCore() except OSError: _LOGGER.exception('Could not initialize Tellstick') return sensors = [] datatype_mask = config.get(CONF_DATATYPE_MASK) if config[CONF_ONLY_NAMED]: named_sensors = { named_sensor[CONF_ID]: named_sensor[CONF_NAME] for named_sensor in config[CONF_ONLY_NAMED]} for tellcore_sensor in tellcore_lib.sensors(): if not config[CONF_ONLY_NAMED]: sensor_name = str(tellcore_sensor.id) else: if tellcore_sensor.id not in named_sensors: continue sensor_name = named_sensors[tellcore_sensor.id] for datatype in sensor_value_descriptions: if datatype & datatype_mask and \ tellcore_sensor.has_value(datatype): sensor_info = sensor_value_descriptions[datatype] sensors.append(TellstickSensor( sensor_name, tellcore_sensor, datatype, sensor_info)) add_entities(sensors) class TellstickSensor(Entity): """Representation of a Tellstick sensor.""" def __init__(self, name, tellcore_sensor, datatype, sensor_info): """Initialize the sensor.""" self._datatype = datatype self._tellcore_sensor = tellcore_sensor self._unit_of_measurement = sensor_info.unit or None self._value = None self._name = '{} {}'.format(name, sensor_info.name) @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._value @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return self._unit_of_measurement def update(self): """Update tellstick sensor.""" self._value = self._tellcore_sensor.value(self._datatype).value
"""Tests for the Z-Wave init.""" import asyncio from collections import OrderedDict from datetime import datetime import unittest from unittest.mock import MagicMock, patch import pytest from pytz import utc import voluptuous as vol from homeassistant.bootstrap import async_setup_component from homeassistant.components import zwave from homeassistant.components.zwave import ( CONF_DEVICE_CONFIG_GLOB, CONFIG_SCHEMA, DATA_NETWORK, const) from homeassistant.components.zwave.binary_sensor import get_device from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.device_registry import ( async_get_registry as get_dev_reg) from homeassistant.setup import setup_component from tests.common import ( async_fire_time_changed, get_test_home_assistant, mock_coro, mock_registry) from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue async def test_valid_device_config(hass, mock_openzwave): """Test valid device config.""" device_config = { 'light.kitchen': { 'ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert result async def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = { 'light.kitchen': { 'some_ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert not result def test_config_access_error(): """Test threading error accessing config values.""" node = MagicMock() def side_effect(): raise RuntimeError node.values.values.side_effect = side_effect result = zwave.get_config_value(node, 1) assert result is None async def test_network_options(hass, mock_openzwave): """Test network options.""" result = await async_setup_component(hass, 'zwave', { 'zwave': { 'usb_path': 'mock_usb_path', 'config_path': 'mock_config_path', }}) await hass.async_block_till_done() assert result network = hass.data[zwave.DATA_NETWORK] assert network.options.device == 'mock_usb_path' assert network.options.config_path == 'mock_config_path' async def test_network_key_validation(hass, mock_openzwave): """Test network key validation.""" test_values = [ ('0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,' '0x0E,0x0F,0x10'), ] for value in test_values: result = zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) assert result['zwave']['network_key'] == value async def test_erronous_network_key_fails_validation(hass, mock_openzwave): """Test failing erronous network key validation.""" test_values = [ ('0x 01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0X01,0X02,0X03,0X04,0X05,0X06,0X07,0X08,0X09,0X0A,0X0B,0X0C,0X0D,' '0X0E,0X0F,0X10'), 'invalid', '1234567', 1234567 ] for value in test_values: with pytest.raises(vol.Invalid): zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) async def test_auto_heal_midnight(hass, mock_openzwave): """Test network auto-heal at midnight.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': True, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert network.heal.called assert len(network.heal.mock_calls) == 1 async def test_auto_heal_disabled(hass, mock_openzwave): """Test network auto-heal disabled.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': False, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert not network.heal.called async def test_setup_platform(hass, mock_openzwave): """Test invalid device config.""" mock_device = MagicMock() hass.data[DATA_NETWORK] = MagicMock() hass.data[zwave.DATA_DEVICES] = {456: mock_device} async_add_entities = MagicMock() result = await zwave.async_setup_platform( hass, None, async_add_entities, None) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 123}) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 456}) assert result assert async_add_entities.called assert len(async_add_entities.mock_calls) == 1 assert async_add_entities.mock_calls[0][1][0] == [mock_device] async def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): """Test device entity base class.""" node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.value_added() device.update_properties() await hass.async_block_till_done() assert not device.should_poll assert device.unique_id == "10-11" assert device.name == 'Mock Node Sensor' assert device.device_state_attributes[zwave.ATTR_POWER] == 50.123 async def test_node_removed(hass, mock_openzwave): """Test node removed in base class.""" # Create a mock node & node entity node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.entity_id = 'zwave.mock_node' device.value_added() device.update_properties() await hass.async_block_till_done() # Save it to the entity registry registry = mock_registry(hass) registry.async_get_or_create('zwave', 'zwave', device.unique_id) device.entity_id = registry.async_get_entity_id( 'zwave', 'zwave', device.unique_id) # Create dummy entity registry entries for other integrations hue_entity = registry.async_get_or_create('light', 'hue', 1234) zha_entity = registry.async_get_or_create('sensor', 'zha', 5678) # Verify our Z-Wave entity is registered assert registry.async_is_registered(device.entity_id) # Remove it entity_id = device.entity_id await device.node_removed() # Verify registry entry for our Z-Wave node is gone assert not registry.async_is_registered(entity_id) # Verify registry entries for our other entities remain assert registry.async_is_registered(hue_entity.entity_id) assert registry.async_is_registered(zha_entity.entity_id) async def test_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node').state == 'unknown' async def test_unparsed_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode( node_id=14, manufacturer_name=None, name=None, is_ready=False) sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert len(sleeps) == const.NODE_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1:] == \ (14, const.NODE_READY_WAIT_SECS) assert hass.states.get('zwave.unknown_node_14').state == 'unknown' async def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': { 'device_config': { 'zwave.mock_node': { 'ignored': True, }}}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None async def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' async def test_value_entities(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = {} def mock_connect(receiver, signal, *args, **kwargs): mock_receivers[signal] = receiver with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert mock_receivers hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_ALL_NODES_QUERIED]) node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) zwave_network.nodes = {node.node_id: node} value = MockValue( data=False, node=node, index=12, instance=1, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values = {'primary': value, value.value_id: value} value2 = MockValue( data=False, node=node, index=12, instance=2, label="Mock Value B", command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values[value2.value_id] = value2 hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_NODE_ADDED], node) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value2) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' assert hass.states.get( 'binary_sensor.mock_node_mock_value_b').state == 'off' ent_reg = await async_get_registry(hass) dev_reg = await get_dev_reg(hass) entry = ent_reg.async_get('zwave.mock_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) node_dev_id = entry.device_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) assert entry.name is None assert entry.device_id == node_dev_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value2.object_id) assert entry.name is None assert entry.device_id != node_dev_id device_id_b = entry.device_id device = dev_reg.async_get(node_dev_id) assert device is not None assert device.name == node.name old_device = device device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming without updating await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_NAME: "Demo Node", }) await hass.async_block_till_done() assert node.name == "Demo Node" entry = ent_reg.async_get('zwave.mock_node') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Node", }) await hass.async_block_till_done() assert node.name == "New Node" entry = ent_reg.async_get('zwave.new_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) entry = ent_reg.async_get('binary_sensor.new_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) await hass.services.async_call('zwave', 'rename_value', { const.ATTR_NODE_ID: node.node_id, const.ATTR_VALUE_ID: value.object_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Label", }) await hass.async_block_till_done() entry = ent_reg.async_get('binary_sensor.new_node_new_label') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) async def test_value_discovery_existing_entity(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_THERMOSTAT) setpoint = MockValue( data=22.0, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, setpoint) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] is None def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): temperature = MockValue( data=23.5, node=node, index=1, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, temperature) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] == 23.5 async def test_power_schemes(hass, mock_openzwave): """Test power attribute.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SWITCH_BINARY) switch = MockValue( data=True, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SWITCH_BINARY, genre=const.GENRE_USER, type=const.TYPE_BOOL) hass.async_add_job(mock_receivers[0], node, switch) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').state == 'on' assert 'power_consumption' not in hass.states.get( 'switch.mock_node_mock_value').attributes def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): power = MockValue( data=23.5, node=node, index=const.INDEX_SENSOR_MULTILEVEL_POWER, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL) hass.async_add_job(mock_receivers[0], node, power) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').attributes[ 'power_consumption'] == 23.5 async def test_network_ready(hass, mock_openzwave): """Test Node network ready event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete_some_dead(hass, mock_openzwave): """Test Node network complete some dead event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE_SOME_DEAD, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 class TestZWaveDeviceEntityValues(unittest.TestCase): """Tests for the ZWaveDeviceEntityValues helper.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() self.registry = mock_registry(self.hass) setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.node = MockNode() self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: ['mock_primary_class'], }, 'secondary': { const.DISC_COMMAND_CLASS: ['mock_secondary_class'], }, 'optional': { const.DISC_COMMAND_CLASS: ['mock_optional_class'], const.DISC_OPTIONAL: True, }}} self.primary = MockValue( command_class='mock_primary_class', node=self.node, value_id=1000) self.secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.duplicate_secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.optional = MockValue( command_class='mock_optional_class', node=self.node) self.no_match_value = MockValue( command_class='mock_bad_class', node=self.node) self.entity_id = 'mock_component.mock_node_mock_value' self.zwave_config = {'zwave': {}} self.device_config = {self.entity_id: {}} def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) assert values.primary is self.primary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) self.hass.block_till_done() assert values.secondary is self.secondary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config discovery.async_load_platform.reset_mock() values.check_value(self.optional) values.check_value(self.duplicate_secondary) values.check_value(self.no_match_value) self.hass.block_till_done() assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called assert len(values._entity.value_added.mock_calls) == 1 assert values._entity.value_changed.called assert len(values._entity.value_changed.mock_calls) == 1 @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, self.optional.value_id: self.optional, self.no_match_value.value_id: self.no_match_value, } values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert values.primary is self.primary assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config assert not self.primary.enable_poll.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_node_schema_mismatch(self, discovery, import_module): """Test node schema mismatch.""" self.node.generic = 'no_match' self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.mock_schema[const.DISC_GENERIC_DEVICE_CLASS] = ['generic_match'] values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.manufacturer_id = '010f' self.node.product_type = '0b00' self.primary.command_class = const.COMMAND_CLASS_SENSOR_ALARM self.entity_id = 'binary_sensor.mock_node_mock_value' self.device_config = {self.entity_id: {}} self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} with patch.object(zwave, 'async_dispatcher_send') as \ mock_dispatch_send: values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert mock_dispatch_send.called assert len(mock_dispatch_send.mock_calls) == 1 args = mock_dispatch_send.mock_calls[0][1] assert args[1] == 'zwave_new_binary_sensor' @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_ignore(self, discovery, import_module): """Test ignore workaround.""" self.node.manufacturer_id = '010f' self.node.product_type = '0301' self.primary.command_class = const.COMMAND_CLASS_SWITCH_BINARY self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore(self, discovery, import_module): """Test ignore config.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_IGNORED: True }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore_with_registry(self, discovery, import_module): """Test ignore config. The case when the device is in entity registry. """ self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {'mock_component.registry_id': { zwave.CONF_IGNORED: True }} with patch.object(self.registry, 'async_schedule_save'): self.registry.async_get_or_create( 'mock_component', zwave.DOMAIN, '567-1000', suggested_object_id='registry_id') zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_platform_ignore(self, discovery, import_module): """Test platform ignore device.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } platform = MagicMock() import_module.return_value = platform platform.get_device.return_value = None zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_config_polling_intensity(self, discovery, import_module): """Test polling intensity.""" mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_POLLING_INTENSITY: 123, }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert discovery.async_load_platform.called assert self.primary.enable_poll.called assert len(self.primary.enable_poll.mock_calls) == 1 assert self.primary.enable_poll.mock_calls[0][1][0] == 123 class TestZwave(unittest.TestCase): """Test zwave init.""" def test_device_config_glob_is_ordered(self): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): """Tests for zwave services.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() # Initialize zwave setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.zwave_network = self.hass.data[DATA_NETWORK] self.zwave_network.state = MockNetwork.STATE_READY self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.block_till_done() def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() self.hass.stop() def test_add_node(self): """Test zwave add_node service.""" self.hass.services.call('zwave', 'add_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller .add_node.mock_calls) == 1 assert len(self.zwave_network.controller .add_node.mock_calls[0][1]) == 0 def test_add_node_secure(self): """Test zwave add_node_secure service.""" self.hass.services.call('zwave', 'add_node_secure', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller.add_node.mock_calls) == 1 assert (self.zwave_network.controller .add_node.mock_calls[0][1][0] is True) def test_remove_node(self): """Test zwave remove_node service.""" self.hass.services.call('zwave', 'remove_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.remove_node.called assert len(self.zwave_network.controller.remove_node.mock_calls) == 1 def test_cancel_command(self): """Test zwave cancel_command service.""" self.hass.services.call('zwave', 'cancel_command', {}) self.hass.block_till_done() assert self.zwave_network.controller.cancel_command.called assert len(self.zwave_network.controller .cancel_command.mock_calls) == 1 def test_heal_network(self): """Test zwave heal_network service.""" self.hass.services.call('zwave', 'heal_network', {}) self.hass.block_till_done() assert self.zwave_network.heal.called assert len(self.zwave_network.heal.mock_calls) == 1 def test_soft_reset(self): """Test zwave soft_reset service.""" self.hass.services.call('zwave', 'soft_reset', {}) self.hass.block_till_done() assert self.zwave_network.controller.soft_reset.called assert len(self.zwave_network.controller.soft_reset.mock_calls) == 1 def test_test_network(self): """Test zwave test_network service.""" self.hass.services.call('zwave', 'test_network', {}) self.hass.block_till_done() assert self.zwave_network.test.called assert len(self.zwave_network.test.mock_calls) == 1 def test_stop_network(self): """Test zwave stop_network service.""" with patch.object(self.hass.bus, 'fire') as mock_fire: self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() assert self.zwave_network.stop.called assert len(self.zwave_network.stop.mock_calls) == 1 assert mock_fire.called assert len(mock_fire.mock_calls) == 1 assert mock_fire.mock_calls[0][1][0] == const.EVENT_NETWORK_STOP def test_rename_node(self): """Test zwave rename_node service.""" self.zwave_network.nodes = {11: MagicMock()} self.hass.services.call('zwave', 'rename_node', { const.ATTR_NODE_ID: 11, const.ATTR_NAME: 'test_name', }) self.hass.block_till_done() assert self.zwave_network.nodes[11].name == 'test_name' def test_rename_value(self): """Test zwave rename_value service.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, label="Old Label") node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.label == "Old Label" self.hass.services.call('zwave', 'rename_value', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_NAME: "New Label", }) self.hass.block_till_done() assert value.label == "New Label" def test_set_poll_intensity_enable(self): """Test zwave set_poll_intensity service, successful set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 2 assert enable_poll.mock_calls[0][1][0] == 4 def test_set_poll_intensity_enable_failed(self): """Test zwave set_poll_intensity service, failed set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) value.enable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 1 def test_set_poll_intensity_disable(self): """Test zwave set_poll_intensity service, successful disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 2 def test_set_poll_intensity_disable_failed(self): """Test zwave set_poll_intensity service, failed disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) value.disable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 1 def test_remove_failed_node(self): """Test zwave remove_failed_node service.""" self.hass.services.call('zwave', 'remove_failed_node', { const.ATTR_NODE_ID: 12, }) self.hass.block_till_done() remove_failed_node = self.zwave_network.controller.remove_failed_node assert remove_failed_node.called assert len(remove_failed_node.mock_calls) == 1 assert remove_failed_node.mock_calls[0][1][0] == 12 def test_replace_failed_node(self): """Test zwave replace_failed_node service.""" self.hass.services.call('zwave', 'replace_failed_node', { const.ATTR_NODE_ID: 13, }) self.hass.block_till_done() replace_failed_node = self.zwave_network.controller.replace_failed_node assert replace_failed_node.called assert len(replace_failed_node.mock_calls) == 1 assert replace_failed_node.mock_calls[0][1][0] == 13 def test_set_config_parameter(self): """Test zwave set_config_parameter service.""" value_byte = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BYTE, ) value_list = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['item1', 'item2', 'item3'], ) value_button = MockValue( index=14, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BUTTON, ) value_list_int = MockValue( index=15, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['1', '2', '3'], ) value_bool = MockValue( index=16, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BOOL, ) node = MockNode(node_id=14) node.get_values.return_value = { 12: value_byte, 13: value_list, 14: value_button, 15: value_list_int, 16: value_bool } self.zwave_network.nodes = {14: node} # Byte self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 12, const.ATTR_CONFIG_VALUE: 7, }) self.hass.block_till_done() assert value_byte.data == 7 # List self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, const.ATTR_CONFIG_VALUE: 'item3', }) self.hass.block_till_done() assert value_list.data == 'item3' # Button self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 14, const.ATTR_CONFIG_VALUE: True, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called assert self.zwave_network.manager.releaseButton.called # List of Ints self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 15, const.ATTR_CONFIG_VALUE: 3, }) self.hass.block_till_done() assert value_list_int.data == '3' # Boolean Truthy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'True', }) self.hass.block_till_done() assert value_bool.data == 1 # Boolean Falsy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'False', }) self.hass.block_till_done() assert value_bool.data == 0 # Different Parameter Size self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 19, const.ATTR_CONFIG_VALUE: 0x01020304, const.ATTR_CONFIG_SIZE: 4 }) self.hass.block_till_done() assert node.set_config_param.called assert len(node.set_config_param.mock_calls) == 1 assert node.set_config_param.mock_calls[0][1][0] == 19 assert node.set_config_param.mock_calls[0][1][1] == 0x01020304 assert node.set_config_param.mock_calls[0][1][2] == 4 node.set_config_param.reset_mock() def test_print_config_parameter(self): """Test zwave print_config_parameter service.""" value1 = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, data=1234, ) value2 = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, data=2345, ) node = MockNode(node_id=14) node.values = {12: value1, 13: value2} self.zwave_network.nodes = {14: node} with patch.object(zwave, '_LOGGER') as mock_logger: self.hass.services.call('zwave', 'print_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, }) self.hass.block_till_done() assert mock_logger.info.called assert len(mock_logger.info.mock_calls) == 1 assert mock_logger.info.mock_calls[0][1][1] == 13 assert mock_logger.info.mock_calls[0][1][2] == 14 assert mock_logger.info.mock_calls[0][1][3] == 2345 def test_print_node(self): """Test zwave print_node_parameter service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} with self.assertLogs(level='DEBUG') as mock_logger: self.hass.services.call('zwave', 'print_node', { const.ATTR_NODE_ID: 14 }) self.hass.block_till_done() assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 15, }) self.hass.block_till_done() assert value.data == 15 node.can_wake_up_value = False self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 20, }) self.hass.block_till_done() assert value.data == 15 def test_reset_node_meters(self): """Test zwave reset_node_meters service.""" value = MockValue( instance=1, index=8, data=99.5, command_class=const.COMMAND_CLASS_METER, ) reset_value = MockValue( instance=1, index=33, command_class=const.COMMAND_CLASS_METER, ) node = MockNode(node_id=14) node.values = {8: value, 33: reset_value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, const.ATTR_INSTANCE: 2, }) self.hass.block_till_done() assert not self.zwave_network.manager.pressButton.called assert not self.zwave_network.manager.releaseButton.called self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called value_id, = self.zwave_network.manager.pressButton.mock_calls.pop(0)[1] assert value_id == reset_value.value_id assert self.zwave_network.manager.releaseButton.called value_id, = ( self.zwave_network.manager.releaseButton.mock_calls.pop(0)[1]) assert value_id == reset_value.value_id def test_add_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'add', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.add_association.called assert len(group.add_association.mock_calls) == 1 assert group.add_association.mock_calls[0][1][0] == 24 assert group.add_association.mock_calls[0][1][1] == 5 def test_remove_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'remove', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.remove_association.called assert len(group.remove_association.mock_calls) == 1 assert group.remove_association.mock_calls[0][1][0] == 24 assert group.remove_association.mock_calls[0][1][1] == 5 def test_refresh_entity(self): """Test zwave refresh_entity service.""" node = MockNode() value = MockValue(data=False, node=node, command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50, node=node, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = get_device(node=node, values=values, node_config={}) device.hass = self.hass device.entity_id = 'binary_sensor.mock_entity_id' self.hass.add_job(device.async_added_to_hass()) self.hass.block_till_done() self.hass.services.call('zwave', 'refresh_entity', { ATTR_ENTITY_ID: 'binary_sensor.mock_entity_id', }) self.hass.block_till_done() assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 assert sorted([node.refresh_value.mock_calls[0][1][0], node.refresh_value.mock_calls[1][1][0]]) == \ sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert node.refresh_info.called assert len(node.refresh_info.mock_calls) == 1 def test_set_node_value(self): """Test zwave set_node_value service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=4 ) node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR]) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12, const.ATTR_CONFIG_VALUE: 2, }) self.hass.block_till_done() assert self.zwave_network.nodes[14].values[12].data == 2 def test_refresh_node_value(self): """Test zwave refresh_node_value service.""" node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR], network=self.zwave_network) value = MockValue( node=node, index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=2 ) value.refresh = MagicMock() node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12 }) self.hass.block_till_done() assert value.refresh.called def test_heal_node(self): """Test zwave heal_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'heal_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.heal.called assert len(node.heal.mock_calls) == 1 def test_test_node(self): """Test the zwave test_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'test_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.test.called assert len(node.test.mock_calls) == 1
jabesq/home-assistant
tests/components/zwave/test_init.py
homeassistant/components/tellstick/sensor.py
"""Support for LaCrosse sensor components.""" from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.sensor import ENTITY_ID_FORMAT, PLATFORM_SCHEMA from homeassistant.const import ( CONF_DEVICE, CONF_ID, CONF_NAME, CONF_SENSORS, CONF_TYPE, EVENT_HOMEASSISTANT_STOP, TEMP_CELSIUS) from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity, async_generate_entity_id from homeassistant.helpers.event import async_track_point_in_utc_time from homeassistant.util import dt as dt_util _LOGGER = logging.getLogger(__name__) CONF_BAUD = 'baud' CONF_DATARATE = 'datarate' CONF_EXPIRE_AFTER = 'expire_after' CONF_FREQUENCY = 'frequency' CONF_JEELINK_LED = 'led' CONF_TOGGLE_INTERVAL = 'toggle_interval' CONF_TOGGLE_MASK = 'toggle_mask' DEFAULT_DEVICE = '/dev/ttyUSB0' DEFAULT_BAUD = '57600' DEFAULT_EXPIRE_AFTER = 300 TYPES = ['battery', 'humidity', 'temperature'] SENSOR_SCHEMA = vol.Schema({ vol.Required(CONF_ID): cv.positive_int, vol.Required(CONF_TYPE): vol.In(TYPES), vol.Optional(CONF_EXPIRE_AFTER): cv.positive_int, vol.Optional(CONF_NAME): cv.string, }) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_SENSORS): cv.schema_with_slug_keys(SENSOR_SCHEMA), vol.Optional(CONF_BAUD, default=DEFAULT_BAUD): cv.string, vol.Optional(CONF_DATARATE): cv.positive_int, vol.Optional(CONF_DEVICE, default=DEFAULT_DEVICE): cv.string, vol.Optional(CONF_FREQUENCY): cv.positive_int, vol.Optional(CONF_JEELINK_LED): cv.boolean, vol.Optional(CONF_TOGGLE_INTERVAL): cv.positive_int, vol.Optional(CONF_TOGGLE_MASK): cv.positive_int, }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the LaCrosse sensors.""" import pylacrosse from serial import SerialException usb_device = config.get(CONF_DEVICE) baud = int(config.get(CONF_BAUD)) expire_after = config.get(CONF_EXPIRE_AFTER) _LOGGER.debug("%s %s", usb_device, baud) try: lacrosse = pylacrosse.LaCrosse(usb_device, baud) lacrosse.open() except SerialException as exc: _LOGGER.warning("Unable to open serial port: %s", exc) return False hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, lacrosse.close) if CONF_JEELINK_LED in config: lacrosse.led_mode_state(config.get(CONF_JEELINK_LED)) if CONF_FREQUENCY in config: lacrosse.set_frequency(config.get(CONF_FREQUENCY)) if CONF_DATARATE in config: lacrosse.set_datarate(config.get(CONF_DATARATE)) if CONF_TOGGLE_INTERVAL in config: lacrosse.set_toggle_interval(config.get(CONF_TOGGLE_INTERVAL)) if CONF_TOGGLE_MASK in config: lacrosse.set_toggle_mask(config.get(CONF_TOGGLE_MASK)) lacrosse.start_scan() sensors = [] for device, device_config in config[CONF_SENSORS].items(): _LOGGER.debug("%s %s", device, device_config) typ = device_config.get(CONF_TYPE) sensor_class = TYPE_CLASSES[typ] name = device_config.get(CONF_NAME, device) sensors.append( sensor_class( hass, lacrosse, device, name, expire_after, device_config ) ) add_entities(sensors) class LaCrosseSensor(Entity): """Implementation of a Lacrosse sensor.""" _temperature = None _humidity = None _low_battery = None _new_battery = None def __init__(self, hass, lacrosse, device_id, name, expire_after, config): """Initialize the sensor.""" self.hass = hass self.entity_id = async_generate_entity_id( ENTITY_ID_FORMAT, device_id, hass=hass) self._config = config self._name = name self._value = None self._expire_after = expire_after self._expiration_trigger = None lacrosse.register_callback( int(self._config['id']), self._callback_lacrosse, None) @property def name(self): """Return the name of the sensor.""" return self._name @property def device_state_attributes(self): """Return the state attributes.""" attributes = { 'low_battery': self._low_battery, 'new_battery': self._new_battery, } return attributes def _callback_lacrosse(self, lacrosse_sensor, user_data): """Handle a function that is called from pylacrosse with new values.""" if self._expire_after is not None and self._expire_after > 0: # Reset old trigger if self._expiration_trigger: self._expiration_trigger() self._expiration_trigger = None # Set new trigger expiration_at = ( dt_util.utcnow() + timedelta(seconds=self._expire_after)) self._expiration_trigger = async_track_point_in_utc_time( self.hass, self.value_is_expired, expiration_at) self._temperature = lacrosse_sensor.temperature self._humidity = lacrosse_sensor.humidity self._low_battery = lacrosse_sensor.low_battery self._new_battery = lacrosse_sensor.new_battery @callback def value_is_expired(self, *_): """Triggered when value is expired.""" self._expiration_trigger = None self._value = None self.async_schedule_update_ha_state() class LaCrosseTemperature(LaCrosseSensor): """Implementation of a Lacrosse temperature sensor.""" @property def unit_of_measurement(self): """Return the unit of measurement.""" return TEMP_CELSIUS @property def state(self): """Return the state of the sensor.""" return self._temperature class LaCrosseHumidity(LaCrosseSensor): """Implementation of a Lacrosse humidity sensor.""" @property def unit_of_measurement(self): """Return the unit of measurement.""" return '%' @property def state(self): """Return the state of the sensor.""" return self._humidity @property def icon(self): """Icon to use in the frontend.""" return 'mdi:water-percent' class LaCrosseBattery(LaCrosseSensor): """Implementation of a Lacrosse battery sensor.""" @property def state(self): """Return the state of the sensor.""" if self._low_battery is None: state = None elif self._low_battery is True: state = 'low' else: state = 'ok' return state @property def icon(self): """Icon to use in the frontend.""" if self._low_battery is None: icon = 'mdi:battery-unknown' elif self._low_battery is True: icon = 'mdi:battery-alert' else: icon = 'mdi:battery' return icon TYPE_CLASSES = { 'temperature': LaCrosseTemperature, 'humidity': LaCrosseHumidity, 'battery': LaCrosseBattery }
"""Tests for the Z-Wave init.""" import asyncio from collections import OrderedDict from datetime import datetime import unittest from unittest.mock import MagicMock, patch import pytest from pytz import utc import voluptuous as vol from homeassistant.bootstrap import async_setup_component from homeassistant.components import zwave from homeassistant.components.zwave import ( CONF_DEVICE_CONFIG_GLOB, CONFIG_SCHEMA, DATA_NETWORK, const) from homeassistant.components.zwave.binary_sensor import get_device from homeassistant.const import ATTR_ENTITY_ID, EVENT_HOMEASSISTANT_START from homeassistant.helpers.entity_registry import async_get_registry from homeassistant.helpers.device_registry import ( async_get_registry as get_dev_reg) from homeassistant.setup import setup_component from tests.common import ( async_fire_time_changed, get_test_home_assistant, mock_coro, mock_registry) from tests.mock.zwave import MockEntityValues, MockNetwork, MockNode, MockValue async def test_valid_device_config(hass, mock_openzwave): """Test valid device config.""" device_config = { 'light.kitchen': { 'ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert result async def test_invalid_device_config(hass, mock_openzwave): """Test invalid device config.""" device_config = { 'light.kitchen': { 'some_ignored': 'true' } } result = await async_setup_component(hass, 'zwave', { 'zwave': { 'device_config': device_config }}) await hass.async_block_till_done() assert not result def test_config_access_error(): """Test threading error accessing config values.""" node = MagicMock() def side_effect(): raise RuntimeError node.values.values.side_effect = side_effect result = zwave.get_config_value(node, 1) assert result is None async def test_network_options(hass, mock_openzwave): """Test network options.""" result = await async_setup_component(hass, 'zwave', { 'zwave': { 'usb_path': 'mock_usb_path', 'config_path': 'mock_config_path', }}) await hass.async_block_till_done() assert result network = hass.data[zwave.DATA_NETWORK] assert network.options.device == 'mock_usb_path' assert network.options.config_path == 'mock_config_path' async def test_network_key_validation(hass, mock_openzwave): """Test network key validation.""" test_values = [ ('0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,' '0x0E,0x0F,0x10'), ] for value in test_values: result = zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) assert result['zwave']['network_key'] == value async def test_erronous_network_key_fails_validation(hass, mock_openzwave): """Test failing erronous network key validation.""" test_values = [ ('0x 01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, ' '0x0C, 0x0D, 0x0E, 0x0F, 0x10'), ('0X01,0X02,0X03,0X04,0X05,0X06,0X07,0X08,0X09,0X0A,0X0B,0X0C,0X0D,' '0X0E,0X0F,0X10'), 'invalid', '1234567', 1234567 ] for value in test_values: with pytest.raises(vol.Invalid): zwave.CONFIG_SCHEMA({'zwave': {'network_key': value}}) async def test_auto_heal_midnight(hass, mock_openzwave): """Test network auto-heal at midnight.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': True, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert network.heal.called assert len(network.heal.mock_calls) == 1 async def test_auto_heal_disabled(hass, mock_openzwave): """Test network auto-heal disabled.""" await async_setup_component(hass, 'zwave', { 'zwave': { 'autoheal': False, }}) await hass.async_block_till_done() network = hass.data[zwave.DATA_NETWORK] assert not network.heal.called time = utc.localize(datetime(2017, 5, 6, 0, 0, 0)) async_fire_time_changed(hass, time) await hass.async_block_till_done() assert not network.heal.called async def test_setup_platform(hass, mock_openzwave): """Test invalid device config.""" mock_device = MagicMock() hass.data[DATA_NETWORK] = MagicMock() hass.data[zwave.DATA_DEVICES] = {456: mock_device} async_add_entities = MagicMock() result = await zwave.async_setup_platform( hass, None, async_add_entities, None) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 123}) assert not result assert not async_add_entities.called result = await zwave.async_setup_platform( hass, None, async_add_entities, {const.DISCOVERY_DEVICE: 456}) assert result assert async_add_entities.called assert len(async_add_entities.mock_calls) == 1 assert async_add_entities.mock_calls[0][1][0] == [mock_device] async def test_zwave_ready_wait(hass, mock_openzwave): """Test that zwave continues after waiting for network ready.""" # Initialize zwave await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert len(sleeps) == const.NETWORK_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1] == \ const.NETWORK_READY_WAIT_SECS async def test_device_entity(hass, mock_openzwave): """Test device entity base class.""" node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.value_added() device.update_properties() await hass.async_block_till_done() assert not device.should_poll assert device.unique_id == "10-11" assert device.name == 'Mock Node Sensor' assert device.device_state_attributes[zwave.ATTR_POWER] == 50.123 async def test_node_removed(hass, mock_openzwave): """Test node removed in base class.""" # Create a mock node & node entity node = MockNode(node_id='10', name='Mock Node') value = MockValue(data=False, node=node, instance=2, object_id='11', label='Sensor', command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50.123456, node=node, precision=3, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = zwave.ZWaveDeviceEntity(values, 'zwave') device.hass = hass device.entity_id = 'zwave.mock_node' device.value_added() device.update_properties() await hass.async_block_till_done() # Save it to the entity registry registry = mock_registry(hass) registry.async_get_or_create('zwave', 'zwave', device.unique_id) device.entity_id = registry.async_get_entity_id( 'zwave', 'zwave', device.unique_id) # Create dummy entity registry entries for other integrations hue_entity = registry.async_get_or_create('light', 'hue', 1234) zha_entity = registry.async_get_or_create('sensor', 'zha', 5678) # Verify our Z-Wave entity is registered assert registry.async_is_registered(device.entity_id) # Remove it entity_id = device.entity_id await device.node_removed() # Verify registry entry for our Z-Wave node is gone assert not registry.async_is_registered(entity_id) # Verify registry entries for our other entities remain assert registry.async_is_registered(hue_entity.entity_id) assert registry.async_is_registered(zha_entity.entity_id) async def test_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node').state == 'unknown' async def test_unparsed_node_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode( node_id=14, manufacturer_name=None, name=None, is_ready=False) sleeps = [] def utcnow(): return datetime.fromtimestamp(len(sleeps)) asyncio_sleep = asyncio.sleep async def sleep(duration, loop=None): if duration > 0: sleeps.append(duration) await asyncio_sleep(0) with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow): with patch('asyncio.sleep', new=sleep): with patch.object(zwave, '_LOGGER') as mock_logger: hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert len(sleeps) == const.NODE_READY_WAIT_SECS assert mock_logger.warning.called assert len(mock_logger.warning.mock_calls) == 1 assert mock_logger.warning.mock_calls[0][1][1:] == \ (14, const.NODE_READY_WAIT_SECS) assert hass.states.get('zwave.unknown_node_14').state == 'unknown' async def test_node_ignored(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_NODE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': { 'device_config': { 'zwave.mock_node': { 'ignored': True, }}}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=14) hass.async_add_job(mock_receivers[0], node) await hass.async_block_till_done() assert hass.states.get('zwave.mock_node') is None async def test_value_discovery(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) value = MockValue(data=False, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) hass.async_add_job(mock_receivers[0], node, value) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' async def test_value_entities(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = {} def mock_connect(receiver, signal, *args, **kwargs): mock_receivers[signal] = receiver with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() zwave_network = hass.data[DATA_NETWORK] zwave_network.state = MockNetwork.STATE_READY hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert mock_receivers hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_ALL_NODES_QUERIED]) node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SENSOR_BINARY) zwave_network.nodes = {node.node_id: node} value = MockValue( data=False, node=node, index=12, instance=1, command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values = {'primary': value, value.value_id: value} value2 = MockValue( data=False, node=node, index=12, instance=2, label="Mock Value B", command_class=const.COMMAND_CLASS_SENSOR_BINARY, type=const.TYPE_BOOL, genre=const.GENRE_USER) node.values[value2.value_id] = value2 hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_NODE_ADDED], node) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value) hass.async_add_job( mock_receivers[MockNetwork.SIGNAL_VALUE_ADDED], node, value2) await hass.async_block_till_done() assert hass.states.get( 'binary_sensor.mock_node_mock_value').state == 'off' assert hass.states.get( 'binary_sensor.mock_node_mock_value_b').state == 'off' ent_reg = await async_get_registry(hass) dev_reg = await get_dev_reg(hass) entry = ent_reg.async_get('zwave.mock_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) node_dev_id = entry.device_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) assert entry.name is None assert entry.device_id == node_dev_id entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value2.object_id) assert entry.name is None assert entry.device_id != node_dev_id device_id_b = entry.device_id device = dev_reg.async_get(node_dev_id) assert device is not None assert device.name == node.name old_device = device device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming without updating await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_NAME: "Demo Node", }) await hass.async_block_till_done() assert node.name == "Demo Node" entry = ent_reg.async_get('zwave.mock_node') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value') assert entry is not None entry = ent_reg.async_get('binary_sensor.mock_node_mock_value_b') assert entry is not None device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) # test renaming await hass.services.async_call('zwave', 'rename_node', { const.ATTR_NODE_ID: node.node_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Node", }) await hass.async_block_till_done() assert node.name == "New Node" entry = ent_reg.async_get('zwave.new_node') assert entry is not None assert entry.unique_id == 'node-{}'.format(node.node_id) entry = ent_reg.async_get('binary_sensor.new_node_mock_value') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) device = dev_reg.async_get(node_dev_id) assert device is not None assert device.id == old_device.id assert device.name == node.name device = dev_reg.async_get(device_id_b) assert device is not None assert device.name == "{} ({})".format(node.name, value2.instance) await hass.services.async_call('zwave', 'rename_value', { const.ATTR_NODE_ID: node.node_id, const.ATTR_VALUE_ID: value.object_id, const.ATTR_UPDATE_IDS: True, const.ATTR_NAME: "New Label", }) await hass.async_block_till_done() entry = ent_reg.async_get('binary_sensor.new_node_new_label') assert entry is not None assert entry.unique_id == '{}-{}'.format(node.node_id, value.object_id) async def test_value_discovery_existing_entity(hass, mock_openzwave): """Test discovery of a node.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_THERMOSTAT) setpoint = MockValue( data=22.0, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_THERMOSTAT_SETPOINT, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, setpoint) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] is None def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): temperature = MockValue( data=23.5, node=node, index=1, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL, genre=const.GENRE_USER, units='C') hass.async_add_job(mock_receivers[0], node, temperature) await hass.async_block_till_done() assert hass.states.get('climate.mock_node_mock_value').attributes[ 'temperature'] == 22.0 assert hass.states.get('climate.mock_node_mock_value').attributes[ 'current_temperature'] == 23.5 async def test_power_schemes(hass, mock_openzwave): """Test power attribute.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_VALUE_ADDED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 node = MockNode(node_id=11, generic=const.GENERIC_TYPE_SWITCH_BINARY) switch = MockValue( data=True, node=node, index=12, instance=13, command_class=const.COMMAND_CLASS_SWITCH_BINARY, genre=const.GENRE_USER, type=const.TYPE_BOOL) hass.async_add_job(mock_receivers[0], node, switch) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').state == 'on' assert 'power_consumption' not in hass.states.get( 'switch.mock_node_mock_value').attributes def mock_update(self): self.hass.add_job(self.async_update_ha_state) with patch.object(zwave.node_entity.ZWaveBaseEntity, 'maybe_schedule_update', new=mock_update): power = MockValue( data=23.5, node=node, index=const.INDEX_SENSOR_MULTILEVEL_POWER, instance=13, command_class=const.COMMAND_CLASS_SENSOR_MULTILEVEL) hass.async_add_job(mock_receivers[0], node, power) await hass.async_block_till_done() assert hass.states.get('switch.mock_node_mock_value').attributes[ 'power_consumption'] == 23.5 async def test_network_ready(hass, mock_openzwave): """Test Node network ready event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete(hass, mock_openzwave): """Test Node network complete event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_AWAKE_NODES_QUERIED: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_READY, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 async def test_network_complete_some_dead(hass, mock_openzwave): """Test Node network complete some dead event.""" mock_receivers = [] def mock_connect(receiver, signal, *args, **kwargs): if signal == MockNetwork.SIGNAL_ALL_NODES_QUERIED_SOME_DEAD: mock_receivers.append(receiver) with patch('pydispatch.dispatcher.connect', new=mock_connect): await async_setup_component(hass, 'zwave', {'zwave': {}}) await hass.async_block_till_done() assert len(mock_receivers) == 1 events = [] def listener(event): events.append(event) hass.bus.async_listen(const.EVENT_NETWORK_COMPLETE_SOME_DEAD, listener) hass.async_add_job(mock_receivers[0]) await hass.async_block_till_done() assert len(events) == 1 class TestZWaveDeviceEntityValues(unittest.TestCase): """Tests for the ZWaveDeviceEntityValues helper.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() self.registry = mock_registry(self.hass) setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.node = MockNode() self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: ['mock_primary_class'], }, 'secondary': { const.DISC_COMMAND_CLASS: ['mock_secondary_class'], }, 'optional': { const.DISC_COMMAND_CLASS: ['mock_optional_class'], const.DISC_OPTIONAL: True, }}} self.primary = MockValue( command_class='mock_primary_class', node=self.node, value_id=1000) self.secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.duplicate_secondary = MockValue( command_class='mock_secondary_class', node=self.node) self.optional = MockValue( command_class='mock_optional_class', node=self.node) self.no_match_value = MockValue( command_class='mock_bad_class', node=self.node) self.entity_id = 'mock_component.mock_node_mock_value' self.zwave_config = {'zwave': {}} self.device_config = {self.entity_id: {}} def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.stop() @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_discovery(self, discovery, import_module): """Test the creation of a new entity.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) assert values.primary is self.primary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, None, None], key=lambda a: id(a)) assert not discovery.async_load_platform.called values.check_value(self.secondary) self.hass.block_till_done() assert values.secondary is self.secondary assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, None], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config discovery.async_load_platform.reset_mock() values.check_value(self.optional) values.check_value(self.duplicate_secondary) values.check_value(self.no_match_value) self.hass.block_till_done() assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert not discovery.async_load_platform.called assert values._entity.value_added.called assert len(values._entity.value_added.mock_calls) == 1 assert values._entity.value_changed.called assert len(values._entity.value_changed.mock_calls) == 1 @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_existing_values(self, discovery, import_module): """Test the loading of already discovered values.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, self.optional.value_id: self.optional, self.no_match_value.value_id: self.no_match_value, } values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert values.primary is self.primary assert values.secondary is self.secondary assert values.optional is self.optional assert len(list(values)) == 3 assert sorted(list(values), key=lambda a: id(a)) == \ sorted([self.primary, self.secondary, self.optional], key=lambda a: id(a)) assert discovery.async_load_platform.called assert len(discovery.async_load_platform.mock_calls) == 1 args = discovery.async_load_platform.mock_calls[0][1] assert args[0] == self.hass assert args[1] == 'mock_component' assert args[2] == 'zwave' assert args[3] == {const.DISCOVERY_DEVICE: mock_device.unique_id} assert args[4] == self.zwave_config assert not self.primary.enable_poll.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_node_schema_mismatch(self, discovery, import_module): """Test node schema mismatch.""" self.node.generic = 'no_match' self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.mock_schema[const.DISC_GENERIC_DEVICE_CLASS] = ['generic_match'] values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_component(self, discovery, import_module): """Test component workaround.""" discovery.async_load_platform.return_value = mock_coro() mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.manufacturer_id = '010f' self.node.product_type = '0b00' self.primary.command_class = const.COMMAND_CLASS_SENSOR_ALARM self.entity_id = 'binary_sensor.mock_node_mock_value' self.device_config = {self.entity_id: {}} self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} with patch.object(zwave, 'async_dispatcher_send') as \ mock_dispatch_send: values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert mock_dispatch_send.called assert len(mock_dispatch_send.mock_calls) == 1 args = mock_dispatch_send.mock_calls[0][1] assert args[1] == 'zwave_new_binary_sensor' @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_workaround_ignore(self, discovery, import_module): """Test ignore workaround.""" self.node.manufacturer_id = '010f' self.node.product_type = '0301' self.primary.command_class = const.COMMAND_CLASS_SWITCH_BINARY self.mock_schema = { const.DISC_COMPONENT: 'mock_component', const.DISC_VALUES: { const.DISC_PRIMARY: { const.DISC_COMMAND_CLASS: [ const.COMMAND_CLASS_SWITCH_BINARY], }}} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore(self, discovery, import_module): """Test ignore config.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_IGNORED: True }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_config_ignore_with_registry(self, discovery, import_module): """Test ignore config. The case when the device is in entity registry. """ self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {'mock_component.registry_id': { zwave.CONF_IGNORED: True }} with patch.object(self.registry, 'async_schedule_save'): self.registry.async_get_or_create( 'mock_component', zwave.DOMAIN, '567-1000', suggested_object_id='registry_id') zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_entity_platform_ignore(self, discovery, import_module): """Test platform ignore device.""" self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } platform = MagicMock() import_module.return_value = platform platform.get_device.return_value = None zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) self.hass.block_till_done() assert not discovery.async_load_platform.called @patch.object(zwave, 'import_module') @patch.object(zwave, 'discovery') def test_config_polling_intensity(self, discovery, import_module): """Test polling intensity.""" mock_platform = MagicMock() import_module.return_value = mock_platform mock_device = MagicMock() mock_device.name = 'test_device' mock_platform.get_device.return_value = mock_device self.node.values = { self.primary.value_id: self.primary, self.secondary.value_id: self.secondary, } self.device_config = {self.entity_id: { zwave.CONF_POLLING_INTENSITY: 123, }} values = zwave.ZWaveDeviceEntityValues( hass=self.hass, schema=self.mock_schema, primary_value=self.primary, zwave_config=self.zwave_config, device_config=self.device_config, registry=self.registry ) values._check_entity_ready() self.hass.block_till_done() assert discovery.async_load_platform.called assert self.primary.enable_poll.called assert len(self.primary.enable_poll.mock_calls) == 1 assert self.primary.enable_poll.mock_calls[0][1][0] == 123 class TestZwave(unittest.TestCase): """Test zwave init.""" def test_device_config_glob_is_ordered(self): """Test that device_config_glob preserves order.""" conf = CONFIG_SCHEMA( {'zwave': {CONF_DEVICE_CONFIG_GLOB: OrderedDict()}}) assert isinstance(conf['zwave'][CONF_DEVICE_CONFIG_GLOB], OrderedDict) class TestZWaveServices(unittest.TestCase): """Tests for zwave services.""" @pytest.fixture(autouse=True) def set_mock_openzwave(self, mock_openzwave): """Use the mock_openzwave fixture for this class.""" self.mock_openzwave = mock_openzwave def setUp(self): """Initialize values for this testcase class.""" self.hass = get_test_home_assistant() self.hass.start() # Initialize zwave setup_component(self.hass, 'zwave', {'zwave': {}}) self.hass.block_till_done() self.zwave_network = self.hass.data[DATA_NETWORK] self.zwave_network.state = MockNetwork.STATE_READY self.hass.bus.fire(EVENT_HOMEASSISTANT_START) self.hass.block_till_done() def tearDown(self): # pylint: disable=invalid-name """Stop everything that was started.""" self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() self.hass.stop() def test_add_node(self): """Test zwave add_node service.""" self.hass.services.call('zwave', 'add_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller .add_node.mock_calls) == 1 assert len(self.zwave_network.controller .add_node.mock_calls[0][1]) == 0 def test_add_node_secure(self): """Test zwave add_node_secure service.""" self.hass.services.call('zwave', 'add_node_secure', {}) self.hass.block_till_done() assert self.zwave_network.controller.add_node.called assert len(self.zwave_network.controller.add_node.mock_calls) == 1 assert (self.zwave_network.controller .add_node.mock_calls[0][1][0] is True) def test_remove_node(self): """Test zwave remove_node service.""" self.hass.services.call('zwave', 'remove_node', {}) self.hass.block_till_done() assert self.zwave_network.controller.remove_node.called assert len(self.zwave_network.controller.remove_node.mock_calls) == 1 def test_cancel_command(self): """Test zwave cancel_command service.""" self.hass.services.call('zwave', 'cancel_command', {}) self.hass.block_till_done() assert self.zwave_network.controller.cancel_command.called assert len(self.zwave_network.controller .cancel_command.mock_calls) == 1 def test_heal_network(self): """Test zwave heal_network service.""" self.hass.services.call('zwave', 'heal_network', {}) self.hass.block_till_done() assert self.zwave_network.heal.called assert len(self.zwave_network.heal.mock_calls) == 1 def test_soft_reset(self): """Test zwave soft_reset service.""" self.hass.services.call('zwave', 'soft_reset', {}) self.hass.block_till_done() assert self.zwave_network.controller.soft_reset.called assert len(self.zwave_network.controller.soft_reset.mock_calls) == 1 def test_test_network(self): """Test zwave test_network service.""" self.hass.services.call('zwave', 'test_network', {}) self.hass.block_till_done() assert self.zwave_network.test.called assert len(self.zwave_network.test.mock_calls) == 1 def test_stop_network(self): """Test zwave stop_network service.""" with patch.object(self.hass.bus, 'fire') as mock_fire: self.hass.services.call('zwave', 'stop_network', {}) self.hass.block_till_done() assert self.zwave_network.stop.called assert len(self.zwave_network.stop.mock_calls) == 1 assert mock_fire.called assert len(mock_fire.mock_calls) == 1 assert mock_fire.mock_calls[0][1][0] == const.EVENT_NETWORK_STOP def test_rename_node(self): """Test zwave rename_node service.""" self.zwave_network.nodes = {11: MagicMock()} self.hass.services.call('zwave', 'rename_node', { const.ATTR_NODE_ID: 11, const.ATTR_NAME: 'test_name', }) self.hass.block_till_done() assert self.zwave_network.nodes[11].name == 'test_name' def test_rename_value(self): """Test zwave rename_value service.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, label="Old Label") node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.label == "Old Label" self.hass.services.call('zwave', 'rename_value', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_NAME: "New Label", }) self.hass.block_till_done() assert value.label == "New Label" def test_set_poll_intensity_enable(self): """Test zwave set_poll_intensity service, successful set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 2 assert enable_poll.mock_calls[0][1][0] == 4 def test_set_poll_intensity_enable_failed(self): """Test zwave set_poll_intensity service, failed set.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=0) value.enable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 0 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 4, }) self.hass.block_till_done() enable_poll = value.enable_poll assert value.enable_poll.called assert len(enable_poll.mock_calls) == 1 def test_set_poll_intensity_disable(self): """Test zwave set_poll_intensity service, successful disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 2 def test_set_poll_intensity_disable_failed(self): """Test zwave set_poll_intensity service, failed disable.""" node = MockNode(node_id=14) value = MockValue(index=12, value_id=123456, poll_intensity=4) value.disable_poll.return_value = False node.values = {123456: value} self.zwave_network.nodes = {11: node} assert value.poll_intensity == 4 self.hass.services.call('zwave', 'set_poll_intensity', { const.ATTR_NODE_ID: 11, const.ATTR_VALUE_ID: 123456, const.ATTR_POLL_INTENSITY: 0, }) self.hass.block_till_done() disable_poll = value.disable_poll assert value.disable_poll.called assert len(disable_poll.mock_calls) == 1 def test_remove_failed_node(self): """Test zwave remove_failed_node service.""" self.hass.services.call('zwave', 'remove_failed_node', { const.ATTR_NODE_ID: 12, }) self.hass.block_till_done() remove_failed_node = self.zwave_network.controller.remove_failed_node assert remove_failed_node.called assert len(remove_failed_node.mock_calls) == 1 assert remove_failed_node.mock_calls[0][1][0] == 12 def test_replace_failed_node(self): """Test zwave replace_failed_node service.""" self.hass.services.call('zwave', 'replace_failed_node', { const.ATTR_NODE_ID: 13, }) self.hass.block_till_done() replace_failed_node = self.zwave_network.controller.replace_failed_node assert replace_failed_node.called assert len(replace_failed_node.mock_calls) == 1 assert replace_failed_node.mock_calls[0][1][0] == 13 def test_set_config_parameter(self): """Test zwave set_config_parameter service.""" value_byte = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BYTE, ) value_list = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['item1', 'item2', 'item3'], ) value_button = MockValue( index=14, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BUTTON, ) value_list_int = MockValue( index=15, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_LIST, data_items=['1', '2', '3'], ) value_bool = MockValue( index=16, command_class=const.COMMAND_CLASS_CONFIGURATION, type=const.TYPE_BOOL, ) node = MockNode(node_id=14) node.get_values.return_value = { 12: value_byte, 13: value_list, 14: value_button, 15: value_list_int, 16: value_bool } self.zwave_network.nodes = {14: node} # Byte self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 12, const.ATTR_CONFIG_VALUE: 7, }) self.hass.block_till_done() assert value_byte.data == 7 # List self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, const.ATTR_CONFIG_VALUE: 'item3', }) self.hass.block_till_done() assert value_list.data == 'item3' # Button self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 14, const.ATTR_CONFIG_VALUE: True, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called assert self.zwave_network.manager.releaseButton.called # List of Ints self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 15, const.ATTR_CONFIG_VALUE: 3, }) self.hass.block_till_done() assert value_list_int.data == '3' # Boolean Truthy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'True', }) self.hass.block_till_done() assert value_bool.data == 1 # Boolean Falsy self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 16, const.ATTR_CONFIG_VALUE: 'False', }) self.hass.block_till_done() assert value_bool.data == 0 # Different Parameter Size self.hass.services.call('zwave', 'set_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 19, const.ATTR_CONFIG_VALUE: 0x01020304, const.ATTR_CONFIG_SIZE: 4 }) self.hass.block_till_done() assert node.set_config_param.called assert len(node.set_config_param.mock_calls) == 1 assert node.set_config_param.mock_calls[0][1][0] == 19 assert node.set_config_param.mock_calls[0][1][1] == 0x01020304 assert node.set_config_param.mock_calls[0][1][2] == 4 node.set_config_param.reset_mock() def test_print_config_parameter(self): """Test zwave print_config_parameter service.""" value1 = MockValue( index=12, command_class=const.COMMAND_CLASS_CONFIGURATION, data=1234, ) value2 = MockValue( index=13, command_class=const.COMMAND_CLASS_CONFIGURATION, data=2345, ) node = MockNode(node_id=14) node.values = {12: value1, 13: value2} self.zwave_network.nodes = {14: node} with patch.object(zwave, '_LOGGER') as mock_logger: self.hass.services.call('zwave', 'print_config_parameter', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_PARAMETER: 13, }) self.hass.block_till_done() assert mock_logger.info.called assert len(mock_logger.info.mock_calls) == 1 assert mock_logger.info.mock_calls[0][1][1] == 13 assert mock_logger.info.mock_calls[0][1][2] == 14 assert mock_logger.info.mock_calls[0][1][3] == 2345 def test_print_node(self): """Test zwave print_node_parameter service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} with self.assertLogs(level='DEBUG') as mock_logger: self.hass.services.call('zwave', 'print_node', { const.ATTR_NODE_ID: 14 }) self.hass.block_till_done() assert "FOUND NODE " in mock_logger.output[1] def test_set_wakeup(self): """Test zwave set_wakeup service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 15, }) self.hass.block_till_done() assert value.data == 15 node.can_wake_up_value = False self.hass.services.call('zwave', 'set_wakeup', { const.ATTR_NODE_ID: 14, const.ATTR_CONFIG_VALUE: 20, }) self.hass.block_till_done() assert value.data == 15 def test_reset_node_meters(self): """Test zwave reset_node_meters service.""" value = MockValue( instance=1, index=8, data=99.5, command_class=const.COMMAND_CLASS_METER, ) reset_value = MockValue( instance=1, index=33, command_class=const.COMMAND_CLASS_METER, ) node = MockNode(node_id=14) node.values = {8: value, 33: reset_value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, const.ATTR_INSTANCE: 2, }) self.hass.block_till_done() assert not self.zwave_network.manager.pressButton.called assert not self.zwave_network.manager.releaseButton.called self.hass.services.call('zwave', 'reset_node_meters', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert self.zwave_network.manager.pressButton.called value_id, = self.zwave_network.manager.pressButton.mock_calls.pop(0)[1] assert value_id == reset_value.value_id assert self.zwave_network.manager.releaseButton.called value_id, = ( self.zwave_network.manager.releaseButton.mock_calls.pop(0)[1]) assert value_id == reset_value.value_id def test_add_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'add', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.add_association.called assert len(group.add_association.mock_calls) == 1 assert group.add_association.mock_calls[0][1][0] == 24 assert group.add_association.mock_calls[0][1][1] == 5 def test_remove_association(self): """Test zwave change_association service.""" ZWaveGroup = self.mock_openzwave.group.ZWaveGroup group = MagicMock() ZWaveGroup.return_value = group value = MockValue( index=12, command_class=const.COMMAND_CLASS_WAKE_UP, ) node = MockNode(node_id=14) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'change_association', { const.ATTR_ASSOCIATION: 'remove', const.ATTR_NODE_ID: 14, const.ATTR_TARGET_NODE_ID: 24, const.ATTR_GROUP: 3, const.ATTR_INSTANCE: 5, }) self.hass.block_till_done() assert ZWaveGroup.called assert len(ZWaveGroup.mock_calls) == 2 assert ZWaveGroup.mock_calls[0][1][0] == 3 assert ZWaveGroup.mock_calls[0][1][2] == 14 assert group.remove_association.called assert len(group.remove_association.mock_calls) == 1 assert group.remove_association.mock_calls[0][1][0] == 24 assert group.remove_association.mock_calls[0][1][1] == 5 def test_refresh_entity(self): """Test zwave refresh_entity service.""" node = MockNode() value = MockValue(data=False, node=node, command_class=const.COMMAND_CLASS_SENSOR_BINARY) power_value = MockValue(data=50, node=node, command_class=const.COMMAND_CLASS_METER) values = MockEntityValues(primary=value, power=power_value) device = get_device(node=node, values=values, node_config={}) device.hass = self.hass device.entity_id = 'binary_sensor.mock_entity_id' self.hass.add_job(device.async_added_to_hass()) self.hass.block_till_done() self.hass.services.call('zwave', 'refresh_entity', { ATTR_ENTITY_ID: 'binary_sensor.mock_entity_id', }) self.hass.block_till_done() assert node.refresh_value.called assert len(node.refresh_value.mock_calls) == 2 assert sorted([node.refresh_value.mock_calls[0][1][0], node.refresh_value.mock_calls[1][1][0]]) == \ sorted([value.value_id, power_value.value_id]) def test_refresh_node(self): """Test zwave refresh_node service.""" node = MockNode(node_id=14) self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node', { const.ATTR_NODE_ID: 14, }) self.hass.block_till_done() assert node.refresh_info.called assert len(node.refresh_info.mock_calls) == 1 def test_set_node_value(self): """Test zwave set_node_value service.""" value = MockValue( index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=4 ) node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR]) node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'set_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12, const.ATTR_CONFIG_VALUE: 2, }) self.hass.block_till_done() assert self.zwave_network.nodes[14].values[12].data == 2 def test_refresh_node_value(self): """Test zwave refresh_node_value service.""" node = MockNode(node_id=14, command_classes=[const.COMMAND_CLASS_INDICATOR], network=self.zwave_network) value = MockValue( node=node, index=12, command_class=const.COMMAND_CLASS_INDICATOR, data=2 ) value.refresh = MagicMock() node.values = {12: value} node.get_values.return_value = node.values self.zwave_network.nodes = {14: node} self.hass.services.call('zwave', 'refresh_node_value', { const.ATTR_NODE_ID: 14, const.ATTR_VALUE_ID: 12 }) self.hass.block_till_done() assert value.refresh.called def test_heal_node(self): """Test zwave heal_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'heal_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.heal.called assert len(node.heal.mock_calls) == 1 def test_test_node(self): """Test the zwave test_node service.""" node = MockNode(node_id=19) self.zwave_network.nodes = {19: node} self.hass.services.call('zwave', 'test_node', { const.ATTR_NODE_ID: 19, }) self.hass.block_till_done() assert node.test.called assert len(node.test.mock_calls) == 1
jabesq/home-assistant
tests/components/zwave/test_init.py
homeassistant/components/lacrosse/sensor.py
# flake8: noqa from pandas.core.reshape.concat import concat from pandas.core.reshape.melt import lreshape, melt, wide_to_long from pandas.core.reshape.merge import merge, merge_asof, merge_ordered from pandas.core.reshape.pivot import crosstab, pivot, pivot_table from pandas.core.reshape.reshape import get_dummies from pandas.core.reshape.tile import cut, qcut
import numpy as np import pytest from pandas import Index, MultiIndex import pandas._testing as tm class TestIndexConstructor: # Tests for the Index constructor, specifically for cases that do # not return a subclass @pytest.mark.parametrize("value", [1, np.int64(1)]) def test_constructor_corner(self, value): # corner case msg = ( r"Index\(\.\.\.\) must be called with a collection of some " f"kind, {value} was passed" ) with pytest.raises(TypeError, match=msg): Index(value) @pytest.mark.parametrize("index_vals", [[("A", 1), "B"], ["B", ("A", 1)]]) def test_construction_list_mixed_tuples(self, index_vals): # see gh-10697: if we are constructing from a mixed list of tuples, # make sure that we are independent of the sorting order. index = Index(index_vals) assert isinstance(index, Index) assert not isinstance(index, MultiIndex) def test_constructor_wrong_kwargs(self): # GH #19348 with pytest.raises(TypeError, match="Unexpected keyword arguments {'foo'}"): with tm.assert_produces_warning(FutureWarning): Index([], foo="bar") @pytest.mark.xfail(reason="see GH#21311: Index doesn't enforce dtype argument") def test_constructor_cast(self): msg = "could not convert string to float" with pytest.raises(ValueError, match=msg): Index(["a", "b", "c"], dtype=float)
gfyoung/pandas
pandas/tests/indexes/base_class/test_constructors.py
pandas/core/reshape/api.py
from pandas.core.arrays.base import ( ExtensionArray, ExtensionOpsMixin, ExtensionScalarOpsMixin, ) from pandas.core.arrays.boolean import BooleanArray from pandas.core.arrays.categorical import Categorical from pandas.core.arrays.datetimes import DatetimeArray from pandas.core.arrays.floating import FloatingArray from pandas.core.arrays.integer import IntegerArray from pandas.core.arrays.interval import IntervalArray from pandas.core.arrays.masked import BaseMaskedArray from pandas.core.arrays.numpy_ import PandasArray, PandasDtype from pandas.core.arrays.period import PeriodArray, period_array from pandas.core.arrays.sparse import SparseArray from pandas.core.arrays.string_ import StringArray from pandas.core.arrays.timedeltas import TimedeltaArray __all__ = [ "ExtensionArray", "ExtensionOpsMixin", "ExtensionScalarOpsMixin", "BaseMaskedArray", "BooleanArray", "Categorical", "DatetimeArray", "FloatingArray", "IntegerArray", "IntervalArray", "PandasArray", "PandasDtype", "PeriodArray", "period_array", "SparseArray", "StringArray", "TimedeltaArray", ]
import numpy as np import pytest from pandas import Index, MultiIndex import pandas._testing as tm class TestIndexConstructor: # Tests for the Index constructor, specifically for cases that do # not return a subclass @pytest.mark.parametrize("value", [1, np.int64(1)]) def test_constructor_corner(self, value): # corner case msg = ( r"Index\(\.\.\.\) must be called with a collection of some " f"kind, {value} was passed" ) with pytest.raises(TypeError, match=msg): Index(value) @pytest.mark.parametrize("index_vals", [[("A", 1), "B"], ["B", ("A", 1)]]) def test_construction_list_mixed_tuples(self, index_vals): # see gh-10697: if we are constructing from a mixed list of tuples, # make sure that we are independent of the sorting order. index = Index(index_vals) assert isinstance(index, Index) assert not isinstance(index, MultiIndex) def test_constructor_wrong_kwargs(self): # GH #19348 with pytest.raises(TypeError, match="Unexpected keyword arguments {'foo'}"): with tm.assert_produces_warning(FutureWarning): Index([], foo="bar") @pytest.mark.xfail(reason="see GH#21311: Index doesn't enforce dtype argument") def test_constructor_cast(self): msg = "could not convert string to float" with pytest.raises(ValueError, match=msg): Index(["a", "b", "c"], dtype=float)
gfyoung/pandas
pandas/tests/indexes/base_class/test_constructors.py
pandas/core/arrays/__init__.py
# Authors: Adam Li <adam2392@gmail.com> # Alex Rockhill <aprockhill@mailbox.org> # License: BSD Style. from functools import partial from ...utils import verbose from ..utils import (has_dataset, _data_path, _data_path_doc, _get_version, _version_doc) has_epilepsy_ecog_data = partial(has_dataset, name='epilepsy_ecog') @verbose def data_path( path=None, force_update=False, update_path=True, download=True, verbose=None): # noqa: D103 return _data_path(path=path, force_update=force_update, update_path=update_path, name='epilepsy_ecog', download=download) data_path.__doc__ = _data_path_doc.format( name='epilepsy_ecog', conf='MNE_DATASETS_EPILEPSY_ECOG_PATH') def get_version(): # noqa: D103 return _get_version('epilepsy_ecog') get_version.__doc__ = _version_doc.format(name='epilepsy_ecog')
from itertools import product import datetime import os.path as op import numpy as np from numpy.testing import (assert_array_equal, assert_equal, assert_allclose) import pytest import matplotlib.pyplot as plt import mne from mne import (Epochs, read_events, pick_types, create_info, EpochsArray, Info, Transform) from mne.io import read_raw_fif from mne.utils import (requires_h5py, requires_pandas, grand_average, catch_logging) from mne.time_frequency.tfr import (morlet, tfr_morlet, _make_dpss, tfr_multitaper, AverageTFR, read_tfrs, write_tfrs, combine_tfr, cwt, _compute_tfr, EpochsTFR) from mne.time_frequency import tfr_array_multitaper, tfr_array_morlet from mne.viz.utils import _fake_click from mne.tests.test_epochs import assert_metadata_equal data_path = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data') raw_fname = op.join(data_path, 'test_raw.fif') event_fname = op.join(data_path, 'test-eve.fif') raw_ctf_fname = op.join(data_path, 'test_ctf_raw.fif') def test_tfr_ctf(): """Test that TFRs can be calculated on CTF data.""" raw = read_raw_fif(raw_ctf_fname).crop(0, 1) raw.apply_gradient_compensation(3) events = mne.make_fixed_length_events(raw, duration=0.5) epochs = mne.Epochs(raw, events) for method in (tfr_multitaper, tfr_morlet): method(epochs, [10], 1) # smoke test def test_morlet(): """Test morlet with and without zero mean.""" Wz = morlet(1000, [10], 2., zero_mean=True) W = morlet(1000, [10], 2., zero_mean=False) assert (np.abs(np.mean(np.real(Wz[0]))) < 1e-5) assert (np.abs(np.mean(np.real(W[0]))) > 1e-3) def test_time_frequency(): """Test time-frequency transform (PSD and ITC).""" # Set parameters event_id = 1 tmin = -0.2 tmax = 0.498 # Allows exhaustive decimation testing # Setup for reading the raw data raw = read_raw_fif(raw_fname) events = read_events(event_fname) include = [] exclude = raw.info['bads'] + ['MEG 2443', 'EEG 053'] # bads + 2 more # picks MEG gradiometers picks = pick_types(raw.info, meg='grad', eeg=False, stim=False, include=include, exclude=exclude) picks = picks[:2] epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks) data = epochs.get_data() times = epochs.times nave = len(data) epochs_nopicks = Epochs(raw, events, event_id, tmin, tmax) freqs = np.arange(6, 20, 5) # define frequencies of interest n_cycles = freqs / 4. # Test first with a single epoch power, itc = tfr_morlet(epochs[0], freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=True) # Now compute evoked evoked = epochs.average() pytest.raises(ValueError, tfr_morlet, evoked, freqs, 1., return_itc=True) power, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=True) power_, itc_ = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=True, decim=slice(0, 2)) # Test picks argument and average parameter pytest.raises(ValueError, tfr_morlet, epochs, freqs=freqs, n_cycles=n_cycles, return_itc=True, average=False) power_picks, itc_picks = \ tfr_morlet(epochs_nopicks, freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=True, picks=picks, average=True) epochs_power_picks = \ tfr_morlet(epochs_nopicks, freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=False, picks=picks, average=False) power_picks_avg = epochs_power_picks.average() # the actual data arrays here are equivalent, too... assert_allclose(power.data, power_picks.data) assert_allclose(power.data, power_picks_avg.data) assert_allclose(itc.data, itc_picks.data) # test on evoked power_evoked = tfr_morlet(evoked, freqs, n_cycles, use_fft=True, return_itc=False) # one is squared magnitude of the average (evoked) and # the other is average of the squared magnitudes (epochs PSD) # so values shouldn't match, but shapes should assert_array_equal(power.data.shape, power_evoked.data.shape) pytest.raises(AssertionError, assert_allclose, power.data, power_evoked.data) # complex output pytest.raises(ValueError, tfr_morlet, epochs, freqs, n_cycles, return_itc=False, average=True, output="complex") pytest.raises(ValueError, tfr_morlet, epochs, freqs, n_cycles, output="complex", average=False, return_itc=True) epochs_power_complex = tfr_morlet(epochs, freqs, n_cycles, output="complex", average=False, return_itc=False) epochs_amplitude_2 = abs(epochs_power_complex) epochs_amplitude_3 = epochs_amplitude_2.copy() epochs_amplitude_3.data[:] = np.inf # test that it's actually copied # test that the power computed via `complex` is equivalent to power # computed within the method. assert_allclose(epochs_amplitude_2.data**2, epochs_power_picks.data) print(itc) # test repr print(itc.ch_names) # test property itc += power # test add itc -= power # test sub ret = itc * 23 # test mult itc = ret / 23 # test dic power = power.apply_baseline(baseline=(-0.1, 0), mode='logratio') assert 'meg' in power assert 'grad' in power assert 'mag' not in power assert 'eeg' not in power assert power.nave == nave assert itc.nave == nave assert (power.data.shape == (len(picks), len(freqs), len(times))) assert (power.data.shape == itc.data.shape) assert (power_.data.shape == (len(picks), len(freqs), 2)) assert (power_.data.shape == itc_.data.shape) assert (np.sum(itc.data >= 1) == 0) assert (np.sum(itc.data <= 0) == 0) # grand average itc2 = itc.copy() itc2.info['bads'] = [itc2.ch_names[0]] # test channel drop gave = grand_average([itc2, itc]) assert gave.data.shape == (itc2.data.shape[0] - 1, itc2.data.shape[1], itc2.data.shape[2]) assert itc2.ch_names[1:] == gave.ch_names assert gave.nave == 2 itc2.drop_channels(itc2.info["bads"]) assert_allclose(gave.data, itc2.data) itc2.data = np.ones(itc2.data.shape) itc.data = np.zeros(itc.data.shape) itc2.nave = 2 itc.nave = 1 itc.drop_channels([itc.ch_names[0]]) combined_itc = combine_tfr([itc2, itc]) assert_allclose(combined_itc.data, np.ones(combined_itc.data.shape) * 2 / 3) # more tests power, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=2, use_fft=False, return_itc=True) assert (power.data.shape == (len(picks), len(freqs), len(times))) assert (power.data.shape == itc.data.shape) assert (np.sum(itc.data >= 1) == 0) assert (np.sum(itc.data <= 0) == 0) tfr = tfr_morlet(epochs[0], freqs, use_fft=True, n_cycles=2, average=False, return_itc=False) tfr_data = tfr.data[0] assert (tfr_data.shape == (len(picks), len(freqs), len(times))) tfr2 = tfr_morlet(epochs[0], freqs, use_fft=True, n_cycles=2, decim=slice(0, 2), average=False, return_itc=False).data[0] assert (tfr2.shape == (len(picks), len(freqs), 2)) single_power = tfr_morlet(epochs, freqs, 2, average=False, return_itc=False).data single_power2 = tfr_morlet(epochs, freqs, 2, decim=slice(0, 2), average=False, return_itc=False).data single_power3 = tfr_morlet(epochs, freqs, 2, decim=slice(1, 3), average=False, return_itc=False).data single_power4 = tfr_morlet(epochs, freqs, 2, decim=slice(2, 4), average=False, return_itc=False).data assert_allclose(np.mean(single_power, axis=0), power.data) assert_allclose(np.mean(single_power2, axis=0), power.data[:, :, :2]) assert_allclose(np.mean(single_power3, axis=0), power.data[:, :, 1:3]) assert_allclose(np.mean(single_power4, axis=0), power.data[:, :, 2:4]) power_pick = power.pick_channels(power.ch_names[:10:2]) assert_equal(len(power_pick.ch_names), len(power.ch_names[:10:2])) assert_equal(power_pick.data.shape[0], len(power.ch_names[:10:2])) power_drop = power.drop_channels(power.ch_names[1:10:2]) assert_equal(power_drop.ch_names, power_pick.ch_names) assert_equal(power_pick.data.shape[0], len(power_drop.ch_names)) power_pick, power_drop = mne.equalize_channels([power_pick, power_drop]) assert_equal(power_pick.ch_names, power_drop.ch_names) assert_equal(power_pick.data.shape, power_drop.data.shape) # Test decimation: # 2: multiple of len(times) even # 3: multiple odd # 8: not multiple, even # 9: not multiple, odd for decim in [2, 3, 8, 9]: for use_fft in [True, False]: power, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=2, use_fft=use_fft, return_itc=True, decim=decim) assert_equal(power.data.shape[2], np.ceil(float(len(times)) / decim)) freqs = list(range(50, 55)) decim = 2 _, n_chan, n_time = data.shape tfr = tfr_morlet(epochs[0], freqs, 2., decim=decim, average=False, return_itc=False).data[0] assert_equal(tfr.shape, (n_chan, len(freqs), n_time // decim)) # Test cwt modes Ws = morlet(512, [10, 20], n_cycles=2) pytest.raises(ValueError, cwt, data[0, :, :], Ws, mode='foo') for use_fft in [True, False]: for mode in ['same', 'valid', 'full']: cwt(data[0], Ws, use_fft=use_fft, mode=mode) # Test invalid frequency arguments with pytest.raises(ValueError, match=" 'freqs' must be greater than 0"): tfr_morlet(epochs, freqs=np.arange(0, 3), n_cycles=7) with pytest.raises(ValueError, match=" 'freqs' must be greater than 0"): tfr_morlet(epochs, freqs=np.arange(-4, -1), n_cycles=7) # Test decim parameter checks pytest.raises(TypeError, tfr_morlet, epochs, freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=True, decim='decim') # When convolving in time, wavelets must not be longer than the data pytest.raises(ValueError, cwt, data[0, :, :Ws[0].size - 1], Ws, use_fft=False) with pytest.warns(UserWarning, match='one of the wavelets.*is longer'): cwt(data[0, :, :Ws[0].size - 1], Ws, use_fft=True) # Check for off-by-one errors when using wavelets with an even number of # samples psd = cwt(data[0], [Ws[0][:-1]], use_fft=False, mode='full') assert_equal(psd.shape, (2, 1, 420)) def test_dpsswavelet(): """Test DPSS tapers.""" freqs = np.arange(5, 25, 3) Ws = _make_dpss(1000, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, zero_mean=True) assert (len(Ws) == 3) # 3 tapers expected # Check that zero mean is true assert (np.abs(np.mean(np.real(Ws[0][0]))) < 1e-5) assert (len(Ws[0]) == len(freqs)) # As many wavelets as asked for @pytest.mark.slowtest def test_tfr_multitaper(): """Test tfr_multitaper.""" sfreq = 200.0 ch_names = ['SIM0001', 'SIM0002'] ch_types = ['grad', 'grad'] info = create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types) n_times = int(sfreq) # Second long epochs n_epochs = 3 seed = 42 rng = np.random.RandomState(seed) noise = 0.1 * rng.randn(n_epochs, len(ch_names), n_times) t = np.arange(n_times, dtype=np.float64) / sfreq signal = np.sin(np.pi * 2. * 50. * t) # 50 Hz sinusoid signal signal[np.logical_or(t < 0.45, t > 0.55)] = 0. # Hard windowing on_time = np.logical_and(t >= 0.45, t <= 0.55) signal[on_time] *= np.hanning(on_time.sum()) # Ramping dat = noise + signal reject = dict(grad=4000.) events = np.empty((n_epochs, 3), int) first_event_sample = 100 event_id = dict(sin50hz=1) for k in range(n_epochs): events[k, :] = first_event_sample + k * n_times, 0, event_id['sin50hz'] epochs = EpochsArray(data=dat, info=info, events=events, event_id=event_id, reject=reject) freqs = np.arange(35, 70, 5, dtype=np.float64) power, itc = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0) power2, itc2 = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, decim=slice(0, 2)) picks = np.arange(len(ch_names)) power_picks, itc_picks = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, picks=picks) power_epochs = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, return_itc=False, average=False) power_averaged = power_epochs.average() power_evoked = tfr_multitaper(epochs.average(), freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, return_itc=False, average=False).average() print(power_evoked) # test repr for EpochsTFR # Test channel picking power_epochs_picked = power_epochs.copy().drop_channels(['SIM0002']) assert_equal(power_epochs_picked.data.shape, (3, 1, 7, 200)) assert_equal(power_epochs_picked.ch_names, ['SIM0001']) pytest.raises(ValueError, tfr_multitaper, epochs, freqs=freqs, n_cycles=freqs / 2., return_itc=True, average=False) # test picks argument assert_allclose(power.data, power_picks.data) assert_allclose(power.data, power_averaged.data) assert_allclose(power.times, power_epochs.times) assert_allclose(power.times, power_averaged.times) assert_equal(power.nave, power_averaged.nave) assert_equal(power_epochs.data.shape, (3, 2, 7, 200)) assert_allclose(itc.data, itc_picks.data) # one is squared magnitude of the average (evoked) and # the other is average of the squared magnitudes (epochs PSD) # so values shouldn't match, but shapes should assert_array_equal(power.data.shape, power_evoked.data.shape) pytest.raises(AssertionError, assert_allclose, power.data, power_evoked.data) tmax = t[np.argmax(itc.data[0, freqs == 50, :])] fmax = freqs[np.argmax(power.data[1, :, t == 0.5])] assert (tmax > 0.3 and tmax < 0.7) assert not np.any(itc.data < 0.) assert (fmax > 40 and fmax < 60) assert (power2.data.shape == (len(picks), len(freqs), 2)) assert (power2.data.shape == itc2.data.shape) # Test decim parameter checks and compatibility between wavelets length # and instance length in the time dimension. pytest.raises(TypeError, tfr_multitaper, epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, decim=(1,)) pytest.raises(ValueError, tfr_multitaper, epochs, freqs=freqs, n_cycles=1000, time_bandwidth=4.0) # Test invalid frequency arguments with pytest.raises(ValueError, match=" 'freqs' must be greater than 0"): tfr_multitaper(epochs, freqs=np.arange(0, 3), n_cycles=7) with pytest.raises(ValueError, match=" 'freqs' must be greater than 0"): tfr_multitaper(epochs, freqs=np.arange(-4, -1), n_cycles=7) def test_crop(): """Test TFR cropping.""" data = np.zeros((3, 4, 5)) times = np.array([.1, .2, .3, .4, .5]) freqs = np.array([.10, .20, .30, .40]) info = mne.create_info(['MEG 001', 'MEG 002', 'MEG 003'], 1000., ['mag', 'mag', 'mag']) tfr = AverageTFR(info, data=data, times=times, freqs=freqs, nave=20, comment='test', method='crazy-tfr') tfr.crop(tmin=0.2) assert_array_equal(tfr.times, [0.2, 0.3, 0.4, 0.5]) assert tfr.data.ndim == 3 assert tfr.data.shape[-1] == 4 tfr.crop(fmax=0.3) assert_array_equal(tfr.freqs, [0.1, 0.2, 0.3]) assert tfr.data.ndim == 3 assert tfr.data.shape[-2] == 3 tfr.crop(tmin=0.3, tmax=0.4, fmin=0.1, fmax=0.2) assert_array_equal(tfr.times, [0.3, 0.4]) assert tfr.data.ndim == 3 assert tfr.data.shape[-1] == 2 assert_array_equal(tfr.freqs, [0.1, 0.2]) assert tfr.data.shape[-2] == 2 @requires_h5py @requires_pandas def test_io(tmpdir): """Test TFR IO capacities.""" from pandas import DataFrame tempdir = str(tmpdir) fname = op.join(tempdir, 'test-tfr.h5') data = np.zeros((3, 2, 3)) times = np.array([.1, .2, .3]) freqs = np.array([.10, .20]) info = mne.create_info(['MEG 001', 'MEG 002', 'MEG 003'], 1000., ['mag', 'mag', 'mag']) info['meas_date'] = datetime.datetime(year=2020, month=2, day=5, tzinfo=datetime.timezone.utc) info._check_consistency() tfr = AverageTFR(info, data=data, times=times, freqs=freqs, nave=20, comment='test', method='crazy-tfr') tfr.save(fname) tfr2 = read_tfrs(fname, condition='test') assert isinstance(tfr2.info, Info) assert isinstance(tfr2.info['dev_head_t'], Transform) assert_array_equal(tfr.data, tfr2.data) assert_array_equal(tfr.times, tfr2.times) assert_array_equal(tfr.freqs, tfr2.freqs) assert_equal(tfr.comment, tfr2.comment) assert_equal(tfr.nave, tfr2.nave) pytest.raises(IOError, tfr.save, fname) tfr.comment = None # test old meas_date info['meas_date'] = (1, 2) tfr.save(fname, overwrite=True) assert_equal(read_tfrs(fname, condition=0).comment, tfr.comment) tfr.comment = 'test-A' tfr2.comment = 'test-B' fname = op.join(tempdir, 'test2-tfr.h5') write_tfrs(fname, [tfr, tfr2]) tfr3 = read_tfrs(fname, condition='test-A') assert_equal(tfr.comment, tfr3.comment) assert (isinstance(tfr.info, mne.Info)) tfrs = read_tfrs(fname, condition=None) assert_equal(len(tfrs), 2) tfr4 = tfrs[1] assert_equal(tfr2.comment, tfr4.comment) pytest.raises(ValueError, read_tfrs, fname, condition='nonono') # Test save of EpochsTFR. n_events = 5 data = np.zeros((n_events, 3, 2, 3)) # create fake metadata rng = np.random.RandomState(42) rt = np.round(rng.uniform(size=(n_events,)), 3) trialtypes = np.array(['face', 'place']) trial = trialtypes[(rng.uniform(size=(n_events,)) > .5).astype(int)] meta = DataFrame(dict(RT=rt, Trial=trial)) # fake events and event_id events = np.zeros([n_events, 3]) events[:, 0] = np.arange(n_events) events[:, 2] = np.ones(n_events) event_id = {'a/b': 1} # fake selection n_dropped_epochs = 3 selection = np.arange(n_events + n_dropped_epochs)[n_dropped_epochs:] drop_log = tuple([('IGNORED',) for i in range(n_dropped_epochs)] + [() for i in range(n_events)]) tfr = EpochsTFR(info, data=data, times=times, freqs=freqs, comment='test', method='crazy-tfr', events=events, event_id=event_id, selection=selection, drop_log=drop_log, metadata=meta) fname_save = fname tfr.save(fname_save, True) fname_write = op.join(tempdir, 'test3-tfr.h5') write_tfrs(fname_write, tfr, overwrite=True) for fname in [fname_save, fname_write]: read_tfr = read_tfrs(fname)[0] assert_array_equal(tfr.data, read_tfr.data) assert_metadata_equal(tfr.metadata, read_tfr.metadata) assert_array_equal(tfr.events, read_tfr.events) assert tfr.event_id == read_tfr.event_id assert_array_equal(tfr.selection, read_tfr.selection) assert tfr.drop_log == read_tfr.drop_log with pytest.raises(NotImplementedError, match='condition not supported'): tfr = read_tfrs(fname, condition='a') def test_init_EpochsTFR(): """Test __init__ for EpochsTFR.""" # Create fake data: data = np.zeros((3, 3, 3, 3)) times = np.array([.1, .2, .3]) freqs = np.array([.10, .20, .30]) info = mne.create_info(['MEG 001', 'MEG 002', 'MEG 003'], 1000., ['mag', 'mag', 'mag']) data_x = data[:, :, :, 0] with pytest.raises(ValueError, match='data should be 4d. Got 3'): tfr = EpochsTFR(info, data=data_x, times=times, freqs=freqs) data_x = data[:, :-1, :, :] with pytest.raises(ValueError, match="channels and data size don't"): tfr = EpochsTFR(info, data=data_x, times=times, freqs=freqs) times_x = times[:-1] with pytest.raises(ValueError, match="times and data size don't match"): tfr = EpochsTFR(info, data=data, times=times_x, freqs=freqs) freqs_x = freqs[:-1] with pytest.raises(ValueError, match="frequencies and data size don't"): tfr = EpochsTFR(info, data=data, times=times_x, freqs=freqs_x) del(tfr) def test_plot(): """Test TFR plotting.""" data = np.zeros((3, 2, 3)) times = np.array([.1, .2, .3]) freqs = np.array([.10, .20]) info = mne.create_info(['MEG 001', 'MEG 002', 'MEG 003'], 1000., ['mag', 'mag', 'mag']) tfr = AverageTFR(info, data=data, times=times, freqs=freqs, nave=20, comment='test', method='crazy-tfr') # test title=auto, combine=None, and correct length of figure list picks = [1, 2] figs = tfr.plot(picks, title='auto', colorbar=False, mask=np.ones(tfr.data.shape[1:], bool)) assert len(figs) == len(picks) assert 'MEG' in figs[0].texts[0].get_text() plt.close('all') # test combine and title keyword figs = tfr.plot(picks, title='title', colorbar=False, combine='rms', mask=np.ones(tfr.data.shape[1:], bool)) assert len(figs) == 1 assert figs[0].texts[0].get_text() == 'title' figs = tfr.plot(picks, title='auto', colorbar=False, combine='mean', mask=np.ones(tfr.data.shape[1:], bool)) assert len(figs) == 1 assert figs[0].texts[0].get_text() == 'Mean of 2 sensors' with pytest.raises(ValueError, match='combine must be None'): tfr.plot(picks, colorbar=False, combine='something', mask=np.ones(tfr.data.shape[1:], bool)) plt.close('all') # test axes argument - first with list of axes ax = plt.subplot2grid((2, 2), (0, 0)) ax2 = plt.subplot2grid((2, 2), (0, 1)) ax3 = plt.subplot2grid((2, 2), (1, 0)) figs = tfr.plot(picks=[0, 1, 2], axes=[ax, ax2, ax3]) assert len(figs) == len([ax, ax2, ax3]) # and as a single axes figs = tfr.plot(picks=[0], axes=ax) assert len(figs) == 1 plt.close('all') # and invalid inputs with pytest.raises(ValueError, match='axes must be None'): tfr.plot(picks, colorbar=False, axes={}, mask=np.ones(tfr.data.shape[1:], bool)) # different number of axes and picks should throw a RuntimeError with pytest.raises(RuntimeError, match='There must be an axes'): tfr.plot(picks=[0], colorbar=False, axes=[ax, ax2], mask=np.ones(tfr.data.shape[1:], bool)) tfr.plot_topo(picks=[1, 2]) plt.close('all') # interactive mode on by default fig = tfr.plot(picks=[1], cmap='RdBu_r')[0] fig.canvas.key_press_event('up') fig.canvas.key_press_event(' ') fig.canvas.key_press_event('down') fig.canvas.key_press_event(' ') fig.canvas.key_press_event('+') fig.canvas.key_press_event(' ') fig.canvas.key_press_event('-') fig.canvas.key_press_event(' ') fig.canvas.key_press_event('pageup') fig.canvas.key_press_event(' ') fig.canvas.key_press_event('pagedown') cbar = fig.get_axes()[0].CB # Fake dragging with mouse. ax = cbar.cbar.ax _fake_click(fig, ax, (0.1, 0.1)) _fake_click(fig, ax, (0.1, 0.2), kind='motion') _fake_click(fig, ax, (0.1, 0.3), kind='release') _fake_click(fig, ax, (0.1, 0.1), button=3) _fake_click(fig, ax, (0.1, 0.2), button=3, kind='motion') _fake_click(fig, ax, (0.1, 0.3), kind='release') fig.canvas.scroll_event(0.5, 0.5, -0.5) # scroll down fig.canvas.scroll_event(0.5, 0.5, 0.5) # scroll up plt.close('all') def test_plot_joint(): """Test TFR joint plotting.""" raw = read_raw_fif(raw_fname) times = np.linspace(-0.1, 0.1, 200) n_freqs = 3 nave = 1 rng = np.random.RandomState(42) data = rng.randn(len(raw.ch_names), n_freqs, len(times)) tfr = AverageTFR(raw.info, data, times, np.arange(n_freqs), nave) topomap_args = {'res': 8, 'contours': 0, 'sensors': False} for combine in ('mean', 'rms'): with catch_logging() as log: tfr.plot_joint(title='auto', colorbar=True, combine=combine, topomap_args=topomap_args, verbose='debug') plt.close('all') log = log.getvalue() assert 'Plotting topomap for grad data' in log # check various timefreqs for timefreqs in ( {(tfr.times[0], tfr.freqs[1]): (0.1, 0.5), (tfr.times[-1], tfr.freqs[-1]): (0.2, 0.6)}, [(tfr.times[1], tfr.freqs[1])]): tfr.plot_joint(timefreqs=timefreqs, topomap_args=topomap_args) plt.close('all') # test bad timefreqs timefreqs = ([(-100, 1)], tfr.times[1], [1], [(tfr.times[1], tfr.freqs[1], tfr.freqs[1])]) for these_timefreqs in timefreqs: pytest.raises(ValueError, tfr.plot_joint, these_timefreqs) # test that the object is not internally modified tfr_orig = tfr.copy() tfr.plot_joint(baseline=(0, None), exclude=[tfr.ch_names[0]], topomap_args=topomap_args) plt.close('all') assert_array_equal(tfr.data, tfr_orig.data) assert set(tfr.ch_names) == set(tfr_orig.ch_names) assert set(tfr.times) == set(tfr_orig.times) # test tfr with picked channels tfr.pick_channels(tfr.ch_names[:-1]) tfr.plot_joint(title='auto', colorbar=True, topomap_args=topomap_args) def test_add_channels(): """Test tfr splitting / re-appending channel types.""" data = np.zeros((6, 2, 3)) times = np.array([.1, .2, .3]) freqs = np.array([.10, .20]) info = mne.create_info( ['MEG 001', 'MEG 002', 'MEG 003', 'EEG 001', 'EEG 002', 'STIM 001'], 1000., ['mag', 'mag', 'mag', 'eeg', 'eeg', 'stim']) tfr = AverageTFR(info, data=data, times=times, freqs=freqs, nave=20, comment='test', method='crazy-tfr') tfr_eeg = tfr.copy().pick_types(meg=False, eeg=True) tfr_meg = tfr.copy().pick_types(meg=True) tfr_stim = tfr.copy().pick_types(meg=False, stim=True) tfr_eeg_meg = tfr.copy().pick_types(meg=True, eeg=True) tfr_new = tfr_meg.copy().add_channels([tfr_eeg, tfr_stim]) assert all(ch in tfr_new.ch_names for ch in tfr_stim.ch_names + tfr_meg.ch_names) tfr_new = tfr_meg.copy().add_channels([tfr_eeg]) have_all = all(ch in tfr_new.ch_names for ch in tfr.ch_names if ch != 'STIM 001') assert have_all assert_array_equal(tfr_new.data, tfr_eeg_meg.data) assert all(ch not in tfr_new.ch_names for ch in tfr_stim.ch_names) # Now test errors tfr_badsf = tfr_eeg.copy() tfr_badsf.info['sfreq'] = 3.1415927 tfr_eeg = tfr_eeg.crop(-.1, .1) pytest.raises(RuntimeError, tfr_meg.add_channels, [tfr_badsf]) pytest.raises(AssertionError, tfr_meg.add_channels, [tfr_eeg]) pytest.raises(ValueError, tfr_meg.add_channels, [tfr_meg]) pytest.raises(TypeError, tfr_meg.add_channels, tfr_badsf) def test_compute_tfr(): """Test _compute_tfr function.""" # Set parameters event_id = 1 tmin = -0.2 tmax = 0.498 # Allows exhaustive decimation testing # Setup for reading the raw data raw = read_raw_fif(raw_fname) events = read_events(event_fname) exclude = raw.info['bads'] + ['MEG 2443', 'EEG 053'] # bads + 2 more # picks MEG gradiometers picks = pick_types(raw.info, meg='grad', eeg=False, stim=False, include=[], exclude=exclude) picks = picks[:2] epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks) data = epochs.get_data() sfreq = epochs.info['sfreq'] freqs = np.arange(10, 20, 3).astype(float) # Check all combination of options for func, use_fft, zero_mean, output in product( (tfr_array_multitaper, tfr_array_morlet), (False, True), (False, True), ('complex', 'power', 'phase', 'avg_power_itc', 'avg_power', 'itc')): # Check exception if (func == tfr_array_multitaper) and (output == 'phase'): pytest.raises(NotImplementedError, func, data, sfreq=sfreq, freqs=freqs, output=output) continue # Check runs out = func(data, sfreq=sfreq, freqs=freqs, use_fft=use_fft, zero_mean=zero_mean, n_cycles=2., output=output) # Check shapes shape = np.r_[data.shape[:2], len(freqs), data.shape[2]] if ('avg' in output) or ('itc' in output): assert_array_equal(shape[1:], out.shape) else: assert_array_equal(shape, out.shape) # Check types if output in ('complex', 'avg_power_itc'): assert_equal(np.complex128, out.dtype) else: assert_equal(np.float64, out.dtype) assert (np.all(np.isfinite(out))) # Check errors params for _data in (None, 'foo', data[0]): pytest.raises(ValueError, _compute_tfr, _data, freqs, sfreq) for _freqs in (None, 'foo', [[0]]): pytest.raises(ValueError, _compute_tfr, data, _freqs, sfreq) for _sfreq in (None, 'foo'): pytest.raises(ValueError, _compute_tfr, data, freqs, _sfreq) for key in ('output', 'method', 'use_fft', 'decim', 'n_jobs'): for value in (None, 'foo'): kwargs = {key: value} # FIXME pep8 pytest.raises(ValueError, _compute_tfr, data, freqs, sfreq, **kwargs) with pytest.raises(ValueError, match='above Nyquist'): _compute_tfr(data, [sfreq], sfreq) # No time_bandwidth param in morlet pytest.raises(ValueError, _compute_tfr, data, freqs, sfreq, method='morlet', time_bandwidth=1) # No phase in multitaper XXX Check ? pytest.raises(NotImplementedError, _compute_tfr, data, freqs, sfreq, method='multitaper', output='phase') # Inter-trial coherence tests out = _compute_tfr(data, freqs, sfreq, output='itc', n_cycles=2.) assert np.sum(out >= 1) == 0 assert np.sum(out <= 0) == 0 # Check decim shapes # 2: multiple of len(times) even # 3: multiple odd # 8: not multiple, even # 9: not multiple, odd for decim in (2, 3, 8, 9, slice(0, 2), slice(1, 3), slice(2, 4)): _decim = slice(None, None, decim) if isinstance(decim, int) else decim n_time = len(np.arange(data.shape[2])[_decim]) shape = np.r_[data.shape[:2], len(freqs), n_time] for method in ('multitaper', 'morlet'): # Single trials out = _compute_tfr(data, freqs, sfreq, method=method, decim=decim, n_cycles=2.) assert_array_equal(shape, out.shape) # Averages out = _compute_tfr(data, freqs, sfreq, method=method, decim=decim, output='avg_power', n_cycles=2.) assert_array_equal(shape[1:], out.shape) @pytest.mark.parametrize('method', ('multitaper', 'morlet')) @pytest.mark.parametrize('decim', (1, slice(1, None, 2), 3)) def test_compute_tfr_correct(method, decim): """Test that TFR actually gets us our freq back.""" sfreq = 1000. t = np.arange(1000) / sfreq f = 50. data = np.sin(2 * np.pi * 50. * t) data *= np.hanning(data.size) data = data[np.newaxis, np.newaxis] freqs = np.arange(10, 111, 10) assert f in freqs tfr = _compute_tfr(data, freqs, sfreq, method=method, decim=decim, n_cycles=2)[0, 0] assert freqs[np.argmax(np.abs(tfr).mean(-1))] == f def test_averaging_epochsTFR(): """Test that EpochsTFR averaging methods work.""" # Setup for reading the raw data event_id = 1 tmin = -0.2 tmax = 0.498 # Allows exhaustive decimation testing freqs = np.arange(6, 20, 5) # define frequencies of interest n_cycles = freqs / 4. raw = read_raw_fif(raw_fname) # only pick a few events for speed events = read_events(event_fname)[:4] include = [] exclude = raw.info['bads'] + ['MEG 2443', 'EEG 053'] # bads + 2 more # picks MEG gradiometers picks = pick_types(raw.info, meg='grad', eeg=False, stim=False, include=include, exclude=exclude) picks = picks[:2] epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks) # Obtain EpochsTFR power = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, average=False, use_fft=True, return_itc=False) # Test average methods for func, method in zip( [np.mean, np.median, np.mean], ['mean', 'median', lambda x: np.mean(x, axis=0)]): avgpower = power.average(method=method) np.testing.assert_array_equal(func(power.data, axis=0), avgpower.data) with pytest.raises(RuntimeError, match='You passed a function that ' 'resulted in data'): power.average(method=np.mean) @requires_pandas def test_getitem_epochsTFR(): """Test GetEpochsMixin in the context of EpochsTFR.""" from pandas import DataFrame # Setup for reading the raw data and select a few trials raw = read_raw_fif(raw_fname) events = read_events(event_fname) # create fake data, test with and without dropping epochs for n_drop_epochs in [0, 2]: n_events = 12 # create fake metadata rng = np.random.RandomState(42) rt = rng.uniform(size=(n_events,)) trialtypes = np.array(['face', 'place']) trial = trialtypes[(rng.uniform(size=(n_events,)) > .5).astype(int)] meta = DataFrame(dict(RT=rt, Trial=trial)) event_id = dict(a=1, b=2, c=3, d=4) epochs = Epochs(raw, events[:n_events], event_id=event_id, metadata=meta, decim=1) epochs.drop(np.arange(n_drop_epochs)) n_events -= n_drop_epochs freqs = np.arange(12., 17., 2.) # define frequencies of interest n_cycles = freqs / 2. # 0.5 second time windows for all frequencies # Choose time x (full) bandwidth product time_bandwidth = 4.0 # With 0.5 s time windows, this gives 8 Hz smoothing kwargs = dict(freqs=freqs, n_cycles=n_cycles, use_fft=True, time_bandwidth=time_bandwidth, return_itc=False, average=False, n_jobs=1) power = tfr_multitaper(epochs, **kwargs) # Check that power and epochs metadata is the same assert_metadata_equal(epochs.metadata, power.metadata) assert_metadata_equal(epochs[::2].metadata, power[::2].metadata) assert_metadata_equal(epochs['RT < .5'].metadata, power['RT < .5'].metadata) assert_array_equal(epochs.selection, power.selection) assert epochs.drop_log == power.drop_log # Check that get power is functioning assert_array_equal(power[3:6].data, power.data[3:6]) assert_array_equal(power[3:6].events, power.events[3:6]) assert_array_equal(epochs.selection[3:6], power.selection[3:6]) indx_check = (power.metadata['Trial'] == 'face') try: indx_check = indx_check.to_numpy() except Exception: pass # older Pandas indx_check = indx_check.nonzero() assert_array_equal(power['Trial == "face"'].events, power.events[indx_check]) assert_array_equal(power['Trial == "face"'].data, power.data[indx_check]) # Check that the wrong Key generates a Key Error for Metadata search with pytest.raises(KeyError): power['Trialz == "place"'] # Test length function assert len(power) == n_events assert len(power[3:6]) == 3 # Test iteration function for ind, power_ep in enumerate(power): assert_array_equal(power_ep, power.data[ind]) if ind == 5: break # Test that current state is maintained assert_array_equal(power.next(), power.data[ind + 1]) # Check decim affects sfreq power_decim = tfr_multitaper(epochs, decim=2, **kwargs) assert power.info['sfreq'] / 2. == power_decim.info['sfreq'] @requires_pandas def test_to_data_frame(): """Test EpochsTFR Pandas exporter.""" # Create fake EpochsTFR data: n_epos = 3 ch_names = ['EEG 001', 'EEG 002', 'EEG 003', 'EEG 004'] n_picks = len(ch_names) ch_types = ['eeg'] * n_picks n_freqs = 5 n_times = 6 data = np.random.rand(n_epos, n_picks, n_freqs, n_times) times = np.arange(6) srate = 1000. freqs = np.arange(5) events = np.zeros((n_epos, 3), dtype=int) events[:, 0] = np.arange(n_epos) events[:, 2] = np.arange(5, 5 + n_epos) event_id = {k: v for v, k in zip(events[:, 2], ['ha', 'he', 'hu'])} info = mne.create_info(ch_names, srate, ch_types) tfr = mne.time_frequency.EpochsTFR(info, data, times, freqs, events=events, event_id=event_id) # test index checking with pytest.raises(ValueError, match='options. Valid index options are'): tfr.to_data_frame(index=['foo', 'bar']) with pytest.raises(ValueError, match='"qux" is not a valid option'): tfr.to_data_frame(index='qux') with pytest.raises(TypeError, match='index must be `None` or a string '): tfr.to_data_frame(index=np.arange(400)) # test wide format df_wide = tfr.to_data_frame() assert all(np.in1d(tfr.ch_names, df_wide.columns)) assert all(np.in1d(['time', 'condition', 'freq', 'epoch'], df_wide.columns)) # test long format df_long = tfr.to_data_frame(long_format=True) expected = ('condition', 'epoch', 'freq', 'time', 'channel', 'ch_type', 'value') assert set(expected) == set(df_long.columns) assert set(tfr.ch_names) == set(df_long['channel']) assert(len(df_long) == tfr.data.size) # test long format w/ index df_long = tfr.to_data_frame(long_format=True, index=['freq']) del df_wide, df_long # test whether data is in correct shape df = tfr.to_data_frame(index=['condition', 'epoch', 'freq', 'time']) data = tfr.data assert_array_equal(df.values[:, 0], data[:, 0, :, :].reshape(1, -1).squeeze()) # compare arbitrary observation: assert df.loc[('he', slice(None), freqs[1], times[2] * srate), ch_names[3]].iloc[0] == data[1, 3, 1, 2] # Check also for AverageTFR: tfr = tfr.average() with pytest.raises(ValueError, match='options. Valid index options are'): tfr.to_data_frame(index=['epoch', 'condition']) with pytest.raises(ValueError, match='"epoch" is not a valid option'): tfr.to_data_frame(index='epoch') with pytest.raises(TypeError, match='index must be `None` or a string '): tfr.to_data_frame(index=np.arange(400)) # test wide format df_wide = tfr.to_data_frame() assert all(np.in1d(tfr.ch_names, df_wide.columns)) assert all(np.in1d(['time', 'freq'], df_wide.columns)) # test long format df_long = tfr.to_data_frame(long_format=True) expected = ('freq', 'time', 'channel', 'ch_type', 'value') assert set(expected) == set(df_long.columns) assert set(tfr.ch_names) == set(df_long['channel']) assert(len(df_long) == tfr.data.size) # test long format w/ index df_long = tfr.to_data_frame(long_format=True, index=['freq']) del df_wide, df_long # test whether data is in correct shape df = tfr.to_data_frame(index=['freq', 'time']) data = tfr.data assert_array_equal(df.values[:, 0], data[0, :, :].reshape(1, -1).squeeze()) # compare arbitrary observation: assert df.loc[(freqs[1], times[2] * srate), ch_names[3]] == \ data[3, 1, 2] @requires_pandas @pytest.mark.parametrize('index', ('time', ['condition', 'time', 'freq'], ['freq', 'time'], ['time', 'freq'], None)) def test_to_data_frame_index(index): """Test index creation in epochs Pandas exporter.""" # Create fake EpochsTFR data: n_epos = 3 ch_names = ['EEG 001', 'EEG 002', 'EEG 003', 'EEG 004'] n_picks = len(ch_names) ch_types = ['eeg'] * n_picks n_freqs = 5 n_times = 6 data = np.random.rand(n_epos, n_picks, n_freqs, n_times) times = np.arange(6) freqs = np.arange(5) events = np.zeros((n_epos, 3), dtype=int) events[:, 0] = np.arange(n_epos) events[:, 2] = np.arange(5, 8) event_id = {k: v for v, k in zip(events[:, 2], ['ha', 'he', 'hu'])} info = mne.create_info(ch_names, 1000., ch_types) tfr = mne.time_frequency.EpochsTFR(info, data, times, freqs, events=events, event_id=event_id) df = tfr.to_data_frame(picks=[0, 2, 3], index=index) # test index order/hierarchy preservation if not isinstance(index, list): index = [index] assert (df.index.names == index) # test that non-indexed data were present as columns non_index = list(set(['condition', 'time', 'freq', 'epoch']) - set(index)) if len(non_index): assert all(np.in1d(non_index, df.columns)) @requires_pandas @pytest.mark.parametrize('time_format', (None, 'ms', 'timedelta')) def test_to_data_frame_time_format(time_format): """Test time conversion in epochs Pandas exporter.""" from pandas import Timedelta n_epos = 3 ch_names = ['EEG 001', 'EEG 002', 'EEG 003', 'EEG 004'] n_picks = len(ch_names) ch_types = ['eeg'] * n_picks n_freqs = 5 n_times = 6 data = np.random.rand(n_epos, n_picks, n_freqs, n_times) times = np.arange(6) freqs = np.arange(5) events = np.zeros((n_epos, 3), dtype=int) events[:, 0] = np.arange(n_epos) events[:, 2] = np.arange(5, 8) event_id = {k: v for v, k in zip(events[:, 2], ['ha', 'he', 'hu'])} info = mne.create_info(ch_names, 1000., ch_types) tfr = mne.time_frequency.EpochsTFR(info, data, times, freqs, events=events, event_id=event_id) # test time_format df = tfr.to_data_frame(time_format=time_format) dtypes = {None: np.float64, 'ms': np.int64, 'timedelta': Timedelta} assert isinstance(df['time'].iloc[0], dtypes[time_format])
rkmaddox/mne-python
mne/time_frequency/tests/test_tfr.py
mne/datasets/epilepsy_ecog/_data.py
# Authors: Denis A. Engemann <denis.engemann@gmail.com> # Teon Brooks <teon.brooks@gmail.com> # # simplified BSD-3 license import datetime import time import numpy as np from .egimff import _read_raw_egi_mff from .events import _combine_triggers from ..base import BaseRaw from ..utils import _read_segments_file, _create_chs from ..meas_info import _empty_info from ..constants import FIFF from ...utils import verbose, logger, warn, _validate_type, _check_fname def _read_header(fid): """Read EGI binary header.""" version = np.fromfile(fid, '<i4', 1)[0] if version > 6 & ~np.bitwise_and(version, 6): version = version.byteswap().astype(np.uint32) else: raise ValueError('Watchout. This does not seem to be a simple ' 'binary EGI file.') def my_fread(*x, **y): return np.fromfile(*x, **y)[0] info = dict( version=version, year=my_fread(fid, '>i2', 1), month=my_fread(fid, '>i2', 1), day=my_fread(fid, '>i2', 1), hour=my_fread(fid, '>i2', 1), minute=my_fread(fid, '>i2', 1), second=my_fread(fid, '>i2', 1), millisecond=my_fread(fid, '>i4', 1), samp_rate=my_fread(fid, '>i2', 1), n_channels=my_fread(fid, '>i2', 1), gain=my_fread(fid, '>i2', 1), bits=my_fread(fid, '>i2', 1), value_range=my_fread(fid, '>i2', 1) ) unsegmented = 1 if np.bitwise_and(version, 1) == 0 else 0 precision = np.bitwise_and(version, 6) if precision == 0: raise RuntimeError('Floating point precision is undefined.') if unsegmented: info.update(dict(n_categories=0, n_segments=1, n_samples=np.fromfile(fid, '>i4', 1)[0], n_events=np.fromfile(fid, '>i2', 1)[0], event_codes=[], category_names=[], category_lengths=[], pre_baseline=0)) for event in range(info['n_events']): event_codes = ''.join(np.fromfile(fid, 'S1', 4).astype('U1')) info['event_codes'].append(event_codes) else: raise NotImplementedError('Only continuous files are supported') info['unsegmented'] = unsegmented info['dtype'], info['orig_format'] = {2: ('>i2', 'short'), 4: ('>f4', 'float'), 6: ('>f8', 'double')}[precision] info['dtype'] = np.dtype(info['dtype']) return info def _read_events(fid, info): """Read events.""" events = np.zeros([info['n_events'], info['n_segments'] * info['n_samples']]) fid.seek(36 + info['n_events'] * 4, 0) # skip header for si in range(info['n_samples']): # skip data channels fid.seek(info['n_channels'] * info['dtype'].itemsize, 1) # read event channels events[:, si] = np.fromfile(fid, info['dtype'], info['n_events']) return events @verbose def read_raw_egi(input_fname, eog=None, misc=None, include=None, exclude=None, preload=False, channel_naming='E%d', verbose=None): """Read EGI simple binary as raw object. .. note:: This function attempts to create a synthetic trigger channel. See the Notes section below. Parameters ---------- input_fname : path-like Path to the raw file. Files with an extension .mff are automatically considered to be EGI's native MFF format files. eog : list or tuple Names of channels or list of indices that should be designated EOG channels. Default is None. misc : list or tuple Names of channels or list of indices that should be designated MISC channels. Default is None. include : None | list The event channels to be ignored when creating the synthetic trigger. Defaults to None. Note. Overrides ``exclude`` parameter. exclude : None | list The event channels to be ignored when creating the synthetic trigger. Defaults to None. If None, channels that have more than one event and the ``sync`` and ``TREV`` channels will be ignored. %(preload)s .. versionadded:: 0.11 channel_naming : str Channel naming convention for the data channels. Defaults to 'E%%d' (resulting in channel names 'E1', 'E2', 'E3'...). The effective default prior to 0.14.0 was 'EEG %%03d'. .. versionadded:: 0.14.0 %(verbose)s Returns ------- raw : instance of RawEGI A Raw object containing EGI data. See Also -------- mne.io.Raw : Documentation of attribute and methods. Notes ----- The trigger channel names are based on the arbitrary user dependent event codes used. However this function will attempt to generate a **synthetic trigger channel** named ``STI 014`` in accordance with the general Neuromag / MNE naming pattern. The event_id assignment equals ``np.arange(n_events) + 1``. The resulting ``event_id`` mapping is stored as attribute to the resulting raw object but will be ignored when saving to a fiff. Note. The trigger channel is artificially constructed based on timestamps received by the Netstation. As a consequence, triggers have only short durations. This step will fail if events are not mutually exclusive. """ _validate_type(input_fname, 'path-like', 'input_fname') input_fname = str(input_fname) if input_fname.endswith('.mff'): return _read_raw_egi_mff(input_fname, eog, misc, include, exclude, preload, channel_naming, verbose) return RawEGI(input_fname, eog, misc, include, exclude, preload, channel_naming, verbose) class RawEGI(BaseRaw): """Raw object from EGI simple binary file.""" @verbose def __init__(self, input_fname, eog=None, misc=None, include=None, exclude=None, preload=False, channel_naming='E%d', verbose=None): # noqa: D102 input_fname = _check_fname(input_fname, 'read', True, 'input_fname') if eog is None: eog = [] if misc is None: misc = [] with open(input_fname, 'rb') as fid: # 'rb' important for py3k logger.info('Reading EGI header from %s...' % input_fname) egi_info = _read_header(fid) logger.info(' Reading events ...') egi_events = _read_events(fid, egi_info) # update info + jump if egi_info['value_range'] != 0 and egi_info['bits'] != 0: cal = egi_info['value_range'] / 2. ** egi_info['bits'] else: cal = 1e-6 logger.info(' Assembling measurement info ...') event_codes = [] if egi_info['n_events'] > 0: event_codes = list(egi_info['event_codes']) if include is None: exclude_list = ['sync', 'TREV'] if exclude is None else exclude exclude_inds = [i for i, k in enumerate(event_codes) if k in exclude_list] more_excludes = [] if exclude is None: for ii, event in enumerate(egi_events): if event.sum() <= 1 and event_codes[ii]: more_excludes.append(ii) if len(exclude_inds) + len(more_excludes) == len(event_codes): warn('Did not find any event code with more than one ' 'event.', RuntimeWarning) else: exclude_inds.extend(more_excludes) exclude_inds.sort() include_ = [i for i in np.arange(egi_info['n_events']) if i not in exclude_inds] include_names = [k for i, k in enumerate(event_codes) if i in include_] else: include_ = [i for i, k in enumerate(event_codes) if k in include] include_names = include for kk, v in [('include', include_names), ('exclude', exclude)]: if isinstance(v, list): for k in v: if k not in event_codes: raise ValueError('Could find event named "%s"' % k) elif v is not None: raise ValueError('`%s` must be None or of type list' % kk) event_ids = np.arange(len(include_)) + 1 logger.info(' Synthesizing trigger channel "STI 014" ...') logger.info(' Excluding events {%s} ...' % ", ".join([k for i, k in enumerate(event_codes) if i not in include_])) egi_info['new_trigger'] = _combine_triggers( egi_events[include_], remapping=event_ids) self.event_id = dict(zip([e for e in event_codes if e in include_names], event_ids)) else: # No events self.event_id = None egi_info['new_trigger'] = None info = _empty_info(egi_info['samp_rate']) my_time = datetime.datetime( egi_info['year'], egi_info['month'], egi_info['day'], egi_info['hour'], egi_info['minute'], egi_info['second']) my_timestamp = time.mktime(my_time.timetuple()) info['meas_date'] = (my_timestamp, 0) ch_names = [channel_naming % (i + 1) for i in range(egi_info['n_channels'])] ch_names.extend(list(egi_info['event_codes'])) if egi_info['new_trigger'] is not None: ch_names.append('STI 014') # our new_trigger nchan = len(ch_names) cals = np.repeat(cal, nchan) ch_coil = FIFF.FIFFV_COIL_EEG ch_kind = FIFF.FIFFV_EEG_CH chs = _create_chs(ch_names, cals, ch_coil, ch_kind, eog, (), (), misc) sti_ch_idx = [i for i, name in enumerate(ch_names) if name.startswith('STI') or name in event_codes] for idx in sti_ch_idx: chs[idx].update({'unit_mul': FIFF.FIFF_UNITM_NONE, 'cal': 1., 'kind': FIFF.FIFFV_STIM_CH, 'coil_type': FIFF.FIFFV_COIL_NONE, 'unit': FIFF.FIFF_UNIT_NONE}) info['chs'] = chs info._update_redundant() super(RawEGI, self).__init__( info, preload, orig_format=egi_info['orig_format'], filenames=[input_fname], last_samps=[egi_info['n_samples'] - 1], raw_extras=[egi_info], verbose=verbose) def _read_segment_file(self, data, idx, fi, start, stop, cals, mult): """Read a segment of data from a file.""" egi_info = self._raw_extras[fi] dtype = egi_info['dtype'] n_chan_read = egi_info['n_channels'] + egi_info['n_events'] offset = 36 + egi_info['n_events'] * 4 trigger_ch = egi_info['new_trigger'] _read_segments_file(self, data, idx, fi, start, stop, cals, mult, dtype=dtype, n_channels=n_chan_read, offset=offset, trigger_ch=trigger_ch)
from itertools import product import datetime import os.path as op import numpy as np from numpy.testing import (assert_array_equal, assert_equal, assert_allclose) import pytest import matplotlib.pyplot as plt import mne from mne import (Epochs, read_events, pick_types, create_info, EpochsArray, Info, Transform) from mne.io import read_raw_fif from mne.utils import (requires_h5py, requires_pandas, grand_average, catch_logging) from mne.time_frequency.tfr import (morlet, tfr_morlet, _make_dpss, tfr_multitaper, AverageTFR, read_tfrs, write_tfrs, combine_tfr, cwt, _compute_tfr, EpochsTFR) from mne.time_frequency import tfr_array_multitaper, tfr_array_morlet from mne.viz.utils import _fake_click from mne.tests.test_epochs import assert_metadata_equal data_path = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data') raw_fname = op.join(data_path, 'test_raw.fif') event_fname = op.join(data_path, 'test-eve.fif') raw_ctf_fname = op.join(data_path, 'test_ctf_raw.fif') def test_tfr_ctf(): """Test that TFRs can be calculated on CTF data.""" raw = read_raw_fif(raw_ctf_fname).crop(0, 1) raw.apply_gradient_compensation(3) events = mne.make_fixed_length_events(raw, duration=0.5) epochs = mne.Epochs(raw, events) for method in (tfr_multitaper, tfr_morlet): method(epochs, [10], 1) # smoke test def test_morlet(): """Test morlet with and without zero mean.""" Wz = morlet(1000, [10], 2., zero_mean=True) W = morlet(1000, [10], 2., zero_mean=False) assert (np.abs(np.mean(np.real(Wz[0]))) < 1e-5) assert (np.abs(np.mean(np.real(W[0]))) > 1e-3) def test_time_frequency(): """Test time-frequency transform (PSD and ITC).""" # Set parameters event_id = 1 tmin = -0.2 tmax = 0.498 # Allows exhaustive decimation testing # Setup for reading the raw data raw = read_raw_fif(raw_fname) events = read_events(event_fname) include = [] exclude = raw.info['bads'] + ['MEG 2443', 'EEG 053'] # bads + 2 more # picks MEG gradiometers picks = pick_types(raw.info, meg='grad', eeg=False, stim=False, include=include, exclude=exclude) picks = picks[:2] epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks) data = epochs.get_data() times = epochs.times nave = len(data) epochs_nopicks = Epochs(raw, events, event_id, tmin, tmax) freqs = np.arange(6, 20, 5) # define frequencies of interest n_cycles = freqs / 4. # Test first with a single epoch power, itc = tfr_morlet(epochs[0], freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=True) # Now compute evoked evoked = epochs.average() pytest.raises(ValueError, tfr_morlet, evoked, freqs, 1., return_itc=True) power, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=True) power_, itc_ = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=True, decim=slice(0, 2)) # Test picks argument and average parameter pytest.raises(ValueError, tfr_morlet, epochs, freqs=freqs, n_cycles=n_cycles, return_itc=True, average=False) power_picks, itc_picks = \ tfr_morlet(epochs_nopicks, freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=True, picks=picks, average=True) epochs_power_picks = \ tfr_morlet(epochs_nopicks, freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=False, picks=picks, average=False) power_picks_avg = epochs_power_picks.average() # the actual data arrays here are equivalent, too... assert_allclose(power.data, power_picks.data) assert_allclose(power.data, power_picks_avg.data) assert_allclose(itc.data, itc_picks.data) # test on evoked power_evoked = tfr_morlet(evoked, freqs, n_cycles, use_fft=True, return_itc=False) # one is squared magnitude of the average (evoked) and # the other is average of the squared magnitudes (epochs PSD) # so values shouldn't match, but shapes should assert_array_equal(power.data.shape, power_evoked.data.shape) pytest.raises(AssertionError, assert_allclose, power.data, power_evoked.data) # complex output pytest.raises(ValueError, tfr_morlet, epochs, freqs, n_cycles, return_itc=False, average=True, output="complex") pytest.raises(ValueError, tfr_morlet, epochs, freqs, n_cycles, output="complex", average=False, return_itc=True) epochs_power_complex = tfr_morlet(epochs, freqs, n_cycles, output="complex", average=False, return_itc=False) epochs_amplitude_2 = abs(epochs_power_complex) epochs_amplitude_3 = epochs_amplitude_2.copy() epochs_amplitude_3.data[:] = np.inf # test that it's actually copied # test that the power computed via `complex` is equivalent to power # computed within the method. assert_allclose(epochs_amplitude_2.data**2, epochs_power_picks.data) print(itc) # test repr print(itc.ch_names) # test property itc += power # test add itc -= power # test sub ret = itc * 23 # test mult itc = ret / 23 # test dic power = power.apply_baseline(baseline=(-0.1, 0), mode='logratio') assert 'meg' in power assert 'grad' in power assert 'mag' not in power assert 'eeg' not in power assert power.nave == nave assert itc.nave == nave assert (power.data.shape == (len(picks), len(freqs), len(times))) assert (power.data.shape == itc.data.shape) assert (power_.data.shape == (len(picks), len(freqs), 2)) assert (power_.data.shape == itc_.data.shape) assert (np.sum(itc.data >= 1) == 0) assert (np.sum(itc.data <= 0) == 0) # grand average itc2 = itc.copy() itc2.info['bads'] = [itc2.ch_names[0]] # test channel drop gave = grand_average([itc2, itc]) assert gave.data.shape == (itc2.data.shape[0] - 1, itc2.data.shape[1], itc2.data.shape[2]) assert itc2.ch_names[1:] == gave.ch_names assert gave.nave == 2 itc2.drop_channels(itc2.info["bads"]) assert_allclose(gave.data, itc2.data) itc2.data = np.ones(itc2.data.shape) itc.data = np.zeros(itc.data.shape) itc2.nave = 2 itc.nave = 1 itc.drop_channels([itc.ch_names[0]]) combined_itc = combine_tfr([itc2, itc]) assert_allclose(combined_itc.data, np.ones(combined_itc.data.shape) * 2 / 3) # more tests power, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=2, use_fft=False, return_itc=True) assert (power.data.shape == (len(picks), len(freqs), len(times))) assert (power.data.shape == itc.data.shape) assert (np.sum(itc.data >= 1) == 0) assert (np.sum(itc.data <= 0) == 0) tfr = tfr_morlet(epochs[0], freqs, use_fft=True, n_cycles=2, average=False, return_itc=False) tfr_data = tfr.data[0] assert (tfr_data.shape == (len(picks), len(freqs), len(times))) tfr2 = tfr_morlet(epochs[0], freqs, use_fft=True, n_cycles=2, decim=slice(0, 2), average=False, return_itc=False).data[0] assert (tfr2.shape == (len(picks), len(freqs), 2)) single_power = tfr_morlet(epochs, freqs, 2, average=False, return_itc=False).data single_power2 = tfr_morlet(epochs, freqs, 2, decim=slice(0, 2), average=False, return_itc=False).data single_power3 = tfr_morlet(epochs, freqs, 2, decim=slice(1, 3), average=False, return_itc=False).data single_power4 = tfr_morlet(epochs, freqs, 2, decim=slice(2, 4), average=False, return_itc=False).data assert_allclose(np.mean(single_power, axis=0), power.data) assert_allclose(np.mean(single_power2, axis=0), power.data[:, :, :2]) assert_allclose(np.mean(single_power3, axis=0), power.data[:, :, 1:3]) assert_allclose(np.mean(single_power4, axis=0), power.data[:, :, 2:4]) power_pick = power.pick_channels(power.ch_names[:10:2]) assert_equal(len(power_pick.ch_names), len(power.ch_names[:10:2])) assert_equal(power_pick.data.shape[0], len(power.ch_names[:10:2])) power_drop = power.drop_channels(power.ch_names[1:10:2]) assert_equal(power_drop.ch_names, power_pick.ch_names) assert_equal(power_pick.data.shape[0], len(power_drop.ch_names)) power_pick, power_drop = mne.equalize_channels([power_pick, power_drop]) assert_equal(power_pick.ch_names, power_drop.ch_names) assert_equal(power_pick.data.shape, power_drop.data.shape) # Test decimation: # 2: multiple of len(times) even # 3: multiple odd # 8: not multiple, even # 9: not multiple, odd for decim in [2, 3, 8, 9]: for use_fft in [True, False]: power, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=2, use_fft=use_fft, return_itc=True, decim=decim) assert_equal(power.data.shape[2], np.ceil(float(len(times)) / decim)) freqs = list(range(50, 55)) decim = 2 _, n_chan, n_time = data.shape tfr = tfr_morlet(epochs[0], freqs, 2., decim=decim, average=False, return_itc=False).data[0] assert_equal(tfr.shape, (n_chan, len(freqs), n_time // decim)) # Test cwt modes Ws = morlet(512, [10, 20], n_cycles=2) pytest.raises(ValueError, cwt, data[0, :, :], Ws, mode='foo') for use_fft in [True, False]: for mode in ['same', 'valid', 'full']: cwt(data[0], Ws, use_fft=use_fft, mode=mode) # Test invalid frequency arguments with pytest.raises(ValueError, match=" 'freqs' must be greater than 0"): tfr_morlet(epochs, freqs=np.arange(0, 3), n_cycles=7) with pytest.raises(ValueError, match=" 'freqs' must be greater than 0"): tfr_morlet(epochs, freqs=np.arange(-4, -1), n_cycles=7) # Test decim parameter checks pytest.raises(TypeError, tfr_morlet, epochs, freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=True, decim='decim') # When convolving in time, wavelets must not be longer than the data pytest.raises(ValueError, cwt, data[0, :, :Ws[0].size - 1], Ws, use_fft=False) with pytest.warns(UserWarning, match='one of the wavelets.*is longer'): cwt(data[0, :, :Ws[0].size - 1], Ws, use_fft=True) # Check for off-by-one errors when using wavelets with an even number of # samples psd = cwt(data[0], [Ws[0][:-1]], use_fft=False, mode='full') assert_equal(psd.shape, (2, 1, 420)) def test_dpsswavelet(): """Test DPSS tapers.""" freqs = np.arange(5, 25, 3) Ws = _make_dpss(1000, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, zero_mean=True) assert (len(Ws) == 3) # 3 tapers expected # Check that zero mean is true assert (np.abs(np.mean(np.real(Ws[0][0]))) < 1e-5) assert (len(Ws[0]) == len(freqs)) # As many wavelets as asked for @pytest.mark.slowtest def test_tfr_multitaper(): """Test tfr_multitaper.""" sfreq = 200.0 ch_names = ['SIM0001', 'SIM0002'] ch_types = ['grad', 'grad'] info = create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types) n_times = int(sfreq) # Second long epochs n_epochs = 3 seed = 42 rng = np.random.RandomState(seed) noise = 0.1 * rng.randn(n_epochs, len(ch_names), n_times) t = np.arange(n_times, dtype=np.float64) / sfreq signal = np.sin(np.pi * 2. * 50. * t) # 50 Hz sinusoid signal signal[np.logical_or(t < 0.45, t > 0.55)] = 0. # Hard windowing on_time = np.logical_and(t >= 0.45, t <= 0.55) signal[on_time] *= np.hanning(on_time.sum()) # Ramping dat = noise + signal reject = dict(grad=4000.) events = np.empty((n_epochs, 3), int) first_event_sample = 100 event_id = dict(sin50hz=1) for k in range(n_epochs): events[k, :] = first_event_sample + k * n_times, 0, event_id['sin50hz'] epochs = EpochsArray(data=dat, info=info, events=events, event_id=event_id, reject=reject) freqs = np.arange(35, 70, 5, dtype=np.float64) power, itc = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0) power2, itc2 = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, decim=slice(0, 2)) picks = np.arange(len(ch_names)) power_picks, itc_picks = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, picks=picks) power_epochs = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, return_itc=False, average=False) power_averaged = power_epochs.average() power_evoked = tfr_multitaper(epochs.average(), freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, return_itc=False, average=False).average() print(power_evoked) # test repr for EpochsTFR # Test channel picking power_epochs_picked = power_epochs.copy().drop_channels(['SIM0002']) assert_equal(power_epochs_picked.data.shape, (3, 1, 7, 200)) assert_equal(power_epochs_picked.ch_names, ['SIM0001']) pytest.raises(ValueError, tfr_multitaper, epochs, freqs=freqs, n_cycles=freqs / 2., return_itc=True, average=False) # test picks argument assert_allclose(power.data, power_picks.data) assert_allclose(power.data, power_averaged.data) assert_allclose(power.times, power_epochs.times) assert_allclose(power.times, power_averaged.times) assert_equal(power.nave, power_averaged.nave) assert_equal(power_epochs.data.shape, (3, 2, 7, 200)) assert_allclose(itc.data, itc_picks.data) # one is squared magnitude of the average (evoked) and # the other is average of the squared magnitudes (epochs PSD) # so values shouldn't match, but shapes should assert_array_equal(power.data.shape, power_evoked.data.shape) pytest.raises(AssertionError, assert_allclose, power.data, power_evoked.data) tmax = t[np.argmax(itc.data[0, freqs == 50, :])] fmax = freqs[np.argmax(power.data[1, :, t == 0.5])] assert (tmax > 0.3 and tmax < 0.7) assert not np.any(itc.data < 0.) assert (fmax > 40 and fmax < 60) assert (power2.data.shape == (len(picks), len(freqs), 2)) assert (power2.data.shape == itc2.data.shape) # Test decim parameter checks and compatibility between wavelets length # and instance length in the time dimension. pytest.raises(TypeError, tfr_multitaper, epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, decim=(1,)) pytest.raises(ValueError, tfr_multitaper, epochs, freqs=freqs, n_cycles=1000, time_bandwidth=4.0) # Test invalid frequency arguments with pytest.raises(ValueError, match=" 'freqs' must be greater than 0"): tfr_multitaper(epochs, freqs=np.arange(0, 3), n_cycles=7) with pytest.raises(ValueError, match=" 'freqs' must be greater than 0"): tfr_multitaper(epochs, freqs=np.arange(-4, -1), n_cycles=7) def test_crop(): """Test TFR cropping.""" data = np.zeros((3, 4, 5)) times = np.array([.1, .2, .3, .4, .5]) freqs = np.array([.10, .20, .30, .40]) info = mne.create_info(['MEG 001', 'MEG 002', 'MEG 003'], 1000., ['mag', 'mag', 'mag']) tfr = AverageTFR(info, data=data, times=times, freqs=freqs, nave=20, comment='test', method='crazy-tfr') tfr.crop(tmin=0.2) assert_array_equal(tfr.times, [0.2, 0.3, 0.4, 0.5]) assert tfr.data.ndim == 3 assert tfr.data.shape[-1] == 4 tfr.crop(fmax=0.3) assert_array_equal(tfr.freqs, [0.1, 0.2, 0.3]) assert tfr.data.ndim == 3 assert tfr.data.shape[-2] == 3 tfr.crop(tmin=0.3, tmax=0.4, fmin=0.1, fmax=0.2) assert_array_equal(tfr.times, [0.3, 0.4]) assert tfr.data.ndim == 3 assert tfr.data.shape[-1] == 2 assert_array_equal(tfr.freqs, [0.1, 0.2]) assert tfr.data.shape[-2] == 2 @requires_h5py @requires_pandas def test_io(tmpdir): """Test TFR IO capacities.""" from pandas import DataFrame tempdir = str(tmpdir) fname = op.join(tempdir, 'test-tfr.h5') data = np.zeros((3, 2, 3)) times = np.array([.1, .2, .3]) freqs = np.array([.10, .20]) info = mne.create_info(['MEG 001', 'MEG 002', 'MEG 003'], 1000., ['mag', 'mag', 'mag']) info['meas_date'] = datetime.datetime(year=2020, month=2, day=5, tzinfo=datetime.timezone.utc) info._check_consistency() tfr = AverageTFR(info, data=data, times=times, freqs=freqs, nave=20, comment='test', method='crazy-tfr') tfr.save(fname) tfr2 = read_tfrs(fname, condition='test') assert isinstance(tfr2.info, Info) assert isinstance(tfr2.info['dev_head_t'], Transform) assert_array_equal(tfr.data, tfr2.data) assert_array_equal(tfr.times, tfr2.times) assert_array_equal(tfr.freqs, tfr2.freqs) assert_equal(tfr.comment, tfr2.comment) assert_equal(tfr.nave, tfr2.nave) pytest.raises(IOError, tfr.save, fname) tfr.comment = None # test old meas_date info['meas_date'] = (1, 2) tfr.save(fname, overwrite=True) assert_equal(read_tfrs(fname, condition=0).comment, tfr.comment) tfr.comment = 'test-A' tfr2.comment = 'test-B' fname = op.join(tempdir, 'test2-tfr.h5') write_tfrs(fname, [tfr, tfr2]) tfr3 = read_tfrs(fname, condition='test-A') assert_equal(tfr.comment, tfr3.comment) assert (isinstance(tfr.info, mne.Info)) tfrs = read_tfrs(fname, condition=None) assert_equal(len(tfrs), 2) tfr4 = tfrs[1] assert_equal(tfr2.comment, tfr4.comment) pytest.raises(ValueError, read_tfrs, fname, condition='nonono') # Test save of EpochsTFR. n_events = 5 data = np.zeros((n_events, 3, 2, 3)) # create fake metadata rng = np.random.RandomState(42) rt = np.round(rng.uniform(size=(n_events,)), 3) trialtypes = np.array(['face', 'place']) trial = trialtypes[(rng.uniform(size=(n_events,)) > .5).astype(int)] meta = DataFrame(dict(RT=rt, Trial=trial)) # fake events and event_id events = np.zeros([n_events, 3]) events[:, 0] = np.arange(n_events) events[:, 2] = np.ones(n_events) event_id = {'a/b': 1} # fake selection n_dropped_epochs = 3 selection = np.arange(n_events + n_dropped_epochs)[n_dropped_epochs:] drop_log = tuple([('IGNORED',) for i in range(n_dropped_epochs)] + [() for i in range(n_events)]) tfr = EpochsTFR(info, data=data, times=times, freqs=freqs, comment='test', method='crazy-tfr', events=events, event_id=event_id, selection=selection, drop_log=drop_log, metadata=meta) fname_save = fname tfr.save(fname_save, True) fname_write = op.join(tempdir, 'test3-tfr.h5') write_tfrs(fname_write, tfr, overwrite=True) for fname in [fname_save, fname_write]: read_tfr = read_tfrs(fname)[0] assert_array_equal(tfr.data, read_tfr.data) assert_metadata_equal(tfr.metadata, read_tfr.metadata) assert_array_equal(tfr.events, read_tfr.events) assert tfr.event_id == read_tfr.event_id assert_array_equal(tfr.selection, read_tfr.selection) assert tfr.drop_log == read_tfr.drop_log with pytest.raises(NotImplementedError, match='condition not supported'): tfr = read_tfrs(fname, condition='a') def test_init_EpochsTFR(): """Test __init__ for EpochsTFR.""" # Create fake data: data = np.zeros((3, 3, 3, 3)) times = np.array([.1, .2, .3]) freqs = np.array([.10, .20, .30]) info = mne.create_info(['MEG 001', 'MEG 002', 'MEG 003'], 1000., ['mag', 'mag', 'mag']) data_x = data[:, :, :, 0] with pytest.raises(ValueError, match='data should be 4d. Got 3'): tfr = EpochsTFR(info, data=data_x, times=times, freqs=freqs) data_x = data[:, :-1, :, :] with pytest.raises(ValueError, match="channels and data size don't"): tfr = EpochsTFR(info, data=data_x, times=times, freqs=freqs) times_x = times[:-1] with pytest.raises(ValueError, match="times and data size don't match"): tfr = EpochsTFR(info, data=data, times=times_x, freqs=freqs) freqs_x = freqs[:-1] with pytest.raises(ValueError, match="frequencies and data size don't"): tfr = EpochsTFR(info, data=data, times=times_x, freqs=freqs_x) del(tfr) def test_plot(): """Test TFR plotting.""" data = np.zeros((3, 2, 3)) times = np.array([.1, .2, .3]) freqs = np.array([.10, .20]) info = mne.create_info(['MEG 001', 'MEG 002', 'MEG 003'], 1000., ['mag', 'mag', 'mag']) tfr = AverageTFR(info, data=data, times=times, freqs=freqs, nave=20, comment='test', method='crazy-tfr') # test title=auto, combine=None, and correct length of figure list picks = [1, 2] figs = tfr.plot(picks, title='auto', colorbar=False, mask=np.ones(tfr.data.shape[1:], bool)) assert len(figs) == len(picks) assert 'MEG' in figs[0].texts[0].get_text() plt.close('all') # test combine and title keyword figs = tfr.plot(picks, title='title', colorbar=False, combine='rms', mask=np.ones(tfr.data.shape[1:], bool)) assert len(figs) == 1 assert figs[0].texts[0].get_text() == 'title' figs = tfr.plot(picks, title='auto', colorbar=False, combine='mean', mask=np.ones(tfr.data.shape[1:], bool)) assert len(figs) == 1 assert figs[0].texts[0].get_text() == 'Mean of 2 sensors' with pytest.raises(ValueError, match='combine must be None'): tfr.plot(picks, colorbar=False, combine='something', mask=np.ones(tfr.data.shape[1:], bool)) plt.close('all') # test axes argument - first with list of axes ax = plt.subplot2grid((2, 2), (0, 0)) ax2 = plt.subplot2grid((2, 2), (0, 1)) ax3 = plt.subplot2grid((2, 2), (1, 0)) figs = tfr.plot(picks=[0, 1, 2], axes=[ax, ax2, ax3]) assert len(figs) == len([ax, ax2, ax3]) # and as a single axes figs = tfr.plot(picks=[0], axes=ax) assert len(figs) == 1 plt.close('all') # and invalid inputs with pytest.raises(ValueError, match='axes must be None'): tfr.plot(picks, colorbar=False, axes={}, mask=np.ones(tfr.data.shape[1:], bool)) # different number of axes and picks should throw a RuntimeError with pytest.raises(RuntimeError, match='There must be an axes'): tfr.plot(picks=[0], colorbar=False, axes=[ax, ax2], mask=np.ones(tfr.data.shape[1:], bool)) tfr.plot_topo(picks=[1, 2]) plt.close('all') # interactive mode on by default fig = tfr.plot(picks=[1], cmap='RdBu_r')[0] fig.canvas.key_press_event('up') fig.canvas.key_press_event(' ') fig.canvas.key_press_event('down') fig.canvas.key_press_event(' ') fig.canvas.key_press_event('+') fig.canvas.key_press_event(' ') fig.canvas.key_press_event('-') fig.canvas.key_press_event(' ') fig.canvas.key_press_event('pageup') fig.canvas.key_press_event(' ') fig.canvas.key_press_event('pagedown') cbar = fig.get_axes()[0].CB # Fake dragging with mouse. ax = cbar.cbar.ax _fake_click(fig, ax, (0.1, 0.1)) _fake_click(fig, ax, (0.1, 0.2), kind='motion') _fake_click(fig, ax, (0.1, 0.3), kind='release') _fake_click(fig, ax, (0.1, 0.1), button=3) _fake_click(fig, ax, (0.1, 0.2), button=3, kind='motion') _fake_click(fig, ax, (0.1, 0.3), kind='release') fig.canvas.scroll_event(0.5, 0.5, -0.5) # scroll down fig.canvas.scroll_event(0.5, 0.5, 0.5) # scroll up plt.close('all') def test_plot_joint(): """Test TFR joint plotting.""" raw = read_raw_fif(raw_fname) times = np.linspace(-0.1, 0.1, 200) n_freqs = 3 nave = 1 rng = np.random.RandomState(42) data = rng.randn(len(raw.ch_names), n_freqs, len(times)) tfr = AverageTFR(raw.info, data, times, np.arange(n_freqs), nave) topomap_args = {'res': 8, 'contours': 0, 'sensors': False} for combine in ('mean', 'rms'): with catch_logging() as log: tfr.plot_joint(title='auto', colorbar=True, combine=combine, topomap_args=topomap_args, verbose='debug') plt.close('all') log = log.getvalue() assert 'Plotting topomap for grad data' in log # check various timefreqs for timefreqs in ( {(tfr.times[0], tfr.freqs[1]): (0.1, 0.5), (tfr.times[-1], tfr.freqs[-1]): (0.2, 0.6)}, [(tfr.times[1], tfr.freqs[1])]): tfr.plot_joint(timefreqs=timefreqs, topomap_args=topomap_args) plt.close('all') # test bad timefreqs timefreqs = ([(-100, 1)], tfr.times[1], [1], [(tfr.times[1], tfr.freqs[1], tfr.freqs[1])]) for these_timefreqs in timefreqs: pytest.raises(ValueError, tfr.plot_joint, these_timefreqs) # test that the object is not internally modified tfr_orig = tfr.copy() tfr.plot_joint(baseline=(0, None), exclude=[tfr.ch_names[0]], topomap_args=topomap_args) plt.close('all') assert_array_equal(tfr.data, tfr_orig.data) assert set(tfr.ch_names) == set(tfr_orig.ch_names) assert set(tfr.times) == set(tfr_orig.times) # test tfr with picked channels tfr.pick_channels(tfr.ch_names[:-1]) tfr.plot_joint(title='auto', colorbar=True, topomap_args=topomap_args) def test_add_channels(): """Test tfr splitting / re-appending channel types.""" data = np.zeros((6, 2, 3)) times = np.array([.1, .2, .3]) freqs = np.array([.10, .20]) info = mne.create_info( ['MEG 001', 'MEG 002', 'MEG 003', 'EEG 001', 'EEG 002', 'STIM 001'], 1000., ['mag', 'mag', 'mag', 'eeg', 'eeg', 'stim']) tfr = AverageTFR(info, data=data, times=times, freqs=freqs, nave=20, comment='test', method='crazy-tfr') tfr_eeg = tfr.copy().pick_types(meg=False, eeg=True) tfr_meg = tfr.copy().pick_types(meg=True) tfr_stim = tfr.copy().pick_types(meg=False, stim=True) tfr_eeg_meg = tfr.copy().pick_types(meg=True, eeg=True) tfr_new = tfr_meg.copy().add_channels([tfr_eeg, tfr_stim]) assert all(ch in tfr_new.ch_names for ch in tfr_stim.ch_names + tfr_meg.ch_names) tfr_new = tfr_meg.copy().add_channels([tfr_eeg]) have_all = all(ch in tfr_new.ch_names for ch in tfr.ch_names if ch != 'STIM 001') assert have_all assert_array_equal(tfr_new.data, tfr_eeg_meg.data) assert all(ch not in tfr_new.ch_names for ch in tfr_stim.ch_names) # Now test errors tfr_badsf = tfr_eeg.copy() tfr_badsf.info['sfreq'] = 3.1415927 tfr_eeg = tfr_eeg.crop(-.1, .1) pytest.raises(RuntimeError, tfr_meg.add_channels, [tfr_badsf]) pytest.raises(AssertionError, tfr_meg.add_channels, [tfr_eeg]) pytest.raises(ValueError, tfr_meg.add_channels, [tfr_meg]) pytest.raises(TypeError, tfr_meg.add_channels, tfr_badsf) def test_compute_tfr(): """Test _compute_tfr function.""" # Set parameters event_id = 1 tmin = -0.2 tmax = 0.498 # Allows exhaustive decimation testing # Setup for reading the raw data raw = read_raw_fif(raw_fname) events = read_events(event_fname) exclude = raw.info['bads'] + ['MEG 2443', 'EEG 053'] # bads + 2 more # picks MEG gradiometers picks = pick_types(raw.info, meg='grad', eeg=False, stim=False, include=[], exclude=exclude) picks = picks[:2] epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks) data = epochs.get_data() sfreq = epochs.info['sfreq'] freqs = np.arange(10, 20, 3).astype(float) # Check all combination of options for func, use_fft, zero_mean, output in product( (tfr_array_multitaper, tfr_array_morlet), (False, True), (False, True), ('complex', 'power', 'phase', 'avg_power_itc', 'avg_power', 'itc')): # Check exception if (func == tfr_array_multitaper) and (output == 'phase'): pytest.raises(NotImplementedError, func, data, sfreq=sfreq, freqs=freqs, output=output) continue # Check runs out = func(data, sfreq=sfreq, freqs=freqs, use_fft=use_fft, zero_mean=zero_mean, n_cycles=2., output=output) # Check shapes shape = np.r_[data.shape[:2], len(freqs), data.shape[2]] if ('avg' in output) or ('itc' in output): assert_array_equal(shape[1:], out.shape) else: assert_array_equal(shape, out.shape) # Check types if output in ('complex', 'avg_power_itc'): assert_equal(np.complex128, out.dtype) else: assert_equal(np.float64, out.dtype) assert (np.all(np.isfinite(out))) # Check errors params for _data in (None, 'foo', data[0]): pytest.raises(ValueError, _compute_tfr, _data, freqs, sfreq) for _freqs in (None, 'foo', [[0]]): pytest.raises(ValueError, _compute_tfr, data, _freqs, sfreq) for _sfreq in (None, 'foo'): pytest.raises(ValueError, _compute_tfr, data, freqs, _sfreq) for key in ('output', 'method', 'use_fft', 'decim', 'n_jobs'): for value in (None, 'foo'): kwargs = {key: value} # FIXME pep8 pytest.raises(ValueError, _compute_tfr, data, freqs, sfreq, **kwargs) with pytest.raises(ValueError, match='above Nyquist'): _compute_tfr(data, [sfreq], sfreq) # No time_bandwidth param in morlet pytest.raises(ValueError, _compute_tfr, data, freqs, sfreq, method='morlet', time_bandwidth=1) # No phase in multitaper XXX Check ? pytest.raises(NotImplementedError, _compute_tfr, data, freqs, sfreq, method='multitaper', output='phase') # Inter-trial coherence tests out = _compute_tfr(data, freqs, sfreq, output='itc', n_cycles=2.) assert np.sum(out >= 1) == 0 assert np.sum(out <= 0) == 0 # Check decim shapes # 2: multiple of len(times) even # 3: multiple odd # 8: not multiple, even # 9: not multiple, odd for decim in (2, 3, 8, 9, slice(0, 2), slice(1, 3), slice(2, 4)): _decim = slice(None, None, decim) if isinstance(decim, int) else decim n_time = len(np.arange(data.shape[2])[_decim]) shape = np.r_[data.shape[:2], len(freqs), n_time] for method in ('multitaper', 'morlet'): # Single trials out = _compute_tfr(data, freqs, sfreq, method=method, decim=decim, n_cycles=2.) assert_array_equal(shape, out.shape) # Averages out = _compute_tfr(data, freqs, sfreq, method=method, decim=decim, output='avg_power', n_cycles=2.) assert_array_equal(shape[1:], out.shape) @pytest.mark.parametrize('method', ('multitaper', 'morlet')) @pytest.mark.parametrize('decim', (1, slice(1, None, 2), 3)) def test_compute_tfr_correct(method, decim): """Test that TFR actually gets us our freq back.""" sfreq = 1000. t = np.arange(1000) / sfreq f = 50. data = np.sin(2 * np.pi * 50. * t) data *= np.hanning(data.size) data = data[np.newaxis, np.newaxis] freqs = np.arange(10, 111, 10) assert f in freqs tfr = _compute_tfr(data, freqs, sfreq, method=method, decim=decim, n_cycles=2)[0, 0] assert freqs[np.argmax(np.abs(tfr).mean(-1))] == f def test_averaging_epochsTFR(): """Test that EpochsTFR averaging methods work.""" # Setup for reading the raw data event_id = 1 tmin = -0.2 tmax = 0.498 # Allows exhaustive decimation testing freqs = np.arange(6, 20, 5) # define frequencies of interest n_cycles = freqs / 4. raw = read_raw_fif(raw_fname) # only pick a few events for speed events = read_events(event_fname)[:4] include = [] exclude = raw.info['bads'] + ['MEG 2443', 'EEG 053'] # bads + 2 more # picks MEG gradiometers picks = pick_types(raw.info, meg='grad', eeg=False, stim=False, include=include, exclude=exclude) picks = picks[:2] epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks) # Obtain EpochsTFR power = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, average=False, use_fft=True, return_itc=False) # Test average methods for func, method in zip( [np.mean, np.median, np.mean], ['mean', 'median', lambda x: np.mean(x, axis=0)]): avgpower = power.average(method=method) np.testing.assert_array_equal(func(power.data, axis=0), avgpower.data) with pytest.raises(RuntimeError, match='You passed a function that ' 'resulted in data'): power.average(method=np.mean) @requires_pandas def test_getitem_epochsTFR(): """Test GetEpochsMixin in the context of EpochsTFR.""" from pandas import DataFrame # Setup for reading the raw data and select a few trials raw = read_raw_fif(raw_fname) events = read_events(event_fname) # create fake data, test with and without dropping epochs for n_drop_epochs in [0, 2]: n_events = 12 # create fake metadata rng = np.random.RandomState(42) rt = rng.uniform(size=(n_events,)) trialtypes = np.array(['face', 'place']) trial = trialtypes[(rng.uniform(size=(n_events,)) > .5).astype(int)] meta = DataFrame(dict(RT=rt, Trial=trial)) event_id = dict(a=1, b=2, c=3, d=4) epochs = Epochs(raw, events[:n_events], event_id=event_id, metadata=meta, decim=1) epochs.drop(np.arange(n_drop_epochs)) n_events -= n_drop_epochs freqs = np.arange(12., 17., 2.) # define frequencies of interest n_cycles = freqs / 2. # 0.5 second time windows for all frequencies # Choose time x (full) bandwidth product time_bandwidth = 4.0 # With 0.5 s time windows, this gives 8 Hz smoothing kwargs = dict(freqs=freqs, n_cycles=n_cycles, use_fft=True, time_bandwidth=time_bandwidth, return_itc=False, average=False, n_jobs=1) power = tfr_multitaper(epochs, **kwargs) # Check that power and epochs metadata is the same assert_metadata_equal(epochs.metadata, power.metadata) assert_metadata_equal(epochs[::2].metadata, power[::2].metadata) assert_metadata_equal(epochs['RT < .5'].metadata, power['RT < .5'].metadata) assert_array_equal(epochs.selection, power.selection) assert epochs.drop_log == power.drop_log # Check that get power is functioning assert_array_equal(power[3:6].data, power.data[3:6]) assert_array_equal(power[3:6].events, power.events[3:6]) assert_array_equal(epochs.selection[3:6], power.selection[3:6]) indx_check = (power.metadata['Trial'] == 'face') try: indx_check = indx_check.to_numpy() except Exception: pass # older Pandas indx_check = indx_check.nonzero() assert_array_equal(power['Trial == "face"'].events, power.events[indx_check]) assert_array_equal(power['Trial == "face"'].data, power.data[indx_check]) # Check that the wrong Key generates a Key Error for Metadata search with pytest.raises(KeyError): power['Trialz == "place"'] # Test length function assert len(power) == n_events assert len(power[3:6]) == 3 # Test iteration function for ind, power_ep in enumerate(power): assert_array_equal(power_ep, power.data[ind]) if ind == 5: break # Test that current state is maintained assert_array_equal(power.next(), power.data[ind + 1]) # Check decim affects sfreq power_decim = tfr_multitaper(epochs, decim=2, **kwargs) assert power.info['sfreq'] / 2. == power_decim.info['sfreq'] @requires_pandas def test_to_data_frame(): """Test EpochsTFR Pandas exporter.""" # Create fake EpochsTFR data: n_epos = 3 ch_names = ['EEG 001', 'EEG 002', 'EEG 003', 'EEG 004'] n_picks = len(ch_names) ch_types = ['eeg'] * n_picks n_freqs = 5 n_times = 6 data = np.random.rand(n_epos, n_picks, n_freqs, n_times) times = np.arange(6) srate = 1000. freqs = np.arange(5) events = np.zeros((n_epos, 3), dtype=int) events[:, 0] = np.arange(n_epos) events[:, 2] = np.arange(5, 5 + n_epos) event_id = {k: v for v, k in zip(events[:, 2], ['ha', 'he', 'hu'])} info = mne.create_info(ch_names, srate, ch_types) tfr = mne.time_frequency.EpochsTFR(info, data, times, freqs, events=events, event_id=event_id) # test index checking with pytest.raises(ValueError, match='options. Valid index options are'): tfr.to_data_frame(index=['foo', 'bar']) with pytest.raises(ValueError, match='"qux" is not a valid option'): tfr.to_data_frame(index='qux') with pytest.raises(TypeError, match='index must be `None` or a string '): tfr.to_data_frame(index=np.arange(400)) # test wide format df_wide = tfr.to_data_frame() assert all(np.in1d(tfr.ch_names, df_wide.columns)) assert all(np.in1d(['time', 'condition', 'freq', 'epoch'], df_wide.columns)) # test long format df_long = tfr.to_data_frame(long_format=True) expected = ('condition', 'epoch', 'freq', 'time', 'channel', 'ch_type', 'value') assert set(expected) == set(df_long.columns) assert set(tfr.ch_names) == set(df_long['channel']) assert(len(df_long) == tfr.data.size) # test long format w/ index df_long = tfr.to_data_frame(long_format=True, index=['freq']) del df_wide, df_long # test whether data is in correct shape df = tfr.to_data_frame(index=['condition', 'epoch', 'freq', 'time']) data = tfr.data assert_array_equal(df.values[:, 0], data[:, 0, :, :].reshape(1, -1).squeeze()) # compare arbitrary observation: assert df.loc[('he', slice(None), freqs[1], times[2] * srate), ch_names[3]].iloc[0] == data[1, 3, 1, 2] # Check also for AverageTFR: tfr = tfr.average() with pytest.raises(ValueError, match='options. Valid index options are'): tfr.to_data_frame(index=['epoch', 'condition']) with pytest.raises(ValueError, match='"epoch" is not a valid option'): tfr.to_data_frame(index='epoch') with pytest.raises(TypeError, match='index must be `None` or a string '): tfr.to_data_frame(index=np.arange(400)) # test wide format df_wide = tfr.to_data_frame() assert all(np.in1d(tfr.ch_names, df_wide.columns)) assert all(np.in1d(['time', 'freq'], df_wide.columns)) # test long format df_long = tfr.to_data_frame(long_format=True) expected = ('freq', 'time', 'channel', 'ch_type', 'value') assert set(expected) == set(df_long.columns) assert set(tfr.ch_names) == set(df_long['channel']) assert(len(df_long) == tfr.data.size) # test long format w/ index df_long = tfr.to_data_frame(long_format=True, index=['freq']) del df_wide, df_long # test whether data is in correct shape df = tfr.to_data_frame(index=['freq', 'time']) data = tfr.data assert_array_equal(df.values[:, 0], data[0, :, :].reshape(1, -1).squeeze()) # compare arbitrary observation: assert df.loc[(freqs[1], times[2] * srate), ch_names[3]] == \ data[3, 1, 2] @requires_pandas @pytest.mark.parametrize('index', ('time', ['condition', 'time', 'freq'], ['freq', 'time'], ['time', 'freq'], None)) def test_to_data_frame_index(index): """Test index creation in epochs Pandas exporter.""" # Create fake EpochsTFR data: n_epos = 3 ch_names = ['EEG 001', 'EEG 002', 'EEG 003', 'EEG 004'] n_picks = len(ch_names) ch_types = ['eeg'] * n_picks n_freqs = 5 n_times = 6 data = np.random.rand(n_epos, n_picks, n_freqs, n_times) times = np.arange(6) freqs = np.arange(5) events = np.zeros((n_epos, 3), dtype=int) events[:, 0] = np.arange(n_epos) events[:, 2] = np.arange(5, 8) event_id = {k: v for v, k in zip(events[:, 2], ['ha', 'he', 'hu'])} info = mne.create_info(ch_names, 1000., ch_types) tfr = mne.time_frequency.EpochsTFR(info, data, times, freqs, events=events, event_id=event_id) df = tfr.to_data_frame(picks=[0, 2, 3], index=index) # test index order/hierarchy preservation if not isinstance(index, list): index = [index] assert (df.index.names == index) # test that non-indexed data were present as columns non_index = list(set(['condition', 'time', 'freq', 'epoch']) - set(index)) if len(non_index): assert all(np.in1d(non_index, df.columns)) @requires_pandas @pytest.mark.parametrize('time_format', (None, 'ms', 'timedelta')) def test_to_data_frame_time_format(time_format): """Test time conversion in epochs Pandas exporter.""" from pandas import Timedelta n_epos = 3 ch_names = ['EEG 001', 'EEG 002', 'EEG 003', 'EEG 004'] n_picks = len(ch_names) ch_types = ['eeg'] * n_picks n_freqs = 5 n_times = 6 data = np.random.rand(n_epos, n_picks, n_freqs, n_times) times = np.arange(6) freqs = np.arange(5) events = np.zeros((n_epos, 3), dtype=int) events[:, 0] = np.arange(n_epos) events[:, 2] = np.arange(5, 8) event_id = {k: v for v, k in zip(events[:, 2], ['ha', 'he', 'hu'])} info = mne.create_info(ch_names, 1000., ch_types) tfr = mne.time_frequency.EpochsTFR(info, data, times, freqs, events=events, event_id=event_id) # test time_format df = tfr.to_data_frame(time_format=time_format) dtypes = {None: np.float64, 'ms': np.int64, 'timedelta': Timedelta} assert isinstance(df['time'].iloc[0], dtypes[time_format])
rkmaddox/mne-python
mne/time_frequency/tests/test_tfr.py
mne/io/egi/egi.py
"""Mayavi/traits GUI for averaging two sets of KIT marker points.""" # Authors: Christian Brodbeck <christianbrodbeck@nyu.edu> # # License: BSD (3-clause) import os import sys import numpy as np from mayavi.tools.mlab_scene_model import MlabSceneModel from pyface.api import confirm, error, FileDialog, OK, YES from traits.api import (HasTraits, HasPrivateTraits, on_trait_change, cached_property, Instance, Property, Array, Bool, Button, Enum, File, Float, List, Str, ArrayOrNone) from traitsui.api import View, Item, HGroup, VGroup, CheckListEditor from traitsui.menu import Action, CancelButton from ..transforms import apply_trans, rotation, translation from ..coreg import fit_matched_points from ..io.kit import read_mrk from ..io._digitization import _write_dig_points from ._viewer import PointObject from ._backend import _get_pyface_backend if _get_pyface_backend() == 'wx': mrk_wildcard = [ 'Supported Files (*.sqd, *.mrk, *.txt, *.pickled)|*.sqd;*.mrk;*.txt;*.pickled', # noqa:E501 'Sqd marker file (*.sqd;*.mrk)|*.sqd;*.mrk', 'Text marker file (*.txt)|*.txt', 'Pickled markers (*.pickled)|*.pickled'] mrk_out_wildcard = ["Tab separated values file (*.txt)|*.txt"] else: if sys.platform in ('win32', 'linux2'): # on Windows and Ubuntu, multiple wildcards does not seem to work mrk_wildcard = ["*.sqd", "*.mrk", "*.txt", "*.pickled"] else: mrk_wildcard = ["*.sqd;*.mrk;*.txt;*.pickled"] mrk_out_wildcard = "*.txt" out_ext = '.txt' use_editor_v = CheckListEditor(cols=1, values=[(i, str(i)) for i in range(5)]) use_editor_h = CheckListEditor(cols=5, values=[(i, str(i)) for i in range(5)]) mrk_view_editable = View( VGroup('file', Item('name', show_label=False, style='readonly'), HGroup( Item('use', editor=use_editor_v, enabled_when="enabled", style='custom'), 'points', ), HGroup(Item('clear', enabled_when="can_save", show_label=False), Item('save_as', enabled_when="can_save", show_label=False)), )) mrk_view_basic = View( VGroup('file', Item('name', show_label=False, style='readonly'), Item('use', editor=use_editor_h, enabled_when="enabled", style='custom'), HGroup(Item('clear', enabled_when="can_save", show_label=False), Item('edit', show_label=False), Item('switch_left_right', label="Switch Left/Right", show_label=False), Item('reorder', show_label=False), Item('save_as', enabled_when="can_save", show_label=False)), )) mrk_view_edit = View(VGroup('points')) class ReorderDialog(HasPrivateTraits): """Dialog for reordering marker points.""" order = Str("0 1 2 3 4") index = Property(List, depends_on='order') is_ok = Property(Bool, depends_on='order') view = View( Item('order', label='New order (five space delimited numbers)'), buttons=[CancelButton, Action(name='OK', enabled_when='is_ok')]) def _get_index(self): try: return [int(i) for i in self.order.split()] except ValueError: return [] def _get_is_ok(self): return sorted(self.index) == [0, 1, 2, 3, 4] class MarkerPoints(HasPrivateTraits): """Represent 5 marker points.""" points = Array(float, (5, 3)) can_save = Property(depends_on='points') save_as = Button() view = View(VGroup('points', Item('save_as', enabled_when='can_save'))) @cached_property def _get_can_save(self): return np.any(self.points) def _save_as_fired(self): dlg = FileDialog(action="save as", wildcard=mrk_out_wildcard, default_filename=self.name, default_directory=self.dir) dlg.open() if dlg.return_code != OK: return path, ext = os.path.splitext(dlg.path) if not path.endswith(out_ext) and len(ext) != 0: ValueError("The extension '%s' is not supported." % ext) path = path + out_ext if os.path.exists(path): answer = confirm(None, "The file %r already exists. Should it " "be replaced?", "Overwrite File?") if answer != YES: return self.save(path) def save(self, path): """Save the marker points. Parameters ---------- path : str Path to the file to write. The kind of file to write is determined based on the extension: '.txt' for tab separated text file, '.pickled' for pickled file. """ _write_dig_points(path, self.points) class MarkerPointSource(MarkerPoints): # noqa: D401 """MarkerPoints subclass for source files.""" file = File(filter=mrk_wildcard, exists=True) name = Property(Str, depends_on='file') dir = Property(Str, depends_on='file') use = List(list(range(5)), desc="Which points to use for the interpolated " "marker.") enabled = Property(Bool, depends_on=['points', 'use']) clear = Button(desc="Clear the current marker data") edit = Button(desc="Edit the marker coordinates manually") switch_left_right = Button( desc="Switch left and right marker points; this is intended to " "correct for markers that were attached in the wrong order") reorder = Button(desc="Change the order of the marker points") view = mrk_view_basic @cached_property def _get_enabled(self): return np.any(self.points) @cached_property def _get_dir(self): if self.file: return os.path.dirname(self.file) @cached_property def _get_name(self): if self.file: return os.path.basename(self.file) @on_trait_change('file') def load(self, fname): if not fname: self.reset_traits(['points']) return try: pts = read_mrk(fname) except Exception as err: error(None, str(err), "Error Reading mrk") self.reset_traits(['points']) else: self.points = pts def _clear_fired(self): self.reset_traits(['file', 'points', 'use']) def _edit_fired(self): self.edit_traits(view=mrk_view_edit) def _reorder_fired(self): dlg = ReorderDialog() ui = dlg.edit_traits(kind='modal') if not ui.result: # user pressed cancel return self.points = self.points[dlg.index] def _switch_left_right_fired(self): self.points = self.points[[1, 0, 2, 4, 3]] class MarkerPointDest(MarkerPoints): # noqa: D401 """MarkerPoints subclass that serves for derived points.""" src1 = Instance(MarkerPointSource) src2 = Instance(MarkerPointSource) name = Property(Str, depends_on='src1.name,src2.name') dir = Property(Str, depends_on='src1.dir,src2.dir') points = Property(ArrayOrNone(float, (5, 3)), depends_on=['method', 'src1.points', 'src1.use', 'src2.points', 'src2.use']) enabled = Property(Bool, depends_on=['points']) method = Enum('Transform', 'Average', desc="Transform: estimate a rotation" "/translation from mrk1 to mrk2; Average: use the average " "of the mrk1 and mrk2 coordinates for each point.") view = View(VGroup(Item('method', style='custom'), Item('save_as', enabled_when='can_save', show_label=False))) @cached_property def _get_dir(self): return self.src1.dir @cached_property def _get_name(self): n1 = self.src1.name n2 = self.src2.name if not n1: if n2: return n2 else: return '' elif not n2: return n1 if n1 == n2: return n1 i = 0 l1 = len(n1) - 1 l2 = len(n1) - 2 while n1[i] == n2[i]: if i == l1: return n1 elif i == l2: return n2 i += 1 return n1[:i] @cached_property def _get_enabled(self): return np.any(self.points) @cached_property def _get_points(self): # in case only one or no source is enabled if not (self.src1 and self.src1.enabled): if (self.src2 and self.src2.enabled): return self.src2.points else: return np.zeros((5, 3)) elif not (self.src2 and self.src2.enabled): return self.src1.points # Average method if self.method == 'Average': if len(np.union1d(self.src1.use, self.src2.use)) < 5: error(None, "Need at least one source for each point.", "Marker Average Error") return np.zeros((5, 3)) pts = (self.src1.points + self.src2.points) / 2. for i in np.setdiff1d(self.src1.use, self.src2.use): pts[i] = self.src1.points[i] for i in np.setdiff1d(self.src2.use, self.src1.use): pts[i] = self.src2.points[i] return pts # Transform method idx = np.intersect1d(np.array(self.src1.use), np.array(self.src2.use), assume_unique=True) if len(idx) < 3: error(None, "Need at least three shared points for trans" "formation.", "Marker Interpolation Error") return np.zeros((5, 3)) src_pts = self.src1.points[idx] tgt_pts = self.src2.points[idx] est = fit_matched_points(src_pts, tgt_pts, out='params') rot = np.array(est[:3]) / 2. tra = np.array(est[3:]) / 2. if len(self.src1.use) == 5: trans = np.dot(translation(*tra), rotation(*rot)) pts = apply_trans(trans, self.src1.points) elif len(self.src2.use) == 5: trans = np.dot(translation(* -tra), rotation(* -rot)) pts = apply_trans(trans, self.src2.points) else: trans1 = np.dot(translation(*tra), rotation(*rot)) pts = apply_trans(trans1, self.src1.points) trans2 = np.dot(translation(* -tra), rotation(* -rot)) for i in np.setdiff1d(self.src2.use, self.src1.use): pts[i] = apply_trans(trans2, self.src2.points[i]) return pts class CombineMarkersModel(HasPrivateTraits): """Combine markers model.""" mrk1_file = Instance(File) mrk2_file = Instance(File) mrk1 = Instance(MarkerPointSource) mrk2 = Instance(MarkerPointSource) mrk3 = Instance(MarkerPointDest) clear = Button(desc="Clear the current marker data") # stats distance = Property(Str, depends_on=['mrk1.points', 'mrk2.points']) def _clear_fired(self): self.mrk1.clear = True self.mrk2.clear = True self.mrk3.reset_traits(['method']) def _mrk1_default(self): return MarkerPointSource() def _mrk1_file_default(self): return self.mrk1.trait('file') def _mrk2_default(self): return MarkerPointSource() def _mrk2_file_default(self): return self.mrk2.trait('file') def _mrk3_default(self): return MarkerPointDest(src1=self.mrk1, src2=self.mrk2) @cached_property def _get_distance(self): if (self.mrk1 is None or self.mrk2 is None or (not np.any(self.mrk1.points)) or (not np.any(self.mrk2.points))): return "" ds = np.sqrt(np.sum((self.mrk1.points - self.mrk2.points) ** 2, 1)) desc = '\t'.join('%.1f mm' % (d * 1000) for d in ds) return desc class CombineMarkersPanel(HasTraits): # noqa: D401 """Has two marker points sources and interpolates to a third one.""" model = Instance(CombineMarkersModel, ()) # model references for UI mrk1 = Instance(MarkerPointSource) mrk2 = Instance(MarkerPointSource) mrk3 = Instance(MarkerPointDest) distance = Str # Visualization scene = Instance(MlabSceneModel) scale = Float(5e-3) mrk1_obj = Instance(PointObject) mrk2_obj = Instance(PointObject) mrk3_obj = Instance(PointObject) trans = Array() view = View(VGroup(VGroup(Item('mrk1', style='custom'), Item('mrk1_obj', style='custom'), show_labels=False, label="Source Marker 1", show_border=True), VGroup(Item('mrk2', style='custom'), Item('mrk2_obj', style='custom'), show_labels=False, label="Source Marker 2", show_border=True), VGroup(Item('distance', style='readonly'), label='Stats', show_border=True), VGroup(Item('mrk3', style='custom'), Item('mrk3_obj', style='custom'), show_labels=False, label="New Marker", show_border=True), )) def _mrk1_default(self): return self.model.mrk1 def _mrk2_default(self): return self.model.mrk2 def _mrk3_default(self): return self.model.mrk3 def __init__(self, *args, **kwargs): # noqa: D102 super(CombineMarkersPanel, self).__init__(*args, **kwargs) self.model.sync_trait('distance', self, 'distance', mutual=False) self.mrk1_obj = PointObject(scene=self.scene, color=(0.608, 0.216, 0.216), point_scale=self.scale) self.model.mrk1.sync_trait( 'enabled', self.mrk1_obj, 'visible', mutual=False) self.mrk2_obj = PointObject(scene=self.scene, color=(0.216, 0.608, 0.216), point_scale=self.scale) self.model.mrk2.sync_trait( 'enabled', self.mrk2_obj, 'visible', mutual=False) self.mrk3_obj = PointObject(scene=self.scene, color=(0.588, 0.784, 1.), point_scale=self.scale) self.model.mrk3.sync_trait( 'enabled', self.mrk3_obj, 'visible', mutual=False) @on_trait_change('model:mrk1:points,trans') def _update_mrk1(self): if self.mrk1_obj is not None: self.mrk1_obj.points = apply_trans(self.trans, self.model.mrk1.points) @on_trait_change('model:mrk2:points,trans') def _update_mrk2(self): if self.mrk2_obj is not None: self.mrk2_obj.points = apply_trans(self.trans, self.model.mrk2.points) @on_trait_change('model:mrk3:points,trans') def _update_mrk3(self): if self.mrk3_obj is not None: self.mrk3_obj.points = apply_trans(self.trans, self.model.mrk3.points)
from itertools import product import datetime import os.path as op import numpy as np from numpy.testing import (assert_array_equal, assert_equal, assert_allclose) import pytest import matplotlib.pyplot as plt import mne from mne import (Epochs, read_events, pick_types, create_info, EpochsArray, Info, Transform) from mne.io import read_raw_fif from mne.utils import (requires_h5py, requires_pandas, grand_average, catch_logging) from mne.time_frequency.tfr import (morlet, tfr_morlet, _make_dpss, tfr_multitaper, AverageTFR, read_tfrs, write_tfrs, combine_tfr, cwt, _compute_tfr, EpochsTFR) from mne.time_frequency import tfr_array_multitaper, tfr_array_morlet from mne.viz.utils import _fake_click from mne.tests.test_epochs import assert_metadata_equal data_path = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data') raw_fname = op.join(data_path, 'test_raw.fif') event_fname = op.join(data_path, 'test-eve.fif') raw_ctf_fname = op.join(data_path, 'test_ctf_raw.fif') def test_tfr_ctf(): """Test that TFRs can be calculated on CTF data.""" raw = read_raw_fif(raw_ctf_fname).crop(0, 1) raw.apply_gradient_compensation(3) events = mne.make_fixed_length_events(raw, duration=0.5) epochs = mne.Epochs(raw, events) for method in (tfr_multitaper, tfr_morlet): method(epochs, [10], 1) # smoke test def test_morlet(): """Test morlet with and without zero mean.""" Wz = morlet(1000, [10], 2., zero_mean=True) W = morlet(1000, [10], 2., zero_mean=False) assert (np.abs(np.mean(np.real(Wz[0]))) < 1e-5) assert (np.abs(np.mean(np.real(W[0]))) > 1e-3) def test_time_frequency(): """Test time-frequency transform (PSD and ITC).""" # Set parameters event_id = 1 tmin = -0.2 tmax = 0.498 # Allows exhaustive decimation testing # Setup for reading the raw data raw = read_raw_fif(raw_fname) events = read_events(event_fname) include = [] exclude = raw.info['bads'] + ['MEG 2443', 'EEG 053'] # bads + 2 more # picks MEG gradiometers picks = pick_types(raw.info, meg='grad', eeg=False, stim=False, include=include, exclude=exclude) picks = picks[:2] epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks) data = epochs.get_data() times = epochs.times nave = len(data) epochs_nopicks = Epochs(raw, events, event_id, tmin, tmax) freqs = np.arange(6, 20, 5) # define frequencies of interest n_cycles = freqs / 4. # Test first with a single epoch power, itc = tfr_morlet(epochs[0], freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=True) # Now compute evoked evoked = epochs.average() pytest.raises(ValueError, tfr_morlet, evoked, freqs, 1., return_itc=True) power, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=True) power_, itc_ = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=True, decim=slice(0, 2)) # Test picks argument and average parameter pytest.raises(ValueError, tfr_morlet, epochs, freqs=freqs, n_cycles=n_cycles, return_itc=True, average=False) power_picks, itc_picks = \ tfr_morlet(epochs_nopicks, freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=True, picks=picks, average=True) epochs_power_picks = \ tfr_morlet(epochs_nopicks, freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=False, picks=picks, average=False) power_picks_avg = epochs_power_picks.average() # the actual data arrays here are equivalent, too... assert_allclose(power.data, power_picks.data) assert_allclose(power.data, power_picks_avg.data) assert_allclose(itc.data, itc_picks.data) # test on evoked power_evoked = tfr_morlet(evoked, freqs, n_cycles, use_fft=True, return_itc=False) # one is squared magnitude of the average (evoked) and # the other is average of the squared magnitudes (epochs PSD) # so values shouldn't match, but shapes should assert_array_equal(power.data.shape, power_evoked.data.shape) pytest.raises(AssertionError, assert_allclose, power.data, power_evoked.data) # complex output pytest.raises(ValueError, tfr_morlet, epochs, freqs, n_cycles, return_itc=False, average=True, output="complex") pytest.raises(ValueError, tfr_morlet, epochs, freqs, n_cycles, output="complex", average=False, return_itc=True) epochs_power_complex = tfr_morlet(epochs, freqs, n_cycles, output="complex", average=False, return_itc=False) epochs_amplitude_2 = abs(epochs_power_complex) epochs_amplitude_3 = epochs_amplitude_2.copy() epochs_amplitude_3.data[:] = np.inf # test that it's actually copied # test that the power computed via `complex` is equivalent to power # computed within the method. assert_allclose(epochs_amplitude_2.data**2, epochs_power_picks.data) print(itc) # test repr print(itc.ch_names) # test property itc += power # test add itc -= power # test sub ret = itc * 23 # test mult itc = ret / 23 # test dic power = power.apply_baseline(baseline=(-0.1, 0), mode='logratio') assert 'meg' in power assert 'grad' in power assert 'mag' not in power assert 'eeg' not in power assert power.nave == nave assert itc.nave == nave assert (power.data.shape == (len(picks), len(freqs), len(times))) assert (power.data.shape == itc.data.shape) assert (power_.data.shape == (len(picks), len(freqs), 2)) assert (power_.data.shape == itc_.data.shape) assert (np.sum(itc.data >= 1) == 0) assert (np.sum(itc.data <= 0) == 0) # grand average itc2 = itc.copy() itc2.info['bads'] = [itc2.ch_names[0]] # test channel drop gave = grand_average([itc2, itc]) assert gave.data.shape == (itc2.data.shape[0] - 1, itc2.data.shape[1], itc2.data.shape[2]) assert itc2.ch_names[1:] == gave.ch_names assert gave.nave == 2 itc2.drop_channels(itc2.info["bads"]) assert_allclose(gave.data, itc2.data) itc2.data = np.ones(itc2.data.shape) itc.data = np.zeros(itc.data.shape) itc2.nave = 2 itc.nave = 1 itc.drop_channels([itc.ch_names[0]]) combined_itc = combine_tfr([itc2, itc]) assert_allclose(combined_itc.data, np.ones(combined_itc.data.shape) * 2 / 3) # more tests power, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=2, use_fft=False, return_itc=True) assert (power.data.shape == (len(picks), len(freqs), len(times))) assert (power.data.shape == itc.data.shape) assert (np.sum(itc.data >= 1) == 0) assert (np.sum(itc.data <= 0) == 0) tfr = tfr_morlet(epochs[0], freqs, use_fft=True, n_cycles=2, average=False, return_itc=False) tfr_data = tfr.data[0] assert (tfr_data.shape == (len(picks), len(freqs), len(times))) tfr2 = tfr_morlet(epochs[0], freqs, use_fft=True, n_cycles=2, decim=slice(0, 2), average=False, return_itc=False).data[0] assert (tfr2.shape == (len(picks), len(freqs), 2)) single_power = tfr_morlet(epochs, freqs, 2, average=False, return_itc=False).data single_power2 = tfr_morlet(epochs, freqs, 2, decim=slice(0, 2), average=False, return_itc=False).data single_power3 = tfr_morlet(epochs, freqs, 2, decim=slice(1, 3), average=False, return_itc=False).data single_power4 = tfr_morlet(epochs, freqs, 2, decim=slice(2, 4), average=False, return_itc=False).data assert_allclose(np.mean(single_power, axis=0), power.data) assert_allclose(np.mean(single_power2, axis=0), power.data[:, :, :2]) assert_allclose(np.mean(single_power3, axis=0), power.data[:, :, 1:3]) assert_allclose(np.mean(single_power4, axis=0), power.data[:, :, 2:4]) power_pick = power.pick_channels(power.ch_names[:10:2]) assert_equal(len(power_pick.ch_names), len(power.ch_names[:10:2])) assert_equal(power_pick.data.shape[0], len(power.ch_names[:10:2])) power_drop = power.drop_channels(power.ch_names[1:10:2]) assert_equal(power_drop.ch_names, power_pick.ch_names) assert_equal(power_pick.data.shape[0], len(power_drop.ch_names)) power_pick, power_drop = mne.equalize_channels([power_pick, power_drop]) assert_equal(power_pick.ch_names, power_drop.ch_names) assert_equal(power_pick.data.shape, power_drop.data.shape) # Test decimation: # 2: multiple of len(times) even # 3: multiple odd # 8: not multiple, even # 9: not multiple, odd for decim in [2, 3, 8, 9]: for use_fft in [True, False]: power, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=2, use_fft=use_fft, return_itc=True, decim=decim) assert_equal(power.data.shape[2], np.ceil(float(len(times)) / decim)) freqs = list(range(50, 55)) decim = 2 _, n_chan, n_time = data.shape tfr = tfr_morlet(epochs[0], freqs, 2., decim=decim, average=False, return_itc=False).data[0] assert_equal(tfr.shape, (n_chan, len(freqs), n_time // decim)) # Test cwt modes Ws = morlet(512, [10, 20], n_cycles=2) pytest.raises(ValueError, cwt, data[0, :, :], Ws, mode='foo') for use_fft in [True, False]: for mode in ['same', 'valid', 'full']: cwt(data[0], Ws, use_fft=use_fft, mode=mode) # Test invalid frequency arguments with pytest.raises(ValueError, match=" 'freqs' must be greater than 0"): tfr_morlet(epochs, freqs=np.arange(0, 3), n_cycles=7) with pytest.raises(ValueError, match=" 'freqs' must be greater than 0"): tfr_morlet(epochs, freqs=np.arange(-4, -1), n_cycles=7) # Test decim parameter checks pytest.raises(TypeError, tfr_morlet, epochs, freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=True, decim='decim') # When convolving in time, wavelets must not be longer than the data pytest.raises(ValueError, cwt, data[0, :, :Ws[0].size - 1], Ws, use_fft=False) with pytest.warns(UserWarning, match='one of the wavelets.*is longer'): cwt(data[0, :, :Ws[0].size - 1], Ws, use_fft=True) # Check for off-by-one errors when using wavelets with an even number of # samples psd = cwt(data[0], [Ws[0][:-1]], use_fft=False, mode='full') assert_equal(psd.shape, (2, 1, 420)) def test_dpsswavelet(): """Test DPSS tapers.""" freqs = np.arange(5, 25, 3) Ws = _make_dpss(1000, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, zero_mean=True) assert (len(Ws) == 3) # 3 tapers expected # Check that zero mean is true assert (np.abs(np.mean(np.real(Ws[0][0]))) < 1e-5) assert (len(Ws[0]) == len(freqs)) # As many wavelets as asked for @pytest.mark.slowtest def test_tfr_multitaper(): """Test tfr_multitaper.""" sfreq = 200.0 ch_names = ['SIM0001', 'SIM0002'] ch_types = ['grad', 'grad'] info = create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types) n_times = int(sfreq) # Second long epochs n_epochs = 3 seed = 42 rng = np.random.RandomState(seed) noise = 0.1 * rng.randn(n_epochs, len(ch_names), n_times) t = np.arange(n_times, dtype=np.float64) / sfreq signal = np.sin(np.pi * 2. * 50. * t) # 50 Hz sinusoid signal signal[np.logical_or(t < 0.45, t > 0.55)] = 0. # Hard windowing on_time = np.logical_and(t >= 0.45, t <= 0.55) signal[on_time] *= np.hanning(on_time.sum()) # Ramping dat = noise + signal reject = dict(grad=4000.) events = np.empty((n_epochs, 3), int) first_event_sample = 100 event_id = dict(sin50hz=1) for k in range(n_epochs): events[k, :] = first_event_sample + k * n_times, 0, event_id['sin50hz'] epochs = EpochsArray(data=dat, info=info, events=events, event_id=event_id, reject=reject) freqs = np.arange(35, 70, 5, dtype=np.float64) power, itc = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0) power2, itc2 = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, decim=slice(0, 2)) picks = np.arange(len(ch_names)) power_picks, itc_picks = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, picks=picks) power_epochs = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, return_itc=False, average=False) power_averaged = power_epochs.average() power_evoked = tfr_multitaper(epochs.average(), freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, return_itc=False, average=False).average() print(power_evoked) # test repr for EpochsTFR # Test channel picking power_epochs_picked = power_epochs.copy().drop_channels(['SIM0002']) assert_equal(power_epochs_picked.data.shape, (3, 1, 7, 200)) assert_equal(power_epochs_picked.ch_names, ['SIM0001']) pytest.raises(ValueError, tfr_multitaper, epochs, freqs=freqs, n_cycles=freqs / 2., return_itc=True, average=False) # test picks argument assert_allclose(power.data, power_picks.data) assert_allclose(power.data, power_averaged.data) assert_allclose(power.times, power_epochs.times) assert_allclose(power.times, power_averaged.times) assert_equal(power.nave, power_averaged.nave) assert_equal(power_epochs.data.shape, (3, 2, 7, 200)) assert_allclose(itc.data, itc_picks.data) # one is squared magnitude of the average (evoked) and # the other is average of the squared magnitudes (epochs PSD) # so values shouldn't match, but shapes should assert_array_equal(power.data.shape, power_evoked.data.shape) pytest.raises(AssertionError, assert_allclose, power.data, power_evoked.data) tmax = t[np.argmax(itc.data[0, freqs == 50, :])] fmax = freqs[np.argmax(power.data[1, :, t == 0.5])] assert (tmax > 0.3 and tmax < 0.7) assert not np.any(itc.data < 0.) assert (fmax > 40 and fmax < 60) assert (power2.data.shape == (len(picks), len(freqs), 2)) assert (power2.data.shape == itc2.data.shape) # Test decim parameter checks and compatibility between wavelets length # and instance length in the time dimension. pytest.raises(TypeError, tfr_multitaper, epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, decim=(1,)) pytest.raises(ValueError, tfr_multitaper, epochs, freqs=freqs, n_cycles=1000, time_bandwidth=4.0) # Test invalid frequency arguments with pytest.raises(ValueError, match=" 'freqs' must be greater than 0"): tfr_multitaper(epochs, freqs=np.arange(0, 3), n_cycles=7) with pytest.raises(ValueError, match=" 'freqs' must be greater than 0"): tfr_multitaper(epochs, freqs=np.arange(-4, -1), n_cycles=7) def test_crop(): """Test TFR cropping.""" data = np.zeros((3, 4, 5)) times = np.array([.1, .2, .3, .4, .5]) freqs = np.array([.10, .20, .30, .40]) info = mne.create_info(['MEG 001', 'MEG 002', 'MEG 003'], 1000., ['mag', 'mag', 'mag']) tfr = AverageTFR(info, data=data, times=times, freqs=freqs, nave=20, comment='test', method='crazy-tfr') tfr.crop(tmin=0.2) assert_array_equal(tfr.times, [0.2, 0.3, 0.4, 0.5]) assert tfr.data.ndim == 3 assert tfr.data.shape[-1] == 4 tfr.crop(fmax=0.3) assert_array_equal(tfr.freqs, [0.1, 0.2, 0.3]) assert tfr.data.ndim == 3 assert tfr.data.shape[-2] == 3 tfr.crop(tmin=0.3, tmax=0.4, fmin=0.1, fmax=0.2) assert_array_equal(tfr.times, [0.3, 0.4]) assert tfr.data.ndim == 3 assert tfr.data.shape[-1] == 2 assert_array_equal(tfr.freqs, [0.1, 0.2]) assert tfr.data.shape[-2] == 2 @requires_h5py @requires_pandas def test_io(tmpdir): """Test TFR IO capacities.""" from pandas import DataFrame tempdir = str(tmpdir) fname = op.join(tempdir, 'test-tfr.h5') data = np.zeros((3, 2, 3)) times = np.array([.1, .2, .3]) freqs = np.array([.10, .20]) info = mne.create_info(['MEG 001', 'MEG 002', 'MEG 003'], 1000., ['mag', 'mag', 'mag']) info['meas_date'] = datetime.datetime(year=2020, month=2, day=5, tzinfo=datetime.timezone.utc) info._check_consistency() tfr = AverageTFR(info, data=data, times=times, freqs=freqs, nave=20, comment='test', method='crazy-tfr') tfr.save(fname) tfr2 = read_tfrs(fname, condition='test') assert isinstance(tfr2.info, Info) assert isinstance(tfr2.info['dev_head_t'], Transform) assert_array_equal(tfr.data, tfr2.data) assert_array_equal(tfr.times, tfr2.times) assert_array_equal(tfr.freqs, tfr2.freqs) assert_equal(tfr.comment, tfr2.comment) assert_equal(tfr.nave, tfr2.nave) pytest.raises(IOError, tfr.save, fname) tfr.comment = None # test old meas_date info['meas_date'] = (1, 2) tfr.save(fname, overwrite=True) assert_equal(read_tfrs(fname, condition=0).comment, tfr.comment) tfr.comment = 'test-A' tfr2.comment = 'test-B' fname = op.join(tempdir, 'test2-tfr.h5') write_tfrs(fname, [tfr, tfr2]) tfr3 = read_tfrs(fname, condition='test-A') assert_equal(tfr.comment, tfr3.comment) assert (isinstance(tfr.info, mne.Info)) tfrs = read_tfrs(fname, condition=None) assert_equal(len(tfrs), 2) tfr4 = tfrs[1] assert_equal(tfr2.comment, tfr4.comment) pytest.raises(ValueError, read_tfrs, fname, condition='nonono') # Test save of EpochsTFR. n_events = 5 data = np.zeros((n_events, 3, 2, 3)) # create fake metadata rng = np.random.RandomState(42) rt = np.round(rng.uniform(size=(n_events,)), 3) trialtypes = np.array(['face', 'place']) trial = trialtypes[(rng.uniform(size=(n_events,)) > .5).astype(int)] meta = DataFrame(dict(RT=rt, Trial=trial)) # fake events and event_id events = np.zeros([n_events, 3]) events[:, 0] = np.arange(n_events) events[:, 2] = np.ones(n_events) event_id = {'a/b': 1} # fake selection n_dropped_epochs = 3 selection = np.arange(n_events + n_dropped_epochs)[n_dropped_epochs:] drop_log = tuple([('IGNORED',) for i in range(n_dropped_epochs)] + [() for i in range(n_events)]) tfr = EpochsTFR(info, data=data, times=times, freqs=freqs, comment='test', method='crazy-tfr', events=events, event_id=event_id, selection=selection, drop_log=drop_log, metadata=meta) fname_save = fname tfr.save(fname_save, True) fname_write = op.join(tempdir, 'test3-tfr.h5') write_tfrs(fname_write, tfr, overwrite=True) for fname in [fname_save, fname_write]: read_tfr = read_tfrs(fname)[0] assert_array_equal(tfr.data, read_tfr.data) assert_metadata_equal(tfr.metadata, read_tfr.metadata) assert_array_equal(tfr.events, read_tfr.events) assert tfr.event_id == read_tfr.event_id assert_array_equal(tfr.selection, read_tfr.selection) assert tfr.drop_log == read_tfr.drop_log with pytest.raises(NotImplementedError, match='condition not supported'): tfr = read_tfrs(fname, condition='a') def test_init_EpochsTFR(): """Test __init__ for EpochsTFR.""" # Create fake data: data = np.zeros((3, 3, 3, 3)) times = np.array([.1, .2, .3]) freqs = np.array([.10, .20, .30]) info = mne.create_info(['MEG 001', 'MEG 002', 'MEG 003'], 1000., ['mag', 'mag', 'mag']) data_x = data[:, :, :, 0] with pytest.raises(ValueError, match='data should be 4d. Got 3'): tfr = EpochsTFR(info, data=data_x, times=times, freqs=freqs) data_x = data[:, :-1, :, :] with pytest.raises(ValueError, match="channels and data size don't"): tfr = EpochsTFR(info, data=data_x, times=times, freqs=freqs) times_x = times[:-1] with pytest.raises(ValueError, match="times and data size don't match"): tfr = EpochsTFR(info, data=data, times=times_x, freqs=freqs) freqs_x = freqs[:-1] with pytest.raises(ValueError, match="frequencies and data size don't"): tfr = EpochsTFR(info, data=data, times=times_x, freqs=freqs_x) del(tfr) def test_plot(): """Test TFR plotting.""" data = np.zeros((3, 2, 3)) times = np.array([.1, .2, .3]) freqs = np.array([.10, .20]) info = mne.create_info(['MEG 001', 'MEG 002', 'MEG 003'], 1000., ['mag', 'mag', 'mag']) tfr = AverageTFR(info, data=data, times=times, freqs=freqs, nave=20, comment='test', method='crazy-tfr') # test title=auto, combine=None, and correct length of figure list picks = [1, 2] figs = tfr.plot(picks, title='auto', colorbar=False, mask=np.ones(tfr.data.shape[1:], bool)) assert len(figs) == len(picks) assert 'MEG' in figs[0].texts[0].get_text() plt.close('all') # test combine and title keyword figs = tfr.plot(picks, title='title', colorbar=False, combine='rms', mask=np.ones(tfr.data.shape[1:], bool)) assert len(figs) == 1 assert figs[0].texts[0].get_text() == 'title' figs = tfr.plot(picks, title='auto', colorbar=False, combine='mean', mask=np.ones(tfr.data.shape[1:], bool)) assert len(figs) == 1 assert figs[0].texts[0].get_text() == 'Mean of 2 sensors' with pytest.raises(ValueError, match='combine must be None'): tfr.plot(picks, colorbar=False, combine='something', mask=np.ones(tfr.data.shape[1:], bool)) plt.close('all') # test axes argument - first with list of axes ax = plt.subplot2grid((2, 2), (0, 0)) ax2 = plt.subplot2grid((2, 2), (0, 1)) ax3 = plt.subplot2grid((2, 2), (1, 0)) figs = tfr.plot(picks=[0, 1, 2], axes=[ax, ax2, ax3]) assert len(figs) == len([ax, ax2, ax3]) # and as a single axes figs = tfr.plot(picks=[0], axes=ax) assert len(figs) == 1 plt.close('all') # and invalid inputs with pytest.raises(ValueError, match='axes must be None'): tfr.plot(picks, colorbar=False, axes={}, mask=np.ones(tfr.data.shape[1:], bool)) # different number of axes and picks should throw a RuntimeError with pytest.raises(RuntimeError, match='There must be an axes'): tfr.plot(picks=[0], colorbar=False, axes=[ax, ax2], mask=np.ones(tfr.data.shape[1:], bool)) tfr.plot_topo(picks=[1, 2]) plt.close('all') # interactive mode on by default fig = tfr.plot(picks=[1], cmap='RdBu_r')[0] fig.canvas.key_press_event('up') fig.canvas.key_press_event(' ') fig.canvas.key_press_event('down') fig.canvas.key_press_event(' ') fig.canvas.key_press_event('+') fig.canvas.key_press_event(' ') fig.canvas.key_press_event('-') fig.canvas.key_press_event(' ') fig.canvas.key_press_event('pageup') fig.canvas.key_press_event(' ') fig.canvas.key_press_event('pagedown') cbar = fig.get_axes()[0].CB # Fake dragging with mouse. ax = cbar.cbar.ax _fake_click(fig, ax, (0.1, 0.1)) _fake_click(fig, ax, (0.1, 0.2), kind='motion') _fake_click(fig, ax, (0.1, 0.3), kind='release') _fake_click(fig, ax, (0.1, 0.1), button=3) _fake_click(fig, ax, (0.1, 0.2), button=3, kind='motion') _fake_click(fig, ax, (0.1, 0.3), kind='release') fig.canvas.scroll_event(0.5, 0.5, -0.5) # scroll down fig.canvas.scroll_event(0.5, 0.5, 0.5) # scroll up plt.close('all') def test_plot_joint(): """Test TFR joint plotting.""" raw = read_raw_fif(raw_fname) times = np.linspace(-0.1, 0.1, 200) n_freqs = 3 nave = 1 rng = np.random.RandomState(42) data = rng.randn(len(raw.ch_names), n_freqs, len(times)) tfr = AverageTFR(raw.info, data, times, np.arange(n_freqs), nave) topomap_args = {'res': 8, 'contours': 0, 'sensors': False} for combine in ('mean', 'rms'): with catch_logging() as log: tfr.plot_joint(title='auto', colorbar=True, combine=combine, topomap_args=topomap_args, verbose='debug') plt.close('all') log = log.getvalue() assert 'Plotting topomap for grad data' in log # check various timefreqs for timefreqs in ( {(tfr.times[0], tfr.freqs[1]): (0.1, 0.5), (tfr.times[-1], tfr.freqs[-1]): (0.2, 0.6)}, [(tfr.times[1], tfr.freqs[1])]): tfr.plot_joint(timefreqs=timefreqs, topomap_args=topomap_args) plt.close('all') # test bad timefreqs timefreqs = ([(-100, 1)], tfr.times[1], [1], [(tfr.times[1], tfr.freqs[1], tfr.freqs[1])]) for these_timefreqs in timefreqs: pytest.raises(ValueError, tfr.plot_joint, these_timefreqs) # test that the object is not internally modified tfr_orig = tfr.copy() tfr.plot_joint(baseline=(0, None), exclude=[tfr.ch_names[0]], topomap_args=topomap_args) plt.close('all') assert_array_equal(tfr.data, tfr_orig.data) assert set(tfr.ch_names) == set(tfr_orig.ch_names) assert set(tfr.times) == set(tfr_orig.times) # test tfr with picked channels tfr.pick_channels(tfr.ch_names[:-1]) tfr.plot_joint(title='auto', colorbar=True, topomap_args=topomap_args) def test_add_channels(): """Test tfr splitting / re-appending channel types.""" data = np.zeros((6, 2, 3)) times = np.array([.1, .2, .3]) freqs = np.array([.10, .20]) info = mne.create_info( ['MEG 001', 'MEG 002', 'MEG 003', 'EEG 001', 'EEG 002', 'STIM 001'], 1000., ['mag', 'mag', 'mag', 'eeg', 'eeg', 'stim']) tfr = AverageTFR(info, data=data, times=times, freqs=freqs, nave=20, comment='test', method='crazy-tfr') tfr_eeg = tfr.copy().pick_types(meg=False, eeg=True) tfr_meg = tfr.copy().pick_types(meg=True) tfr_stim = tfr.copy().pick_types(meg=False, stim=True) tfr_eeg_meg = tfr.copy().pick_types(meg=True, eeg=True) tfr_new = tfr_meg.copy().add_channels([tfr_eeg, tfr_stim]) assert all(ch in tfr_new.ch_names for ch in tfr_stim.ch_names + tfr_meg.ch_names) tfr_new = tfr_meg.copy().add_channels([tfr_eeg]) have_all = all(ch in tfr_new.ch_names for ch in tfr.ch_names if ch != 'STIM 001') assert have_all assert_array_equal(tfr_new.data, tfr_eeg_meg.data) assert all(ch not in tfr_new.ch_names for ch in tfr_stim.ch_names) # Now test errors tfr_badsf = tfr_eeg.copy() tfr_badsf.info['sfreq'] = 3.1415927 tfr_eeg = tfr_eeg.crop(-.1, .1) pytest.raises(RuntimeError, tfr_meg.add_channels, [tfr_badsf]) pytest.raises(AssertionError, tfr_meg.add_channels, [tfr_eeg]) pytest.raises(ValueError, tfr_meg.add_channels, [tfr_meg]) pytest.raises(TypeError, tfr_meg.add_channels, tfr_badsf) def test_compute_tfr(): """Test _compute_tfr function.""" # Set parameters event_id = 1 tmin = -0.2 tmax = 0.498 # Allows exhaustive decimation testing # Setup for reading the raw data raw = read_raw_fif(raw_fname) events = read_events(event_fname) exclude = raw.info['bads'] + ['MEG 2443', 'EEG 053'] # bads + 2 more # picks MEG gradiometers picks = pick_types(raw.info, meg='grad', eeg=False, stim=False, include=[], exclude=exclude) picks = picks[:2] epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks) data = epochs.get_data() sfreq = epochs.info['sfreq'] freqs = np.arange(10, 20, 3).astype(float) # Check all combination of options for func, use_fft, zero_mean, output in product( (tfr_array_multitaper, tfr_array_morlet), (False, True), (False, True), ('complex', 'power', 'phase', 'avg_power_itc', 'avg_power', 'itc')): # Check exception if (func == tfr_array_multitaper) and (output == 'phase'): pytest.raises(NotImplementedError, func, data, sfreq=sfreq, freqs=freqs, output=output) continue # Check runs out = func(data, sfreq=sfreq, freqs=freqs, use_fft=use_fft, zero_mean=zero_mean, n_cycles=2., output=output) # Check shapes shape = np.r_[data.shape[:2], len(freqs), data.shape[2]] if ('avg' in output) or ('itc' in output): assert_array_equal(shape[1:], out.shape) else: assert_array_equal(shape, out.shape) # Check types if output in ('complex', 'avg_power_itc'): assert_equal(np.complex128, out.dtype) else: assert_equal(np.float64, out.dtype) assert (np.all(np.isfinite(out))) # Check errors params for _data in (None, 'foo', data[0]): pytest.raises(ValueError, _compute_tfr, _data, freqs, sfreq) for _freqs in (None, 'foo', [[0]]): pytest.raises(ValueError, _compute_tfr, data, _freqs, sfreq) for _sfreq in (None, 'foo'): pytest.raises(ValueError, _compute_tfr, data, freqs, _sfreq) for key in ('output', 'method', 'use_fft', 'decim', 'n_jobs'): for value in (None, 'foo'): kwargs = {key: value} # FIXME pep8 pytest.raises(ValueError, _compute_tfr, data, freqs, sfreq, **kwargs) with pytest.raises(ValueError, match='above Nyquist'): _compute_tfr(data, [sfreq], sfreq) # No time_bandwidth param in morlet pytest.raises(ValueError, _compute_tfr, data, freqs, sfreq, method='morlet', time_bandwidth=1) # No phase in multitaper XXX Check ? pytest.raises(NotImplementedError, _compute_tfr, data, freqs, sfreq, method='multitaper', output='phase') # Inter-trial coherence tests out = _compute_tfr(data, freqs, sfreq, output='itc', n_cycles=2.) assert np.sum(out >= 1) == 0 assert np.sum(out <= 0) == 0 # Check decim shapes # 2: multiple of len(times) even # 3: multiple odd # 8: not multiple, even # 9: not multiple, odd for decim in (2, 3, 8, 9, slice(0, 2), slice(1, 3), slice(2, 4)): _decim = slice(None, None, decim) if isinstance(decim, int) else decim n_time = len(np.arange(data.shape[2])[_decim]) shape = np.r_[data.shape[:2], len(freqs), n_time] for method in ('multitaper', 'morlet'): # Single trials out = _compute_tfr(data, freqs, sfreq, method=method, decim=decim, n_cycles=2.) assert_array_equal(shape, out.shape) # Averages out = _compute_tfr(data, freqs, sfreq, method=method, decim=decim, output='avg_power', n_cycles=2.) assert_array_equal(shape[1:], out.shape) @pytest.mark.parametrize('method', ('multitaper', 'morlet')) @pytest.mark.parametrize('decim', (1, slice(1, None, 2), 3)) def test_compute_tfr_correct(method, decim): """Test that TFR actually gets us our freq back.""" sfreq = 1000. t = np.arange(1000) / sfreq f = 50. data = np.sin(2 * np.pi * 50. * t) data *= np.hanning(data.size) data = data[np.newaxis, np.newaxis] freqs = np.arange(10, 111, 10) assert f in freqs tfr = _compute_tfr(data, freqs, sfreq, method=method, decim=decim, n_cycles=2)[0, 0] assert freqs[np.argmax(np.abs(tfr).mean(-1))] == f def test_averaging_epochsTFR(): """Test that EpochsTFR averaging methods work.""" # Setup for reading the raw data event_id = 1 tmin = -0.2 tmax = 0.498 # Allows exhaustive decimation testing freqs = np.arange(6, 20, 5) # define frequencies of interest n_cycles = freqs / 4. raw = read_raw_fif(raw_fname) # only pick a few events for speed events = read_events(event_fname)[:4] include = [] exclude = raw.info['bads'] + ['MEG 2443', 'EEG 053'] # bads + 2 more # picks MEG gradiometers picks = pick_types(raw.info, meg='grad', eeg=False, stim=False, include=include, exclude=exclude) picks = picks[:2] epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks) # Obtain EpochsTFR power = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, average=False, use_fft=True, return_itc=False) # Test average methods for func, method in zip( [np.mean, np.median, np.mean], ['mean', 'median', lambda x: np.mean(x, axis=0)]): avgpower = power.average(method=method) np.testing.assert_array_equal(func(power.data, axis=0), avgpower.data) with pytest.raises(RuntimeError, match='You passed a function that ' 'resulted in data'): power.average(method=np.mean) @requires_pandas def test_getitem_epochsTFR(): """Test GetEpochsMixin in the context of EpochsTFR.""" from pandas import DataFrame # Setup for reading the raw data and select a few trials raw = read_raw_fif(raw_fname) events = read_events(event_fname) # create fake data, test with and without dropping epochs for n_drop_epochs in [0, 2]: n_events = 12 # create fake metadata rng = np.random.RandomState(42) rt = rng.uniform(size=(n_events,)) trialtypes = np.array(['face', 'place']) trial = trialtypes[(rng.uniform(size=(n_events,)) > .5).astype(int)] meta = DataFrame(dict(RT=rt, Trial=trial)) event_id = dict(a=1, b=2, c=3, d=4) epochs = Epochs(raw, events[:n_events], event_id=event_id, metadata=meta, decim=1) epochs.drop(np.arange(n_drop_epochs)) n_events -= n_drop_epochs freqs = np.arange(12., 17., 2.) # define frequencies of interest n_cycles = freqs / 2. # 0.5 second time windows for all frequencies # Choose time x (full) bandwidth product time_bandwidth = 4.0 # With 0.5 s time windows, this gives 8 Hz smoothing kwargs = dict(freqs=freqs, n_cycles=n_cycles, use_fft=True, time_bandwidth=time_bandwidth, return_itc=False, average=False, n_jobs=1) power = tfr_multitaper(epochs, **kwargs) # Check that power and epochs metadata is the same assert_metadata_equal(epochs.metadata, power.metadata) assert_metadata_equal(epochs[::2].metadata, power[::2].metadata) assert_metadata_equal(epochs['RT < .5'].metadata, power['RT < .5'].metadata) assert_array_equal(epochs.selection, power.selection) assert epochs.drop_log == power.drop_log # Check that get power is functioning assert_array_equal(power[3:6].data, power.data[3:6]) assert_array_equal(power[3:6].events, power.events[3:6]) assert_array_equal(epochs.selection[3:6], power.selection[3:6]) indx_check = (power.metadata['Trial'] == 'face') try: indx_check = indx_check.to_numpy() except Exception: pass # older Pandas indx_check = indx_check.nonzero() assert_array_equal(power['Trial == "face"'].events, power.events[indx_check]) assert_array_equal(power['Trial == "face"'].data, power.data[indx_check]) # Check that the wrong Key generates a Key Error for Metadata search with pytest.raises(KeyError): power['Trialz == "place"'] # Test length function assert len(power) == n_events assert len(power[3:6]) == 3 # Test iteration function for ind, power_ep in enumerate(power): assert_array_equal(power_ep, power.data[ind]) if ind == 5: break # Test that current state is maintained assert_array_equal(power.next(), power.data[ind + 1]) # Check decim affects sfreq power_decim = tfr_multitaper(epochs, decim=2, **kwargs) assert power.info['sfreq'] / 2. == power_decim.info['sfreq'] @requires_pandas def test_to_data_frame(): """Test EpochsTFR Pandas exporter.""" # Create fake EpochsTFR data: n_epos = 3 ch_names = ['EEG 001', 'EEG 002', 'EEG 003', 'EEG 004'] n_picks = len(ch_names) ch_types = ['eeg'] * n_picks n_freqs = 5 n_times = 6 data = np.random.rand(n_epos, n_picks, n_freqs, n_times) times = np.arange(6) srate = 1000. freqs = np.arange(5) events = np.zeros((n_epos, 3), dtype=int) events[:, 0] = np.arange(n_epos) events[:, 2] = np.arange(5, 5 + n_epos) event_id = {k: v for v, k in zip(events[:, 2], ['ha', 'he', 'hu'])} info = mne.create_info(ch_names, srate, ch_types) tfr = mne.time_frequency.EpochsTFR(info, data, times, freqs, events=events, event_id=event_id) # test index checking with pytest.raises(ValueError, match='options. Valid index options are'): tfr.to_data_frame(index=['foo', 'bar']) with pytest.raises(ValueError, match='"qux" is not a valid option'): tfr.to_data_frame(index='qux') with pytest.raises(TypeError, match='index must be `None` or a string '): tfr.to_data_frame(index=np.arange(400)) # test wide format df_wide = tfr.to_data_frame() assert all(np.in1d(tfr.ch_names, df_wide.columns)) assert all(np.in1d(['time', 'condition', 'freq', 'epoch'], df_wide.columns)) # test long format df_long = tfr.to_data_frame(long_format=True) expected = ('condition', 'epoch', 'freq', 'time', 'channel', 'ch_type', 'value') assert set(expected) == set(df_long.columns) assert set(tfr.ch_names) == set(df_long['channel']) assert(len(df_long) == tfr.data.size) # test long format w/ index df_long = tfr.to_data_frame(long_format=True, index=['freq']) del df_wide, df_long # test whether data is in correct shape df = tfr.to_data_frame(index=['condition', 'epoch', 'freq', 'time']) data = tfr.data assert_array_equal(df.values[:, 0], data[:, 0, :, :].reshape(1, -1).squeeze()) # compare arbitrary observation: assert df.loc[('he', slice(None), freqs[1], times[2] * srate), ch_names[3]].iloc[0] == data[1, 3, 1, 2] # Check also for AverageTFR: tfr = tfr.average() with pytest.raises(ValueError, match='options. Valid index options are'): tfr.to_data_frame(index=['epoch', 'condition']) with pytest.raises(ValueError, match='"epoch" is not a valid option'): tfr.to_data_frame(index='epoch') with pytest.raises(TypeError, match='index must be `None` or a string '): tfr.to_data_frame(index=np.arange(400)) # test wide format df_wide = tfr.to_data_frame() assert all(np.in1d(tfr.ch_names, df_wide.columns)) assert all(np.in1d(['time', 'freq'], df_wide.columns)) # test long format df_long = tfr.to_data_frame(long_format=True) expected = ('freq', 'time', 'channel', 'ch_type', 'value') assert set(expected) == set(df_long.columns) assert set(tfr.ch_names) == set(df_long['channel']) assert(len(df_long) == tfr.data.size) # test long format w/ index df_long = tfr.to_data_frame(long_format=True, index=['freq']) del df_wide, df_long # test whether data is in correct shape df = tfr.to_data_frame(index=['freq', 'time']) data = tfr.data assert_array_equal(df.values[:, 0], data[0, :, :].reshape(1, -1).squeeze()) # compare arbitrary observation: assert df.loc[(freqs[1], times[2] * srate), ch_names[3]] == \ data[3, 1, 2] @requires_pandas @pytest.mark.parametrize('index', ('time', ['condition', 'time', 'freq'], ['freq', 'time'], ['time', 'freq'], None)) def test_to_data_frame_index(index): """Test index creation in epochs Pandas exporter.""" # Create fake EpochsTFR data: n_epos = 3 ch_names = ['EEG 001', 'EEG 002', 'EEG 003', 'EEG 004'] n_picks = len(ch_names) ch_types = ['eeg'] * n_picks n_freqs = 5 n_times = 6 data = np.random.rand(n_epos, n_picks, n_freqs, n_times) times = np.arange(6) freqs = np.arange(5) events = np.zeros((n_epos, 3), dtype=int) events[:, 0] = np.arange(n_epos) events[:, 2] = np.arange(5, 8) event_id = {k: v for v, k in zip(events[:, 2], ['ha', 'he', 'hu'])} info = mne.create_info(ch_names, 1000., ch_types) tfr = mne.time_frequency.EpochsTFR(info, data, times, freqs, events=events, event_id=event_id) df = tfr.to_data_frame(picks=[0, 2, 3], index=index) # test index order/hierarchy preservation if not isinstance(index, list): index = [index] assert (df.index.names == index) # test that non-indexed data were present as columns non_index = list(set(['condition', 'time', 'freq', 'epoch']) - set(index)) if len(non_index): assert all(np.in1d(non_index, df.columns)) @requires_pandas @pytest.mark.parametrize('time_format', (None, 'ms', 'timedelta')) def test_to_data_frame_time_format(time_format): """Test time conversion in epochs Pandas exporter.""" from pandas import Timedelta n_epos = 3 ch_names = ['EEG 001', 'EEG 002', 'EEG 003', 'EEG 004'] n_picks = len(ch_names) ch_types = ['eeg'] * n_picks n_freqs = 5 n_times = 6 data = np.random.rand(n_epos, n_picks, n_freqs, n_times) times = np.arange(6) freqs = np.arange(5) events = np.zeros((n_epos, 3), dtype=int) events[:, 0] = np.arange(n_epos) events[:, 2] = np.arange(5, 8) event_id = {k: v for v, k in zip(events[:, 2], ['ha', 'he', 'hu'])} info = mne.create_info(ch_names, 1000., ch_types) tfr = mne.time_frequency.EpochsTFR(info, data, times, freqs, events=events, event_id=event_id) # test time_format df = tfr.to_data_frame(time_format=time_format) dtypes = {None: np.float64, 'ms': np.int64, 'timedelta': Timedelta} assert isinstance(df['time'].iloc[0], dtypes[time_format])
rkmaddox/mne-python
mne/time_frequency/tests/test_tfr.py
mne/gui/_marker_gui.py
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Martin Luessi <mluessi@nmr.mgh.harvard.edu> # Denis Engemann <denis.engemann@gmail.com> # # License: BSD (3-clause) from collections import defaultdict from colorsys import hsv_to_rgb, rgb_to_hsv import copy as cp import os import os.path as op import re import numpy as np from .morph_map import read_morph_map from .parallel import parallel_func, check_n_jobs from .source_estimate import (SourceEstimate, VolSourceEstimate, _center_of_mass, extract_label_time_course, spatial_src_adjacency) from .source_space import (add_source_space_distances, SourceSpaces, read_freesurfer_lut, _import_nibabel) from .stats.cluster_level import _find_clusters, _get_components from .surface import read_surface, fast_cross_3d, mesh_edges, mesh_dist from .transforms import apply_trans from .utils import (get_subjects_dir, _check_subject, logger, verbose, warn, check_random_state, _validate_type, fill_doc, _check_option, check_version) def _blend_colors(color_1, color_2): """Blend two colors in HSV space. Parameters ---------- color_1, color_2 : None | tuple RGBA tuples with values between 0 and 1. None if no color is available. If both colors are None, the output is None. If only one is None, the output is the other color. Returns ------- color : None | tuple RGBA tuple of the combined color. Saturation, value and alpha are averaged, whereas the new hue is determined as angle half way between the two input colors' hues. """ if color_1 is None and color_2 is None: return None elif color_1 is None: return color_2 elif color_2 is None: return color_1 r_1, g_1, b_1, a_1 = color_1 h_1, s_1, v_1 = rgb_to_hsv(r_1, g_1, b_1) r_2, g_2, b_2, a_2 = color_2 h_2, s_2, v_2 = rgb_to_hsv(r_2, g_2, b_2) hue_diff = abs(h_1 - h_2) if hue_diff < 0.5: h = min(h_1, h_2) + hue_diff / 2. else: h = max(h_1, h_2) + (1. - hue_diff) / 2. h %= 1. s = (s_1 + s_2) / 2. v = (v_1 + v_2) / 2. r, g, b = hsv_to_rgb(h, s, v) a = (a_1 + a_2) / 2. color = (r, g, b, a) return color def _split_colors(color, n): """Create n colors in HSV space that occupy a gradient in value. Parameters ---------- color : tuple RGBA tuple with values between 0 and 1. n : int >= 2 Number of colors on the gradient. Returns ------- colors : tuple of tuples, len = n N RGBA tuples that occupy a gradient in value (low to high) but share saturation and hue with the input color. """ r, g, b, a = color h, s, v = rgb_to_hsv(r, g, b) gradient_range = np.sqrt(n / 10.) if v > 0.5: v_max = min(0.95, v + gradient_range / 2) v_min = max(0.05, v_max - gradient_range) else: v_min = max(0.05, v - gradient_range / 2) v_max = min(0.95, v_min + gradient_range) hsv_colors = ((h, s, v_) for v_ in np.linspace(v_min, v_max, n)) rgb_colors = (hsv_to_rgb(h_, s_, v_) for h_, s_, v_ in hsv_colors) rgba_colors = ((r_, g_, b_, a,) for r_, g_, b_ in rgb_colors) return tuple(rgba_colors) def _n_colors(n, bytes_=False, cmap='hsv'): """Produce a list of n unique RGBA color tuples based on a colormap. Parameters ---------- n : int Number of colors. bytes : bool Return colors as integers values between 0 and 255 (instead of floats between 0 and 1). cmap : str Which colormap to use. Returns ------- colors : array, shape (n, 4) RGBA color values. """ n_max = 2 ** 10 if n > n_max: raise NotImplementedError("Can't produce more than %i unique " "colors" % n_max) from matplotlib.cm import get_cmap cm = get_cmap(cmap, n_max) pos = np.linspace(0, 1, n, False) colors = cm(pos, bytes=bytes_) if bytes_: # make sure colors are unique for ii, c in enumerate(colors): if np.any(np.all(colors[:ii] == c, 1)): raise RuntimeError('Could not get %d unique colors from %s ' 'colormap. Try using a different colormap.' % (n, cmap)) return colors @fill_doc class Label(object): """A FreeSurfer/MNE label with vertices restricted to one hemisphere. Labels can be combined with the ``+`` operator: * Duplicate vertices are removed. * If duplicate vertices have conflicting position values, an error is raised. * Values of duplicate vertices are summed. Parameters ---------- vertices : array, shape (N,) Vertex indices (0 based). pos : array, shape (N, 3) | None Locations in meters. If None, then zeros are used. values : array, shape (N,) | None Values at the vertices. If None, then ones are used. hemi : 'lh' | 'rh' Hemisphere to which the label applies. comment : str Kept as information but not used by the object itself. name : str Kept as information but not used by the object itself. filename : str Kept as information but not used by the object itself. subject : str | None Name of the subject the label is from. color : None | matplotlib color Default label color and alpha (e.g., ``(1., 0., 0., 1.)`` for red). %(verbose)s Attributes ---------- color : None | tuple Default label color, represented as RGBA tuple with values between 0 and 1. comment : str Comment from the first line of the label file. hemi : 'lh' | 'rh' Hemisphere. name : None | str A name for the label. It is OK to change that attribute manually. pos : array, shape (N, 3) Locations in meters. subject : str | None Subject name. It is best practice to set this to the proper value on initialization, but it can also be set manually. values : array, shape (N,) Values at the vertices. %(verbose)s vertices : array, shape (N,) Vertex indices (0 based) """ @verbose def __init__(self, vertices=(), pos=None, values=None, hemi=None, comment="", name=None, filename=None, subject=None, color=None, verbose=None): # noqa: D102 # check parameters if not isinstance(hemi, str): raise ValueError('hemi must be a string, not %s' % type(hemi)) vertices = np.asarray(vertices, int) if np.any(np.diff(vertices.astype(int)) <= 0): raise ValueError('Vertices must be ordered in increasing order.') if color is not None: from matplotlib.colors import colorConverter color = colorConverter.to_rgba(color) if values is None: values = np.ones(len(vertices)) else: values = np.asarray(values) if pos is None: pos = np.zeros((len(vertices), 3)) else: pos = np.asarray(pos) if not (len(vertices) == len(values) == len(pos)): raise ValueError("vertices, values and pos need to have same " "length (number of vertices)") # name if name is None and filename is not None: name = op.basename(filename[:-6]) self.vertices = vertices self.pos = pos self.values = values self.hemi = hemi self.comment = comment self.verbose = verbose self.subject = _check_subject(None, subject, raise_error=False) self.color = color self.name = name self.filename = filename def __setstate__(self, state): # noqa: D105 self.vertices = state['vertices'] self.pos = state['pos'] self.values = state['values'] self.hemi = state['hemi'] self.comment = state['comment'] self.verbose = state['verbose'] self.subject = state.get('subject', None) self.color = state.get('color', None) self.name = state['name'] self.filename = state['filename'] def __getstate__(self): # noqa: D105 out = dict(vertices=self.vertices, pos=self.pos, values=self.values, hemi=self.hemi, comment=self.comment, verbose=self.verbose, subject=self.subject, color=self.color, name=self.name, filename=self.filename) return out def __repr__(self): # noqa: D105 name = 'unknown, ' if self.subject is None else self.subject + ', ' name += repr(self.name) if self.name is not None else "unnamed" n_vert = len(self) return "<Label | %s, %s : %i vertices>" % (name, self.hemi, n_vert) def __len__(self): """Return the number of vertices. Returns ------- n_vertices : int The number of vertices. """ return len(self.vertices) def __add__(self, other): """Add Labels.""" _validate_type(other, (Label, BiHemiLabel), 'other') if isinstance(other, BiHemiLabel): return other + self else: # isinstance(other, Label) if self.subject != other.subject: raise ValueError('Label subject parameters must match, got ' '"%s" and "%s". Consider setting the ' 'subject parameter on initialization, or ' 'setting label.subject manually before ' 'combining labels.' % (self.subject, other.subject)) if self.hemi != other.hemi: name = '%s + %s' % (self.name, other.name) if self.hemi == 'lh': lh, rh = self.copy(), other.copy() else: lh, rh = other.copy(), self.copy() color = _blend_colors(self.color, other.color) return BiHemiLabel(lh, rh, name, color) # check for overlap duplicates = np.intersect1d(self.vertices, other.vertices) n_dup = len(duplicates) if n_dup: self_dup = [np.where(self.vertices == d)[0][0] for d in duplicates] other_dup = [np.where(other.vertices == d)[0][0] for d in duplicates] if not np.all(self.pos[self_dup] == other.pos[other_dup]): err = ("Labels %r and %r: vertices overlap but differ in " "position values" % (self.name, other.name)) raise ValueError(err) isnew = np.array([v not in duplicates for v in other.vertices]) vertices = np.hstack((self.vertices, other.vertices[isnew])) pos = np.vstack((self.pos, other.pos[isnew])) # find position of other's vertices in new array tgt_idx = [np.where(vertices == v)[0][0] for v in other.vertices] n_self = len(self.values) n_other = len(other.values) new_len = n_self + n_other - n_dup values = np.zeros(new_len, dtype=self.values.dtype) values[:n_self] += self.values values[tgt_idx] += other.values else: vertices = np.hstack((self.vertices, other.vertices)) pos = np.vstack((self.pos, other.pos)) values = np.hstack((self.values, other.values)) indcs = np.argsort(vertices) vertices, pos, values = vertices[indcs], pos[indcs, :], values[indcs] comment = "%s + %s" % (self.comment, other.comment) name0 = self.name if self.name else 'unnamed' name1 = other.name if other.name else 'unnamed' name = "%s + %s" % (name0, name1) color = _blend_colors(self.color, other.color) verbose = self.verbose or other.verbose label = Label(vertices, pos, values, self.hemi, comment, name, None, self.subject, color, verbose) return label def __sub__(self, other): """Subtract Labels.""" _validate_type(other, (Label, BiHemiLabel), 'other') if isinstance(other, BiHemiLabel): if self.hemi == 'lh': return self - other.lh else: return self - other.rh else: # isinstance(other, Label): if self.subject != other.subject: raise ValueError('Label subject parameters must match, got ' '"%s" and "%s". Consider setting the ' 'subject parameter on initialization, or ' 'setting label.subject manually before ' 'combining labels.' % (self.subject, other.subject)) if self.hemi == other.hemi: keep = np.in1d(self.vertices, other.vertices, True, invert=True) else: keep = np.arange(len(self.vertices)) name = "%s - %s" % (self.name or 'unnamed', other.name or 'unnamed') return Label(self.vertices[keep], self.pos[keep], self.values[keep], self.hemi, self.comment, name, None, self.subject, self.color, self.verbose) def save(self, filename): r"""Write to disk as FreeSurfer \*.label file. Parameters ---------- filename : str Path to label file to produce. Notes ----- Note that due to file specification limitations, the Label's subject and color attributes are not saved to disk. """ write_label(filename, self) def copy(self): """Copy the label instance. Returns ------- label : instance of Label The copied label. """ return cp.deepcopy(self) def fill(self, src, name=None): """Fill the surface between sources for a source space label. Parameters ---------- src : SourceSpaces Source space in which the label was defined. If a source space is provided, the label is expanded to fill in surface vertices that lie between the vertices included in the source space. For the added vertices, ``pos`` is filled in with positions from the source space, and ``values`` is filled in from the closest source space vertex. name : None | str Name for the new Label (default is self.name). Returns ------- label : Label The label covering the same vertices in source space but also including intermediate surface vertices. See Also -------- Label.restrict Label.smooth """ # find source space patch info if len(self.vertices) == 0: return self.copy() hemi_src = _get_label_src(self, src) if not np.all(np.in1d(self.vertices, hemi_src['vertno'])): msg = "Source space does not contain all of the label's vertices" raise ValueError(msg) if hemi_src['nearest'] is None: warn("Source space is being modified in place because patch " "information is needed. To avoid this in the future, run " "mne.add_source_space_distances() on the source space " "and save it to disk.") if check_version('scipy', '1.3'): dist_limit = 0 else: warn('SciPy < 1.3 detected, adding source space patch ' 'information will be slower. Consider upgrading SciPy.') dist_limit = np.inf add_source_space_distances(src, dist_limit=dist_limit) nearest = hemi_src['nearest'] # find new vertices include = np.in1d(nearest, self.vertices, False) vertices = np.nonzero(include)[0] # values nearest_in_label = np.digitize(nearest[vertices], self.vertices, True) values = self.values[nearest_in_label] # pos pos = hemi_src['rr'][vertices] name = self.name if name is None else name label = Label(vertices, pos, values, self.hemi, self.comment, name, None, self.subject, self.color) return label def restrict(self, src, name=None): """Restrict a label to a source space. Parameters ---------- src : instance of SourceSpaces The source spaces to use to restrict the label. name : None | str Name for the new Label (default is self.name). Returns ------- label : instance of Label The Label restricted to the set of source space vertices. See Also -------- Label.fill Notes ----- .. versionadded:: 0.20 """ if len(self.vertices) == 0: return self.copy() hemi_src = _get_label_src(self, src) mask = np.in1d(self.vertices, hemi_src['vertno']) name = self.name if name is None else name label = Label(self.vertices[mask], self.pos[mask], self.values[mask], self.hemi, self.comment, name, None, self.subject, self.color) return label @verbose def smooth(self, subject=None, smooth=2, grade=None, subjects_dir=None, n_jobs=1, verbose=None): """Smooth the label. Useful for filling in labels made in a decimated source space for display. Parameters ---------- subject : str | None The name of the subject used. If None, the value will be taken from self.subject. smooth : int Number of iterations for the smoothing of the surface data. Cannot be None here since not all vertices are used. For a grade of 5 (e.g., fsaverage), a smoothing of 2 will fill a label. grade : int, list of shape (2,), array, or None Resolution of the icosahedral mesh (typically 5). If None, all vertices will be used (potentially filling the surface). If a list, values will be morphed to the set of vertices specified in grade[0] and grade[1], assuming that these are vertices for the left and right hemispheres. Note that specifying the vertices (e.g., grade=[np.arange(10242), np.arange(10242)] for fsaverage on a standard grade 5 source space) can be substantially faster than computing vertex locations. If one array is used, it is assumed that all vertices belong to the hemisphere of the label. To create a label filling the surface, use None. %(subjects_dir)s %(n_jobs)s %(verbose_meth)s Returns ------- label : instance of Label The smoothed label. Notes ----- This function will set label.pos to be all zeros. If the positions on the new surface are required, consider using mne.read_surface with ``label.vertices``. """ subject = _check_subject(self.subject, subject) return self.morph(subject, subject, smooth, grade, subjects_dir, n_jobs, verbose) @verbose def morph(self, subject_from=None, subject_to=None, smooth=5, grade=None, subjects_dir=None, n_jobs=1, verbose=None): """Morph the label. Useful for transforming a label from one subject to another. Parameters ---------- subject_from : str | None The name of the subject of the current label. If None, the initial subject will be taken from self.subject. subject_to : str The name of the subject to morph the label to. This will be put in label.subject of the output label file. smooth : int Number of iterations for the smoothing of the surface data. Cannot be None here since not all vertices are used. grade : int, list of shape (2,), array, or None Resolution of the icosahedral mesh (typically 5). If None, all vertices will be used (potentially filling the surface). If a list, values will be morphed to the set of vertices specified in grade[0] and grade[1], assuming that these are vertices for the left and right hemispheres. Note that specifying the vertices (e.g., ``grade=[np.arange(10242), np.arange(10242)]`` for fsaverage on a standard grade 5 source space) can be substantially faster than computing vertex locations. If one array is used, it is assumed that all vertices belong to the hemisphere of the label. To create a label filling the surface, use None. %(subjects_dir)s %(n_jobs)s %(verbose_meth)s Returns ------- label : instance of Label The morphed label. See Also -------- mne.morph_labels : Morph a set of labels. Notes ----- This function will set label.pos to be all zeros. If the positions on the new surface are required, consider using `mne.read_surface` with ``label.vertices``. """ from .morph import compute_source_morph, grade_to_vertices subject_from = _check_subject(self.subject, subject_from) if not isinstance(subject_to, str): raise TypeError('"subject_to" must be entered as a string') if not isinstance(smooth, int): raise TypeError('smooth must be an integer') if np.all(self.values == 0): raise ValueError('Morphing label with all zero values will result ' 'in the label having no vertices. Consider using ' 'something like label.values.fill(1.0).') idx = 0 if self.hemi == 'lh' else 1 if isinstance(grade, np.ndarray): grade_ = [np.array([], int)] * 2 grade_[idx] = grade grade = grade_ del grade_ grade = grade_to_vertices(subject_to, grade, subjects_dir=subjects_dir) spacing = [np.array([], int)] * 2 spacing[idx] = grade[idx] vertices = [np.array([], int)] * 2 vertices[idx] = self.vertices data = self.values[:, np.newaxis] assert len(data) == sum(len(v) for v in vertices) stc = SourceEstimate(data, vertices, tmin=1, tstep=1, subject=subject_from) stc = compute_source_morph( stc, subject_from, subject_to, spacing=spacing, smooth=smooth, subjects_dir=subjects_dir, warn=False).apply(stc) inds = np.nonzero(stc.data)[0] self.values = stc.data[inds, :].ravel() self.pos = np.zeros((len(inds), 3)) self.vertices = stc.vertices[idx][inds] self.subject = subject_to return self @fill_doc def split(self, parts=2, subject=None, subjects_dir=None, freesurfer=False): """Split the Label into two or more parts. Parameters ---------- parts : int >= 2 | tuple of str | str Number of labels to create (default is 2), or tuple of strings specifying label names for new labels (from posterior to anterior), or 'contiguous' to split the label into connected components. If a number or 'contiguous' is specified, names of the new labels will be the input label's name with div1, div2 etc. appended. subject : None | str Subject which this label belongs to (needed to locate surface file; should only be specified if it is not specified in the label). %(subjects_dir)s freesurfer : bool By default (``False``) ``split_label`` uses an algorithm that is slightly optimized for performance and numerical precision. Set ``freesurfer`` to ``True`` in order to replicate label splits from FreeSurfer's ``mris_divide_parcellation``. Returns ------- labels : list of Label, shape (n_parts,) The labels, starting from the lowest to the highest end of the projection axis. Notes ----- If using 'contiguous' split, you must ensure that the label being split uses the same triangular resolution as the surface mesh files in ``subjects_dir`` Also, some small fringe labels may be returned that are close (but not connected) to the large components. The spatial split finds the label's principal eigen-axis on the spherical surface, projects all label vertex coordinates onto this axis, and divides them at regular spatial intervals. """ if isinstance(parts, str) and parts == 'contiguous': return _split_label_contig(self, subject, subjects_dir) elif isinstance(parts, (tuple, int)): return split_label(self, parts, subject, subjects_dir, freesurfer) else: raise ValueError("Need integer, tuple of strings, or string " "('contiguous'). Got %s)" % type(parts)) def get_vertices_used(self, vertices=None): """Get the source space's vertices inside the label. Parameters ---------- vertices : ndarray of int, shape (n_vertices,) | None The set of vertices to compare the label to. If None, equals to ``np.arange(10242)``. Defaults to None. Returns ------- label_verts : ndarray of in, shape (n_label_vertices,) The vertices of the label corresponding used by the data. """ if vertices is None: vertices = np.arange(10242) label_verts = vertices[np.in1d(vertices, self.vertices)] return label_verts def get_tris(self, tris, vertices=None): """Get the source space's triangles inside the label. Parameters ---------- tris : ndarray of int, shape (n_tris, 3) The set of triangles corresponding to the vertices in a source space. vertices : ndarray of int, shape (n_vertices,) | None The set of vertices to compare the label to. If None, equals to ``np.arange(10242)``. Defaults to None. Returns ------- label_tris : ndarray of int, shape (n_tris, 3) The subset of tris used by the label. """ vertices_ = self.get_vertices_used(vertices) selection = np.all(np.in1d(tris, vertices_).reshape(tris.shape), axis=1) label_tris = tris[selection] if len(np.unique(label_tris)) < len(vertices_): logger.info('Surprising label structure. Trying to repair ' 'triangles.') dropped_vertices = np.setdiff1d(vertices_, label_tris) n_dropped = len(dropped_vertices) assert n_dropped == (len(vertices_) - len(np.unique(label_tris))) # put missing vertices as extra zero-length triangles add_tris = (dropped_vertices + np.zeros((len(dropped_vertices), 3), dtype=int).T) label_tris = np.r_[label_tris, add_tris.T] assert len(np.unique(label_tris)) == len(vertices_) return label_tris @fill_doc def center_of_mass(self, subject=None, restrict_vertices=False, subjects_dir=None, surf='sphere'): """Compute the center of mass of the label. This function computes the spatial center of mass on the surface as in :footcite:`LarsonLee2013`. Parameters ---------- subject : str | None The subject the label is defined for. restrict_vertices : bool | array of int | instance of SourceSpaces If True, returned vertex will be one from the label. Otherwise, it could be any vertex from surf. If an array of int, the returned vertex will come from that array. If instance of SourceSpaces (as of 0.13), the returned vertex will be from the given source space. For most accuruate estimates, do not restrict vertices. %(subjects_dir)s surf : str The surface to use for Euclidean distance center of mass finding. The default here is "sphere", which finds the center of mass on the spherical surface to help avoid potential issues with cortical folding. Returns ------- vertex : int Vertex of the spatial center of mass for the inferred hemisphere, with each vertex weighted by its label value. See Also -------- SourceEstimate.center_of_mass vertex_to_mni Notes ----- .. versionadded:: 0.13 References ---------- .. footbibliography:: """ if not isinstance(surf, str): raise TypeError('surf must be a string, got %s' % (type(surf),)) subject = _check_subject(self.subject, subject) if np.any(self.values < 0): raise ValueError('Cannot compute COM with negative values') if np.all(self.values == 0): raise ValueError('Cannot compute COM with all values == 0. For ' 'structural labels, consider setting to ones via ' 'label.values[:] = 1.') vertex = _center_of_mass(self.vertices, self.values, self.hemi, surf, subject, subjects_dir, restrict_vertices) return vertex def _get_label_src(label, src): _validate_type(src, SourceSpaces, 'src') if src.kind != 'surface': raise RuntimeError('Cannot operate on SourceSpaces that are not ' 'surface type, got %s' % (src.kind,)) if label.hemi == 'lh': hemi_src = src[0] else: hemi_src = src[1] return hemi_src class BiHemiLabel(object): """A freesurfer/MNE label with vertices in both hemispheres. Parameters ---------- lh : Label Label for the left hemisphere. rh : Label Label for the right hemisphere. name : None | str Name for the label. color : None | color Label color and alpha (e.g., ``(1., 0., 0., 1.)`` for red). Note that due to file specification limitations, the color isn't saved to or loaded from files written to disk. Attributes ---------- lh : Label Label for the left hemisphere. rh : Label Label for the right hemisphere. name : None | str A name for the label. It is OK to change that attribute manually. subject : str | None Subject the label is from. """ def __init__(self, lh, rh, name=None, color=None): # noqa: D102 if lh.subject != rh.subject: raise ValueError('lh.subject (%s) and rh.subject (%s) must ' 'agree' % (lh.subject, rh.subject)) self.lh = lh self.rh = rh self.name = name self.subject = lh.subject self.color = color self.hemi = 'both' def __repr__(self): # noqa: D105 temp = "<BiHemiLabel | %s, lh : %i vertices, rh : %i vertices>" name = 'unknown, ' if self.subject is None else self.subject + ', ' name += repr(self.name) if self.name is not None else "unnamed" return temp % (name, len(self.lh), len(self.rh)) def __len__(self): """Return the number of vertices. Returns ------- n_vertices : int The number of vertices. """ return len(self.lh) + len(self.rh) def __add__(self, other): """Add labels.""" if isinstance(other, Label): if other.hemi == 'lh': lh = self.lh + other rh = self.rh else: lh = self.lh rh = self.rh + other elif isinstance(other, BiHemiLabel): lh = self.lh + other.lh rh = self.rh + other.rh else: raise TypeError("Need: Label or BiHemiLabel. Got: %r" % other) name = '%s + %s' % (self.name, other.name) color = _blend_colors(self.color, other.color) return BiHemiLabel(lh, rh, name, color) def __sub__(self, other): """Subtract labels.""" _validate_type(other, (Label, BiHemiLabel), 'other') if isinstance(other, Label): if other.hemi == 'lh': lh = self.lh - other rh = self.rh else: rh = self.rh - other lh = self.lh else: # isinstance(other, BiHemiLabel) lh = self.lh - other.lh rh = self.rh - other.rh if len(lh.vertices) == 0: return rh elif len(rh.vertices) == 0: return lh else: name = '%s - %s' % (self.name, other.name) return BiHemiLabel(lh, rh, name, self.color) def read_label(filename, subject=None, color=None): """Read FreeSurfer Label file. Parameters ---------- filename : str Path to label file. subject : str | None Name of the subject the data are defined for. It is good practice to set this attribute to avoid combining incompatible labels and SourceEstimates (e.g., ones from other subjects). Note that due to file specification limitations, the subject name isn't saved to or loaded from files written to disk. color : None | matplotlib color Default label color and alpha (e.g., ``(1., 0., 0., 1.)`` for red). Note that due to file specification limitations, the color isn't saved to or loaded from files written to disk. Returns ------- label : Label Instance of Label object with attributes: - ``comment``: comment from the first line of the label file - ``vertices``: vertex indices (0 based, column 1) - ``pos``: locations in meters (columns 2 - 4 divided by 1000) - ``values``: values at the vertices (column 5) See Also -------- read_labels_from_annot write_labels_to_annot """ if subject is not None and not isinstance(subject, str): raise TypeError('subject must be a string') # find hemi basename = op.basename(filename) if basename.endswith('lh.label') or basename.startswith('lh.'): hemi = 'lh' elif basename.endswith('rh.label') or basename.startswith('rh.'): hemi = 'rh' else: raise ValueError('Cannot find which hemisphere it is. File should end' ' with lh.label or rh.label: %s' % (basename,)) # find name if basename.startswith(('lh.', 'rh.')): basename_ = basename[3:] if basename.endswith('.label'): basename_ = basename[:-6] else: basename_ = basename[:-9] name = "%s-%s" % (basename_, hemi) # read the file with open(filename, 'r') as fid: comment = fid.readline().replace('\n', '')[1:] nv = int(fid.readline()) data = np.empty((5, nv)) for i, line in enumerate(fid): data[:, i] = line.split() # let's make sure everything is ordered correctly vertices = np.array(data[0], dtype=np.int32) pos = 1e-3 * data[1:4].T values = data[4] order = np.argsort(vertices) vertices = vertices[order] pos = pos[order] values = values[order] label = Label(vertices, pos, values, hemi, comment, name, filename, subject, color) return label @verbose def write_label(filename, label, verbose=None): """Write a FreeSurfer label. Parameters ---------- filename : str Path to label file to produce. label : Label The label object to save. %(verbose)s See Also -------- write_labels_to_annot Notes ----- Note that due to file specification limitations, the Label's subject and color attributes are not saved to disk. """ hemi = label.hemi path_head, name = op.split(filename) if name.endswith('.label'): name = name[:-6] if not (name.startswith(hemi) or name.endswith(hemi)): name += '-' + hemi filename = op.join(path_head, name) + '.label' logger.info('Saving label to : %s' % filename) with open(filename, 'wb') as fid: n_vertices = len(label.vertices) data = np.zeros((n_vertices, 5), dtype=np.float64) data[:, 0] = label.vertices data[:, 1:4] = 1e3 * label.pos data[:, 4] = label.values fid.write(b'#%s\n' % label.comment.encode()) fid.write(b'%d\n' % n_vertices) for d in data: fid.write(b'%d %f %f %f %f\n' % tuple(d)) def _prep_label_split(label, subject=None, subjects_dir=None): """Get label and subject information prior to label splitting.""" # If necessary, find the label if isinstance(label, BiHemiLabel): raise TypeError("Can only split labels restricted to one hemisphere.") elif isinstance(label, str): label = read_label(label) # Find the subject subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) if label.subject is None and subject is None: raise ValueError("The subject needs to be specified.") elif subject is None: subject = label.subject elif label.subject is None: pass elif subject != label.subject: raise ValueError("The label specifies a different subject (%r) from " "the subject parameter (%r)." % label.subject, subject) return label, subject, subjects_dir def _split_label_contig(label_to_split, subject=None, subjects_dir=None): """Split label into contiguous regions (i.e., connected components). Parameters ---------- label_to_split : Label | str Label which is to be split (Label object or path to a label file). subject : None | str Subject which this label belongs to (needed to locate surface file; should only be specified if it is not specified in the label). %(subjects_dir)s Returns ------- labels : list of Label The contiguous labels, in order of descending size. """ # Convert to correct input if necessary label_to_split, subject, subjects_dir = _prep_label_split(label_to_split, subject, subjects_dir) # Find the spherical surface to get vertices and tris surf_fname = '.'.join((label_to_split.hemi, 'sphere')) surf_path = op.join(subjects_dir, subject, 'surf', surf_fname) surface_points, surface_tris = read_surface(surf_path) # Get vertices we want to keep and compute mesh edges verts_arr = label_to_split.vertices edges_all = mesh_edges(surface_tris) # Subselect rows and cols of vertices that belong to the label select_edges = edges_all[verts_arr][:, verts_arr].tocoo() # Compute connected components and store as lists of vertex numbers comp_labels = _get_components(verts_arr, select_edges) # Convert to indices in the original surface space label_divs = [] for comp in comp_labels: label_divs.append(verts_arr[comp]) # Construct label division names n_parts = len(label_divs) if label_to_split.name.endswith(('lh', 'rh')): basename = label_to_split.name[:-3] name_ext = label_to_split.name[-3:] else: basename = label_to_split.name name_ext = '' name_pattern = "%s_div%%i%s" % (basename, name_ext) names = tuple(name_pattern % i for i in range(1, n_parts + 1)) # Colors if label_to_split.color is None: colors = (None,) * n_parts else: colors = _split_colors(label_to_split.color, n_parts) # Sort label divisions by their size (in vertices) label_divs.sort(key=lambda x: len(x), reverse=True) labels = [] for div, name, color in zip(label_divs, names, colors): # Get indices of dipoles within this division of the label verts = np.array(sorted(list(div)), int) vert_indices = np.in1d(verts_arr, verts, assume_unique=True) # Set label attributes pos = label_to_split.pos[vert_indices] values = label_to_split.values[vert_indices] hemi = label_to_split.hemi comment = label_to_split.comment lbl = Label(verts, pos, values, hemi, comment, name, None, subject, color) labels.append(lbl) return labels @fill_doc def split_label(label, parts=2, subject=None, subjects_dir=None, freesurfer=False): """Split a Label into two or more parts. Parameters ---------- label : Label | str Label which is to be split (Label object or path to a label file). parts : int >= 2 | tuple of str A sequence of strings specifying label names for the new labels (from posterior to anterior), or the number of new labels to create (default is 2). If a number is specified, names of the new labels will be the input label's name with div1, div2 etc. appended. subject : None | str Subject which this label belongs to (needed to locate surface file; should only be specified if it is not specified in the label). %(subjects_dir)s freesurfer : bool By default (``False``) ``split_label`` uses an algorithm that is slightly optimized for performance and numerical precision. Set ``freesurfer`` to ``True`` in order to replicate label splits from FreeSurfer's ``mris_divide_parcellation``. Returns ------- labels : list of Label, shape (n_parts,) The labels, starting from the lowest to the highest end of the projection axis. Notes ----- Works by finding the label's principal eigen-axis on the spherical surface, projecting all label vertex coordinates onto this axis and dividing them at regular spatial intervals. """ from scipy import linalg label, subject, subjects_dir = _prep_label_split(label, subject, subjects_dir) # find the parts if np.isscalar(parts): n_parts = int(parts) if label.name.endswith(('lh', 'rh')): basename = label.name[:-3] name_ext = label.name[-3:] else: basename = label.name name_ext = '' name_pattern = "%s_div%%i%s" % (basename, name_ext) names = tuple(name_pattern % i for i in range(1, n_parts + 1)) else: names = parts n_parts = len(names) if n_parts < 2: raise ValueError("Can't split label into %i parts" % n_parts) # find the spherical surface surf_fname = '.'.join((label.hemi, 'sphere')) surf_path = op.join(subjects_dir, subject, "surf", surf_fname) surface_points, surface_tris = read_surface(surf_path) # find the label coordinates on the surface points = surface_points[label.vertices] center = np.mean(points, axis=0) centered_points = points - center # find the label's normal if freesurfer: # find the Freesurfer vertex closest to the center distance = np.sqrt(np.sum(centered_points ** 2, axis=1)) i_closest = np.argmin(distance) closest_vertex = label.vertices[i_closest] # find the normal according to freesurfer convention idx = np.any(surface_tris == closest_vertex, axis=1) tris_for_normal = surface_tris[idx] r1 = surface_points[tris_for_normal[:, 0], :] r2 = surface_points[tris_for_normal[:, 1], :] r3 = surface_points[tris_for_normal[:, 2], :] tri_normals = fast_cross_3d((r2 - r1), (r3 - r1)) normal = np.mean(tri_normals, axis=0) normal /= linalg.norm(normal) else: # Normal of the center normal = center / linalg.norm(center) # project all vertex coordinates on the tangential plane for this point q, _ = linalg.qr(normal[:, np.newaxis]) tangent_u = q[:, 1:] m_obs = np.dot(centered_points, tangent_u) # find principal eigendirection m_cov = np.dot(m_obs.T, m_obs) w, vr = linalg.eig(m_cov) i = np.argmax(w) eigendir = vr[:, i] # project back into 3d space axis = np.dot(tangent_u, eigendir) # orient them from posterior to anterior if axis[1] < 0: axis *= -1 # project the label on the axis proj = np.dot(points, axis) # assign mark (new label index) proj -= proj.min() proj /= (proj.max() / n_parts) mark = proj // 1 mark[mark == n_parts] = n_parts - 1 # colors if label.color is None: colors = (None,) * n_parts else: colors = _split_colors(label.color, n_parts) # construct new labels labels = [] for i, name, color in zip(range(n_parts), names, colors): idx = (mark == i) vert = label.vertices[idx] pos = label.pos[idx] values = label.values[idx] hemi = label.hemi comment = label.comment lbl = Label(vert, pos, values, hemi, comment, name, None, subject, color) labels.append(lbl) return labels def label_sign_flip(label, src): """Compute sign for label averaging. Parameters ---------- label : Label | BiHemiLabel A label. src : SourceSpaces The source space over which the label is defined. Returns ------- flip : array Sign flip vector (contains 1 or -1). """ from scipy import linalg if len(src) != 2: raise ValueError('Only source spaces with 2 hemisphers are accepted') lh_vertno = src[0]['vertno'] rh_vertno = src[1]['vertno'] # get source orientations ori = list() if label.hemi in ('lh', 'both'): vertices = label.vertices if label.hemi == 'lh' else label.lh.vertices vertno_sel = np.intersect1d(lh_vertno, vertices) ori.append(src[0]['nn'][vertno_sel]) if label.hemi in ('rh', 'both'): vertices = label.vertices if label.hemi == 'rh' else label.rh.vertices vertno_sel = np.intersect1d(rh_vertno, vertices) ori.append(src[1]['nn'][vertno_sel]) if len(ori) == 0: raise Exception('Unknown hemisphere type "%s"' % (label.hemi,)) ori = np.concatenate(ori, axis=0) if len(ori) == 0: return np.array([], int) _, _, Vh = linalg.svd(ori, full_matrices=False) # The sign of Vh is ambiguous, so we should align to the max-positive # (outward) direction dots = np.dot(ori, Vh[0]) if np.mean(dots) < 0: dots *= -1 # Comparing to the direction of the first right singular vector flip = np.sign(dots) return flip @verbose def stc_to_label(stc, src=None, smooth=True, connected=False, subjects_dir=None, verbose=None): """Compute a label from the non-zero sources in an stc object. Parameters ---------- stc : SourceEstimate The source estimates. src : SourceSpaces | str | None The source space over which the source estimates are defined. If it's a string it should the subject name (e.g. fsaverage). Can be None if stc.subject is not None. smooth : bool Fill in vertices on the cortical surface that are not in the source space based on the closest source space vertex (requires src to be a SourceSpace). connected : bool If True a list of connected labels will be returned in each hemisphere. The labels are ordered in decreasing order depending of the maximum value in the stc. %(subjects_dir)s %(verbose)s Returns ------- labels : list of Label | list of list of Label The generated labels. If connected is False, it returns a list of Labels (one per hemisphere). If no Label is available in a hemisphere, None is returned. If connected is True, it returns for each hemisphere a list of connected labels ordered in decreasing order depending of the maximum value in the stc. If no Label is available in an hemisphere, an empty list is returned. """ if not isinstance(smooth, bool): raise ValueError('smooth should be True or False. Got %s.' % smooth) src = stc.subject if src is None else src if src is None: raise ValueError('src cannot be None if stc.subject is None') if isinstance(src, str): subject = src else: subject = stc.subject if not isinstance(stc, SourceEstimate): raise ValueError('SourceEstimate should be surface source estimates') if isinstance(src, str): if connected: raise ValueError('The option to return only connected labels is ' 'only available if source spaces are provided.') if smooth: msg = ("stc_to_label with smooth=True requires src to be an " "instance of SourceSpace") raise ValueError(msg) subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) surf_path_from = op.join(subjects_dir, src, 'surf') rr_lh, tris_lh = read_surface(op.join(surf_path_from, 'lh.white')) rr_rh, tris_rh = read_surface(op.join(surf_path_from, 'rh.white')) rr = [rr_lh, rr_rh] tris = [tris_lh, tris_rh] else: if not isinstance(src, SourceSpaces): raise TypeError('src must be a string or a set of source spaces') if len(src) != 2: raise ValueError('source space should contain the 2 hemispheres') rr = [1e3 * src[0]['rr'], 1e3 * src[1]['rr']] tris = [src[0]['tris'], src[1]['tris']] src_conn = spatial_src_adjacency(src).tocsr() labels = [] cnt = 0 cnt_full = 0 for hemi_idx, (hemi, this_vertno, this_tris, this_rr) in enumerate( zip(['lh', 'rh'], stc.vertices, tris, rr)): this_data = stc.data[cnt:cnt + len(this_vertno)] if connected: # we know src *must* be a SourceSpaces now vertno = np.where(src[hemi_idx]['inuse'])[0] if not len(np.setdiff1d(this_vertno, vertno)) == 0: raise RuntimeError('stc contains vertices not present ' 'in source space, did you morph?') tmp = np.zeros((len(vertno), this_data.shape[1])) this_vertno_idx = np.searchsorted(vertno, this_vertno) tmp[this_vertno_idx] = this_data this_data = tmp offset = cnt_full + len(this_data) this_src_adj = src_conn[cnt_full:offset, cnt_full:offset].tocoo() this_data_abs_max = np.abs(this_data).max(axis=1) clusters, _ = _find_clusters(this_data_abs_max, 0., adjacency=this_src_adj) cnt_full += len(this_data) # Then order clusters in descending order based on maximum value clusters_max = np.argsort([np.max(this_data_abs_max[c]) for c in clusters])[::-1] clusters = [clusters[k] for k in clusters_max] clusters = [vertno[c] for c in clusters] else: clusters = [this_vertno[np.any(this_data, axis=1)]] cnt += len(this_vertno) clusters = [c for c in clusters if len(c) > 0] if len(clusters) == 0: if not connected: this_labels = None else: this_labels = [] else: this_labels = [] colors = _n_colors(len(clusters)) for c, color in zip(clusters, colors): idx_use = c label = Label(idx_use, this_rr[idx_use], None, hemi, 'Label from stc', subject=subject, color=color) if smooth: label = label.fill(src) this_labels.append(label) if not connected: this_labels = this_labels[0] labels.append(this_labels) return labels def _verts_within_dist(graph, sources, max_dist): """Find all vertices wihin a maximum geodesic distance from source. Parameters ---------- graph : scipy.sparse.csr_matrix Sparse matrix with distances between adjacent vertices. sources : list of int Source vertices. max_dist : float Maximum geodesic distance. Returns ------- verts : array Vertices within max_dist. dist : array Distances from source vertex. """ dist_map = {} verts_added_last = [] for source in sources: dist_map[source] = 0 verts_added_last.append(source) # add neighbors until no more neighbors within max_dist can be found while len(verts_added_last) > 0: verts_added = [] for i in verts_added_last: v_dist = dist_map[i] row = graph[i, :] neighbor_vert = row.indices neighbor_dist = row.data for j, d in zip(neighbor_vert, neighbor_dist): n_dist = v_dist + d if j in dist_map: if n_dist < dist_map[j]: dist_map[j] = n_dist else: if n_dist <= max_dist: dist_map[j] = n_dist # we found a new vertex within max_dist verts_added.append(j) verts_added_last = verts_added verts = np.sort(np.array(list(dist_map.keys()), int)) dist = np.array([dist_map[v] for v in verts], int) return verts, dist def _grow_labels(seeds, extents, hemis, names, dist, vert, subject): """Parallelize grow_labels.""" labels = [] for seed, extent, hemi, name in zip(seeds, extents, hemis, names): label_verts, label_dist = _verts_within_dist(dist[hemi], seed, extent) # create a label if len(seed) == 1: seed_repr = str(seed) else: seed_repr = ','.join(map(str, seed)) comment = 'Circular label: seed=%s, extent=%0.1fmm' % (seed_repr, extent) label = Label(vertices=label_verts, pos=vert[hemi][label_verts], values=label_dist, hemi=hemi, comment=comment, name=str(name), subject=subject) labels.append(label) return labels @fill_doc def grow_labels(subject, seeds, extents, hemis, subjects_dir=None, n_jobs=1, overlap=True, names=None, surface='white', colors=None): """Generate circular labels in source space with region growing. This function generates a number of labels in source space by growing regions starting from the vertices defined in "seeds". For each seed, a label is generated containing all vertices within a maximum geodesic distance on the white matter surface from the seed. Parameters ---------- subject : str Name of the subject as in SUBJECTS_DIR. seeds : int | list Seed, or list of seeds. Each seed can be either a vertex number or a list of vertex numbers. extents : array | float Extents (radius in mm) of the labels. hemis : array | int Hemispheres to use for the labels (0: left, 1: right). %(subjects_dir)s %(n_jobs)s Likely only useful if tens or hundreds of labels are being expanded simultaneously. Does not apply with ``overlap=False``. overlap : bool Produce overlapping labels. If True (default), the resulting labels can be overlapping. If False, each label will be grown one step at a time, and occupied territory will not be invaded. names : None | list of str Assign names to the new labels (list needs to have the same length as seeds). surface : str The surface used to grow the labels, defaults to the white surface. colors : array, shape (n, 4) or (, 4) | None How to assign colors to each label. If None then unique colors will be chosen automatically (default), otherwise colors will be broadcast from the array. The first three values will be interpreted as RGB colors and the fourth column as the alpha value (commonly 1). Returns ------- labels : list of Label The labels' ``comment`` attribute contains information on the seed vertex and extent; the ``values`` attribute contains distance from the seed in millimeters. Notes ----- "extents" and "hemis" can either be arrays with the same length as seeds, which allows using a different extent and hemisphere for label, or integers, in which case the same extent and hemisphere is used for each label. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) n_jobs = check_n_jobs(n_jobs) # make sure the inputs are arrays if np.isscalar(seeds): seeds = [seeds] seeds = [np.atleast_1d(seed) for seed in seeds] extents = np.atleast_1d(extents) hemis = np.atleast_1d(hemis) n_seeds = len(seeds) if len(extents) != 1 and len(extents) != n_seeds: raise ValueError('The extents parameter has to be of length 1 or ' 'len(seeds)') if len(hemis) != 1 and len(hemis) != n_seeds: raise ValueError('The hemis parameter has to be of length 1 or ' 'len(seeds)') if colors is not None: if len(colors.shape) == 1: # if one color for all seeds n_colors = 1 n = colors.shape[0] else: n_colors, n = colors.shape if n_colors != n_seeds and n_colors != 1: msg = ('Number of colors (%d) and seeds (%d) are not compatible.' % (n_colors, n_seeds)) raise ValueError(msg) if n != 4: msg = 'Colors must have 4 values (RGB and alpha), not %d.' % n raise ValueError(msg) # make the arrays the same length as seeds if len(extents) == 1: extents = np.tile(extents, n_seeds) if len(hemis) == 1: hemis = np.tile(hemis, n_seeds) hemis = np.array(['lh' if h == 0 else 'rh' for h in hemis]) # names if names is None: names = ["Label_%i-%s" % items for items in enumerate(hemis)] else: if np.isscalar(names): names = [names] if len(names) != n_seeds: raise ValueError('The names parameter has to be None or have ' 'length len(seeds)') for i, hemi in enumerate(hemis): if not names[i].endswith(hemi): names[i] = '-'.join((names[i], hemi)) names = np.array(names) # load the surfaces and create the distance graphs tris, vert, dist = {}, {}, {} for hemi in set(hemis): surf_fname = op.join(subjects_dir, subject, 'surf', hemi + '.' + surface) vert[hemi], tris[hemi] = read_surface(surf_fname) dist[hemi] = mesh_dist(tris[hemi], vert[hemi]) if overlap: # create the patches parallel, my_grow_labels, _ = parallel_func(_grow_labels, n_jobs) seeds = np.array_split(np.array(seeds, dtype='O'), n_jobs) extents = np.array_split(extents, n_jobs) hemis = np.array_split(hemis, n_jobs) names = np.array_split(names, n_jobs) labels = sum(parallel(my_grow_labels(s, e, h, n, dist, vert, subject) for s, e, h, n in zip(seeds, extents, hemis, names)), []) else: # special procedure for non-overlapping labels labels = _grow_nonoverlapping_labels(subject, seeds, extents, hemis, vert, dist, names) if colors is None: # add a unique color to each label label_colors = _n_colors(len(labels)) else: # use specified colors label_colors = np.empty((len(labels), 4)) label_colors[:] = colors for label, color in zip(labels, label_colors): label.color = color return labels def _grow_nonoverlapping_labels(subject, seeds_, extents_, hemis, vertices_, graphs, names_): """Grow labels while ensuring that they don't overlap.""" labels = [] for hemi in set(hemis): hemi_index = (hemis == hemi) seeds = [seed for seed, h in zip(seeds_, hemis) if h == hemi] extents = extents_[hemi_index] names = names_[hemi_index] graph = graphs[hemi] # distance graph n_vertices = len(vertices_[hemi]) n_labels = len(seeds) # prepare parcellation parc = np.empty(n_vertices, dtype='int32') parc[:] = -1 # initialize active sources sources = {} # vert -> (label, dist_from_seed) edge = [] # queue of vertices to process for label, seed in enumerate(seeds): if np.any(parc[seed] >= 0): raise ValueError("Overlapping seeds") parc[seed] = label for s in np.atleast_1d(seed): sources[s] = (label, 0.) edge.append(s) # grow from sources while edge: vert_from = edge.pop(0) label, old_dist = sources[vert_from] # add neighbors within allowable distance row = graph[vert_from, :] for vert_to, dist in zip(row.indices, row.data): # Prevent adding a point that has already been used # (prevents infinite loop) if (vert_to == seeds[label]).any(): continue new_dist = old_dist + dist # abort if outside of extent if new_dist > extents[label]: continue vert_to_label = parc[vert_to] if vert_to_label >= 0: _, vert_to_dist = sources[vert_to] # abort if the vertex is occupied by a closer seed if new_dist > vert_to_dist: continue elif vert_to in edge: edge.remove(vert_to) # assign label value parc[vert_to] = label sources[vert_to] = (label, new_dist) edge.append(vert_to) # convert parc to labels for i in range(n_labels): vertices = np.nonzero(parc == i)[0] name = str(names[i]) label_ = Label(vertices, hemi=hemi, name=name, subject=subject) labels.append(label_) return labels @fill_doc def random_parcellation(subject, n_parcel, hemi, subjects_dir=None, surface='white', random_state=None): """Generate random cortex parcellation by growing labels. This function generates a number of labels which don't intersect and cover the whole surface. Regions are growing around randomly chosen seeds. Parameters ---------- subject : str Name of the subject as in SUBJECTS_DIR. n_parcel : int Total number of cortical parcels. hemi : str Hemisphere id (ie 'lh', 'rh', 'both'). In the case of 'both', both hemispheres are processed with (n_parcel // 2) parcels per hemisphere. %(subjects_dir)s surface : str The surface used to grow the labels, defaults to the white surface. %(random_state)s Returns ------- labels : list of Label Random cortex parcellation. """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) if hemi == 'both': hemi = ['lh', 'rh'] hemis = np.atleast_1d(hemi) # load the surfaces and create the distance graphs tris, vert, dist = {}, {}, {} for hemi in set(hemis): surf_fname = op.join(subjects_dir, subject, 'surf', hemi + '.' + surface) vert[hemi], tris[hemi] = read_surface(surf_fname) dist[hemi] = mesh_dist(tris[hemi], vert[hemi]) # create the patches labels = _cortex_parcellation(subject, n_parcel, hemis, vert, dist, random_state) # add a unique color to each label colors = _n_colors(len(labels)) for label, color in zip(labels, colors): label.color = color return labels def _cortex_parcellation(subject, n_parcel, hemis, vertices_, graphs, random_state=None): """Random cortex parcellation.""" labels = [] rng = check_random_state(random_state) for hemi in set(hemis): parcel_size = len(hemis) * len(vertices_[hemi]) // n_parcel graph = graphs[hemi] # distance graph n_vertices = len(vertices_[hemi]) # prepare parcellation parc = np.full(n_vertices, -1, dtype='int32') # initialize active sources s = rng.choice(range(n_vertices)) label_idx = 0 edge = [s] # queue of vertices to process parc[s] = label_idx label_size = 1 rest = len(parc) - 1 # grow from sources while rest: # if there are not free neighbors, start new parcel if not edge: rest_idx = np.where(parc < 0)[0] s = rng.choice(rest_idx) edge = [s] label_idx += 1 label_size = 1 parc[s] = label_idx rest -= 1 vert_from = edge.pop(0) # add neighbors within allowable distance # row = graph[vert_from, :] # row_indices, row_data = row.indices, row.data sl = slice(graph.indptr[vert_from], graph.indptr[vert_from + 1]) row_indices, row_data = graph.indices[sl], graph.data[sl] for vert_to, dist in zip(row_indices, row_data): vert_to_label = parc[vert_to] # abort if the vertex is already occupied if vert_to_label >= 0: continue # abort if outside of extent if label_size > parcel_size: label_idx += 1 label_size = 1 edge = [vert_to] parc[vert_to] = label_idx rest -= 1 break # assign label value parc[vert_to] = label_idx label_size += 1 edge.append(vert_to) rest -= 1 # merging small labels # label adjacency matrix n_labels = label_idx + 1 label_sizes = np.empty(n_labels, dtype=int) label_conn = np.zeros([n_labels, n_labels], dtype='bool') for i in range(n_labels): vertices = np.nonzero(parc == i)[0] label_sizes[i] = len(vertices) neighbor_vertices = graph[vertices, :].indices neighbor_labels = np.unique(np.array(parc[neighbor_vertices])) label_conn[i, neighbor_labels] = 1 np.fill_diagonal(label_conn, 0) # merging label_id = range(n_labels) while n_labels > n_parcel // len(hemis): # smallest label and its smallest neighbor i = np.argmin(label_sizes) neighbors = np.nonzero(label_conn[i, :])[0] j = neighbors[np.argmin(label_sizes[neighbors])] # merging two labels label_conn[j, :] += label_conn[i, :] label_conn[:, j] += label_conn[:, i] label_conn = np.delete(label_conn, i, 0) label_conn = np.delete(label_conn, i, 1) label_conn[j, j] = 0 label_sizes[j] += label_sizes[i] label_sizes = np.delete(label_sizes, i, 0) n_labels -= 1 vertices = np.nonzero(parc == label_id[i])[0] parc[vertices] = label_id[j] label_id = np.delete(label_id, i, 0) # convert parc to labels for i in range(n_labels): vertices = np.nonzero(parc == label_id[i])[0] name = 'label_' + str(i) label_ = Label(vertices, hemi=hemi, name=name, subject=subject) labels.append(label_) return labels def _read_annot_cands(dir_name, raise_error=True): """List the candidate parcellations.""" if not op.isdir(dir_name): if not raise_error: return list() raise IOError('Directory for annotation does not exist: %s', dir_name) cands = os.listdir(dir_name) cands = sorted(set(c.replace('lh.', '').replace('rh.', '').replace( '.annot', '') for c in cands if '.annot' in c), key=lambda x: x.lower()) # exclude .ctab files cands = [c for c in cands if '.ctab' not in c] return cands def _read_annot(fname): """Read a Freesurfer annotation from a .annot file. Note : Copied from PySurfer Parameters ---------- fname : str Path to annotation file Returns ------- annot : numpy array, shape=(n_verts) Annotation id at each vertex ctab : numpy array, shape=(n_entries, 5) RGBA + label id colortable array names : list of str List of region names as stored in the annot file """ if not op.isfile(fname): dir_name = op.split(fname)[0] cands = _read_annot_cands(dir_name) if len(cands) == 0: raise IOError('No such file %s, no candidate parcellations ' 'found in directory' % fname) else: raise IOError('No such file %s, candidate parcellations in ' 'that directory:\n%s' % (fname, '\n'.join(cands))) with open(fname, "rb") as fid: n_verts = np.fromfile(fid, '>i4', 1)[0] data = np.fromfile(fid, '>i4', n_verts * 2).reshape(n_verts, 2) annot = data[data[:, 0], 1] ctab_exists = np.fromfile(fid, '>i4', 1)[0] if not ctab_exists: raise Exception('Color table not found in annotation file') n_entries = np.fromfile(fid, '>i4', 1)[0] if n_entries > 0: length = np.fromfile(fid, '>i4', 1)[0] np.fromfile(fid, '>c', length) # discard orig_tab names = list() ctab = np.zeros((n_entries, 5), np.int64) for i in range(n_entries): name_length = np.fromfile(fid, '>i4', 1)[0] name = np.fromfile(fid, "|S%d" % name_length, 1)[0] names.append(name) ctab[i, :4] = np.fromfile(fid, '>i4', 4) ctab[i, 4] = (ctab[i, 0] + ctab[i, 1] * (2 ** 8) + ctab[i, 2] * (2 ** 16) + ctab[i, 3] * (2 ** 24)) else: ctab_version = -n_entries if ctab_version != 2: raise Exception('Color table version not supported') n_entries = np.fromfile(fid, '>i4', 1)[0] ctab = np.zeros((n_entries, 5), np.int64) length = np.fromfile(fid, '>i4', 1)[0] np.fromfile(fid, "|S%d" % length, 1) # Orig table path entries_to_read = np.fromfile(fid, '>i4', 1)[0] names = list() for i in range(entries_to_read): np.fromfile(fid, '>i4', 1) # Structure name_length = np.fromfile(fid, '>i4', 1)[0] name = np.fromfile(fid, "|S%d" % name_length, 1)[0] names.append(name) ctab[i, :4] = np.fromfile(fid, '>i4', 4) ctab[i, 4] = (ctab[i, 0] + ctab[i, 1] * (2 ** 8) + ctab[i, 2] * (2 ** 16)) # convert to more common alpha value ctab[:, 3] = 255 - ctab[:, 3] return annot, ctab, names def _get_annot_fname(annot_fname, subject, hemi, parc, subjects_dir): """Get the .annot filenames and hemispheres.""" if annot_fname is not None: # we use use the .annot file specified by the user hemis = [op.basename(annot_fname)[:2]] if hemis[0] not in ['lh', 'rh']: raise ValueError('Could not determine hemisphere from filename, ' 'filename has to start with "lh" or "rh".') annot_fname = [annot_fname] else: # construct .annot file names for requested subject, parc, hemi _check_option('hemi', hemi, ['lh', 'rh', 'both']) if hemi == 'both': hemis = ['lh', 'rh'] else: hemis = [hemi] subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) dst = op.join(subjects_dir, subject, 'label', '%%s.%s.annot' % parc) annot_fname = [dst % hemi_ for hemi_ in hemis] return annot_fname, hemis def _load_vert_pos(subject, subjects_dir, surf_name, hemi, n_expected, extra=''): fname_surf = op.join(subjects_dir, subject, 'surf', '%s.%s' % (hemi, surf_name)) vert_pos, _ = read_surface(fname_surf) vert_pos /= 1e3 # the positions in labels are in meters if len(vert_pos) != n_expected: raise RuntimeError('Number of surface vertices (%s) for subject %s' ' does not match the expected number of vertices' '(%s)%s' % (len(vert_pos), subject, n_expected, extra)) return vert_pos @verbose def read_labels_from_annot(subject, parc='aparc', hemi='both', surf_name='white', annot_fname=None, regexp=None, subjects_dir=None, sort=True, verbose=None): """Read labels from a FreeSurfer annotation file. Note: Only cortical labels will be returned. Parameters ---------- subject : str The subject for which to read the parcellation. parc : str The parcellation to use, e.g., 'aparc' or 'aparc.a2009s'. hemi : str The hemisphere from which to read the parcellation, can be 'lh', 'rh', or 'both'. surf_name : str Surface used to obtain vertex locations, e.g., 'white', 'pial'. annot_fname : str or None Filename of the .annot file. If not None, only this file is read and 'parc' and 'hemi' are ignored. regexp : str Regular expression or substring to select particular labels from the parcellation. E.g. 'superior' will return all labels in which this substring is contained. %(subjects_dir)s sort : bool If true, labels will be sorted by name before being returned. .. versionadded:: 0.21.0 %(verbose)s Returns ------- labels : list of Label The labels, sorted by label name (ascending). See Also -------- write_labels_to_annot morph_labels """ logger.info('Reading labels from parcellation...') subjects_dir = get_subjects_dir(subjects_dir) # get the .annot filenames and hemispheres annot_fname, hemis = _get_annot_fname(annot_fname, subject, hemi, parc, subjects_dir) if regexp is not None: # allow for convenient substring match r_ = (re.compile('.*%s.*' % regexp if regexp.replace('_', '').isalnum() else regexp)) # now we are ready to create the labels n_read = 0 labels = list() orig_names = set() for fname, hemi in zip(annot_fname, hemis): # read annotation annot, ctab, label_names = _read_annot(fname) label_rgbas = ctab[:, :4] / 255. label_ids = ctab[:, -1] # load the vertex positions from surface vert_pos = _load_vert_pos( subject, subjects_dir, surf_name, hemi, len(annot), extra='for annotation file %s' % fname) for label_id, label_name, label_rgba in\ zip(label_ids, label_names, label_rgbas): vertices = np.where(annot == label_id)[0] if len(vertices) == 0: # label is not part of cortical surface continue label_name = label_name.decode() orig_names.add(label_name) name = f'{label_name}-{hemi}' if (regexp is not None) and not r_.match(name): continue pos = vert_pos[vertices, :] label = Label(vertices, pos, hemi=hemi, name=name, subject=subject, color=tuple(label_rgba)) labels.append(label) n_read = len(labels) - n_read logger.info(' read %d labels from %s' % (n_read, fname)) # sort the labels by label name if sort: labels = sorted(labels, key=lambda l: l.name) if len(labels) == 0: msg = 'No labels found.' if regexp is not None: orig_names = '\n'.join(sorted(orig_names)) msg += (f' Maybe the regular expression {repr(regexp)} did not ' f'match any of:\n{orig_names}') raise RuntimeError(msg) return labels def _check_labels_subject(labels, subject, name): _validate_type(labels, (list, tuple), 'labels') for label in labels: _validate_type(label, Label, 'each entry in labels') if subject is None: subject = label.subject if subject is not None: # label.subject can be None, depending on init if subject != label.subject: raise ValueError('Got multiple values of %s: %s and %s' % (name, subject, label.subject)) if subject is None: raise ValueError('if label.subject is None for all labels, ' '%s must be provided' % name) return subject @verbose def morph_labels(labels, subject_to, subject_from=None, subjects_dir=None, surf_name='white', verbose=None): """Morph a set of labels. This is useful when morphing a set of non-overlapping labels (such as those obtained with :func:`read_labels_from_annot`) from one subject to another. Parameters ---------- labels : list The labels to morph. subject_to : str The subject to morph labels to. subject_from : str | None The subject to morph labels from. Can be None if the labels have the ``.subject`` property defined. %(subjects_dir)s surf_name : str Surface used to obtain vertex locations, e.g., 'white', 'pial'. %(verbose)s Returns ------- labels : list The morphed labels. See Also -------- read_labels_from_annot mne.Label.morph Notes ----- This does not use the same algorithm as Freesurfer, so the results morphing (e.g., from ``'fsaverage'`` to your subject) might not match what Freesurfer produces during ``recon-all``. .. versionadded:: 0.18 """ subjects_dir = get_subjects_dir(subjects_dir, raise_error=True) subject_from = _check_labels_subject(labels, subject_from, 'subject_from') mmaps = read_morph_map(subject_from, subject_to, subjects_dir) vert_poss = [_load_vert_pos(subject_to, subjects_dir, surf_name, hemi, mmap.shape[0]) for hemi, mmap in zip(('lh', 'rh'), mmaps)] idxs = [mmap.argmax(axis=1) for mmap in mmaps] out_labels = list() values = filename = None for label in labels: li = dict(lh=0, rh=1)[label.hemi] vertices = np.where(np.in1d(idxs[li], label.vertices))[0] pos = vert_poss[li][vertices] out_labels.append( Label(vertices, pos, values, label.hemi, label.comment, label.name, filename, subject_to, label.color, label.verbose)) return out_labels @verbose def labels_to_stc(labels, values, tmin=0, tstep=1, subject=None, src=None, verbose=None): """Convert a set of labels and values to a STC. This function is meant to work like the opposite of `extract_label_time_course`. Parameters ---------- %(eltc_labels)s values : ndarray, shape (n_labels, ...) The values in each label. Can be 1D or 2D. tmin : float The tmin to use for the STC. tstep : float The tstep to use for the STC. subject : str | None The subject for which to create the STC. %(eltc_src)s Can be omitted if using a surface source space, in which case the label vertices will determine the output STC vertices. Required if using a volumetric source space. .. versionadded:: 0.22 %(verbose)s Returns ------- stc : instance of SourceEstimate | instance of VolSourceEstimate The values-in-labels converted to a STC. See Also -------- extract_label_time_course Notes ----- Vertices that appear in more than one label will be averaged. .. versionadded:: 0.18 """ values = np.array(values, float) if values.ndim == 1: values = values[:, np.newaxis] if values.ndim != 2: raise ValueError('values must have 1 or 2 dimensions, got %s' % (values.ndim,)) _validate_type(src, (SourceSpaces, None)) if src is None: data, vertices, subject = _labels_to_stc_surf( labels, values, tmin, tstep, subject) klass = SourceEstimate else: kind = src.kind subject = _check_subject( src._subject, subject, first_kind='source space subject', raise_error=False) _check_option('source space kind', kind, ('surface', 'volume')) if kind == 'volume': klass = VolSourceEstimate else: klass = SourceEstimate # Easiest way is to get a dot-able operator and use it vertices = [s['vertno'].copy() for s in src] stc = klass( np.eye(sum(len(v) for v in vertices)), vertices, 0, 1, subject) label_op = extract_label_time_course( stc, labels, src=src, mode='mean', allow_empty=True) _check_values_labels(values, label_op.shape[0]) rev_op = np.zeros(label_op.shape[::-1]) rev_op[np.arange(label_op.shape[1]), np.argmax(label_op, axis=0)] = 1. data = rev_op @ values return klass(data, vertices, tmin, tstep, subject, verbose) def _check_values_labels(values, n_labels): if n_labels != len(values): raise ValueError( f'values.shape[0] ({values.shape[0]}) must match the number of ' f'labels ({n_labels})') def _labels_to_stc_surf(labels, values, tmin, tstep, subject): from scipy import sparse subject = _check_labels_subject(labels, subject, 'subject') _check_values_labels(values, len(labels)) vertices = dict(lh=[], rh=[]) data = dict(lh=[], rh=[]) for li, label in enumerate(labels): data[label.hemi].append( np.repeat(values[li][np.newaxis], len(label.vertices), axis=0)) vertices[label.hemi].append(label.vertices) hemis = ('lh', 'rh') for hemi in hemis: vertices[hemi] = np.concatenate(vertices[hemi], axis=0) data[hemi] = np.concatenate(data[hemi], axis=0).astype(float) cols = np.arange(len(vertices[hemi])) vertices[hemi], rows = np.unique(vertices[hemi], return_inverse=True) mat = sparse.coo_matrix((np.ones(len(rows)), (rows, cols))).tocsr() mat = mat * sparse.diags(1. / np.asarray(mat.sum(axis=-1))[:, 0]) data[hemi] = mat.dot(data[hemi]) vertices = [vertices[hemi] for hemi in hemis] data = np.concatenate([data[hemi] for hemi in hemis], axis=0) return data, vertices, subject _DEFAULT_TABLE_NAME = 'MNE-Python Colortable' def _write_annot(fname, annot, ctab, names, table_name=_DEFAULT_TABLE_NAME): """Write a Freesurfer annotation to a .annot file.""" assert len(names) == len(ctab) with open(fname, 'wb') as fid: n_verts = len(annot) np.array(n_verts, dtype='>i4').tofile(fid) data = np.zeros((n_verts, 2), dtype='>i4') data[:, 0] = np.arange(n_verts) data[:, 1] = annot data.ravel().tofile(fid) # indicate that color table exists np.array(1, dtype='>i4').tofile(fid) # color table version 2 np.array(-2, dtype='>i4').tofile(fid) # write color table n_entries = len(ctab) np.array(n_entries, dtype='>i4').tofile(fid) # write our color table name _write_annot_str(fid, table_name) # number of entries to write np.array(n_entries, dtype='>i4').tofile(fid) # write entries for ii, (name, color) in enumerate(zip(names, ctab)): np.array(ii, dtype='>i4').tofile(fid) _write_annot_str(fid, name) np.array(color[:4], dtype='>i4').tofile(fid) def _write_annot_str(fid, s): s = s.encode('ascii') + b'\x00' np.array(len(s), '>i4').tofile(fid) fid.write(s) @verbose def write_labels_to_annot(labels, subject=None, parc=None, overwrite=False, subjects_dir=None, annot_fname=None, colormap='hsv', hemi='both', sort=True, table_name=_DEFAULT_TABLE_NAME, verbose=None): r"""Create a FreeSurfer annotation from a list of labels. Parameters ---------- labels : list with instances of mne.Label The labels to create a parcellation from. subject : str | None The subject for which to write the parcellation. parc : str | None The parcellation name to use. overwrite : bool Overwrite files if they already exist. %(subjects_dir)s annot_fname : str | None Filename of the .annot file. If not None, only this file is written and 'parc' and 'subject' are ignored. colormap : str Colormap to use to generate label colors for labels that do not have a color specified. hemi : 'both' | 'lh' | 'rh' The hemisphere(s) for which to write \*.annot files (only applies if annot_fname is not specified; default is 'both'). sort : bool If True (default), labels will be sorted by name before writing. .. versionadded:: 0.21.0 table_name : str The table name to use for the colortable. .. versionadded:: 0.21.0 %(verbose)s See Also -------- read_labels_from_annot Notes ----- Vertices that are not covered by any of the labels are assigned to a label named "unknown". """ logger.info('Writing labels to parcellation...') subjects_dir = get_subjects_dir(subjects_dir) # get the .annot filenames and hemispheres annot_fname, hemis = _get_annot_fname(annot_fname, subject, hemi, parc, subjects_dir) if not overwrite: for fname in annot_fname: if op.exists(fname): raise ValueError('File %s exists. Use "overwrite=True" to ' 'overwrite it' % fname) # prepare container for data to save: to_save = [] # keep track of issues found in the labels duplicate_colors = [] invalid_colors = [] overlap = [] no_color = (-1, -1, -1, -1) no_color_rgb = (-1, -1, -1) for hemi, fname in zip(hemis, annot_fname): hemi_labels = [label for label in labels if label.hemi == hemi] n_hemi_labels = len(hemi_labels) if n_hemi_labels == 0: ctab = np.empty((0, 4), dtype=np.int32) ctab_rgb = ctab[:, :3] else: if sort: hemi_labels.sort(key=lambda label: label.name) # convert colors to 0-255 RGBA tuples hemi_colors = [no_color if label.color is None else tuple(int(round(255 * i)) for i in label.color) for label in hemi_labels] ctab = np.array(hemi_colors, dtype=np.int32) ctab_rgb = ctab[:, :3] # make color dict (for annot ID, only R, G and B count) labels_by_color = defaultdict(list) for label, color in zip(hemi_labels, ctab_rgb): labels_by_color[tuple(color)].append(label.name) # check label colors for color, names in labels_by_color.items(): if color == no_color_rgb: continue if color == (0, 0, 0): # we cannot have an all-zero color, otherw. e.g. tksurfer # refuses to read the parcellation warn('At least one label contains a color with, "r=0, ' 'g=0, b=0" value. Some FreeSurfer tools may fail ' 'to read the parcellation') if any(i > 255 for i in color): msg = ("%s: %s (%s)" % (color, ', '.join(names), hemi)) invalid_colors.append(msg) if len(names) > 1: msg = "%s: %s (%s)" % (color, ', '.join(names), hemi) duplicate_colors.append(msg) # replace None values (labels with unspecified color) if labels_by_color[no_color_rgb]: default_colors = _n_colors(n_hemi_labels, bytes_=True, cmap=colormap) # keep track of colors known to be in hemi_colors : safe_color_i = 0 for i in range(n_hemi_labels): if ctab[i, 0] == -1: color = default_colors[i] # make sure to add no duplicate color while np.any(np.all(color[:3] == ctab_rgb, 1)): color = default_colors[safe_color_i] safe_color_i += 1 # assign the color ctab[i] = color # find number of vertices in surface if subject is not None and subjects_dir is not None: fpath = op.join(subjects_dir, subject, 'surf', '%s.white' % hemi) points, _ = read_surface(fpath) n_vertices = len(points) else: if len(hemi_labels) > 0: max_vert = max(np.max(label.vertices) for label in hemi_labels) n_vertices = max_vert + 1 else: n_vertices = 1 warn('Number of vertices in the surface could not be ' 'verified because the surface file could not be found; ' 'specify subject and subjects_dir parameters.') # Create annot and color table array to write annot = np.empty(n_vertices, dtype=np.int64) annot[:] = -1 # create the annotation ids from the colors annot_id_coding = np.array((1, 2 ** 8, 2 ** 16)) annot_ids = list(np.sum(ctab_rgb * annot_id_coding, axis=1)) for label, annot_id in zip(hemi_labels, annot_ids): # make sure the label is not overwriting another label if np.any(annot[label.vertices] != -1): other_ids = set(annot[label.vertices]) other_ids.discard(-1) other_indices = (annot_ids.index(i) for i in other_ids) other_names = (hemi_labels[i].name for i in other_indices) other_repr = ', '.join(other_names) msg = "%s: %s overlaps %s" % (hemi, label.name, other_repr) overlap.append(msg) annot[label.vertices] = annot_id hemi_names = [label.name for label in hemi_labels] if None in hemi_names: msg = ("Found %i labels with no name. Writing annotation file" "requires all labels named" % (hemi_names.count(None))) # raise the error immediately rather than crash with an # uninformative error later (e.g. cannot join NoneType) raise ValueError(msg) # Assign unlabeled vertices to an "unknown" label unlabeled = (annot == -1) if np.any(unlabeled): msg = ("Assigning %i unlabeled vertices to " "'unknown-%s'" % (unlabeled.sum(), hemi)) logger.info(msg) # find an unused color (try shades of gray first) for i in range(1, 257): if not np.any(np.all((i, i, i) == ctab_rgb, 1)): break if i < 256: color = (i, i, i, 0) else: err = ("Need one free shade of gray for 'unknown' label. " "Please modify your label colors, or assign the " "unlabeled vertices to another label.") raise ValueError(err) # find the id annot_id = np.sum(annot_id_coding * color[:3]) # update data to write annot[unlabeled] = annot_id ctab = np.vstack((ctab, color)) hemi_names.append("unknown") # convert to FreeSurfer alpha values ctab[:, 3] = 255 - ctab[:, 3] # remove hemi ending in names hemi_names = [name[:-3] if name.endswith(hemi) else name for name in hemi_names] to_save.append((fname, annot, ctab, hemi_names)) issues = [] if duplicate_colors: msg = ("Some labels have the same color values (all labels in one " "hemisphere must have a unique color):") duplicate_colors.insert(0, msg) issues.append('\n'.join(duplicate_colors)) if invalid_colors: msg = ("Some labels have invalid color values (all colors should be " "RGBA tuples with values between 0 and 1)") invalid_colors.insert(0, msg) issues.append('\n'.join(invalid_colors)) if overlap: msg = ("Some labels occupy vertices that are also occupied by one or " "more other labels. Each vertex can only be occupied by a " "single label in *.annot files.") overlap.insert(0, msg) issues.append('\n'.join(overlap)) if issues: raise ValueError('\n\n'.join(issues)) # write it for fname, annot, ctab, hemi_names in to_save: logger.info(' writing %d labels to %s' % (len(hemi_names), fname)) _write_annot(fname, annot, ctab, hemi_names, table_name) @fill_doc def select_sources(subject, label, location='center', extent=0., grow_outside=True, subjects_dir=None, name=None, random_state=None, surf='white'): """Select sources from a label. Parameters ---------- %(subject)s label : instance of Label | str Define where the seed will be chosen. If str, can be 'lh' or 'rh', which correspond to left or right hemisphere, respectively. location : 'random' | 'center' | int Location to grow label from. If the location is an int, it represents the vertex number in the corresponding label. If it is a str, it can be either 'random' or 'center'. extent : float Extents (radius in mm) of the labels, i.e. maximum geodesic distance on the white matter surface from the seed. If 0, the resulting label will contain only one vertex. grow_outside : bool Let the region grow outside the original label where location was defined. %(subjects_dir)s name : None | str Assign name to the new label. %(random_state)s surf : str The surface used to simulated the label, defaults to the white surface. Returns ------- label : instance of Label The label that contains the selected sources. Notes ----- This function selects a region of interest on the cortical surface based on a label (or a hemisphere). The sources are selected by growing a region around a seed which is selected randomly, is the center of the label, or is a specific vertex. The selected vertices can extend beyond the initial provided label. This can be prevented by setting grow_outside to False. The selected sources are returned in the form of a new Label object. The values of the label contain the distance from the seed in millimeters. .. versionadded:: 0.18 """ # If label is a string, convert it to a label that contains the whole # hemisphere. if isinstance(label, str): _check_option('label', label, ['lh', 'rh']) surf_filename = op.join(subjects_dir, subject, 'surf', label + '.white') vertices, _ = read_surface(surf_filename) indices = np.arange(len(vertices), dtype=int) label = Label(indices, vertices, hemi=label) # Choose the seed according to the selected strategy. if isinstance(location, str): _check_option('location', location, ['center', 'random']) if location == 'center': seed = label.center_of_mass( subject, restrict_vertices=True, subjects_dir=subjects_dir, surf=surf) else: rng = check_random_state(random_state) seed = rng.choice(label.vertices) else: seed = label.vertices[location] hemi = 0 if label.hemi == 'lh' else 1 new_label = grow_labels(subject, seed, extent, hemi, subjects_dir)[0] # We override the name because grow_label automatically adds a -rh or -lh # to the given parameter. new_label.name = name # Restrict the new label to the vertices of the input label if needed. if not grow_outside: to_keep = np.array([v in label.vertices for v in new_label.vertices]) new_label = Label(new_label.vertices[to_keep], new_label.pos[to_keep], hemi=new_label.hemi, name=name, subject=subject) return new_label def find_pos_in_annot(pos, subject='fsaverage', annot='aparc+aseg', subjects_dir=None): """ Find name in atlas for given MRI coordinates. Parameters ---------- pos : ndarray, shape (3,) Vector of x,y,z coordinates in MRI space. subject : str MRI subject name. annot : str MRI volumetric atlas file name. Do not include the ``.mgz`` suffix. subjects_dir : path-like Path to MRI subjects directory. Returns ------- label : str Anatomical region name from atlas. Notes ----- .. versionadded:: 0.24 """ pos = np.asarray(pos, float) if pos.shape != (3,): raise ValueError( 'pos must be an array of shape (3,), ' f'got {pos.shape}') nibabel = _import_nibabel('read MRI parcellations') if subjects_dir is None: subjects_dir = get_subjects_dir(None) atlas_fname = os.path.join(subjects_dir, subject, 'mri', annot + '.mgz') parcellation_img = nibabel.load(atlas_fname) # Load freesurface atlas LUT lut_inv_dict = read_freesurfer_lut()[0] label_lut = {v: k for k, v in lut_inv_dict.items()} # Find voxel for dipole position mri_vox_t = np.linalg.inv(parcellation_img.header.get_vox2ras_tkr()) vox_dip_pos_f = apply_trans(mri_vox_t, pos) vox_dip_pos = np.rint(vox_dip_pos_f).astype(int) # Get voxel value and label from LUT vol_values = parcellation_img.get_fdata()[tuple(vox_dip_pos.T)] label = label_lut.get(vol_values, 'Unknown') return label
from itertools import product import datetime import os.path as op import numpy as np from numpy.testing import (assert_array_equal, assert_equal, assert_allclose) import pytest import matplotlib.pyplot as plt import mne from mne import (Epochs, read_events, pick_types, create_info, EpochsArray, Info, Transform) from mne.io import read_raw_fif from mne.utils import (requires_h5py, requires_pandas, grand_average, catch_logging) from mne.time_frequency.tfr import (morlet, tfr_morlet, _make_dpss, tfr_multitaper, AverageTFR, read_tfrs, write_tfrs, combine_tfr, cwt, _compute_tfr, EpochsTFR) from mne.time_frequency import tfr_array_multitaper, tfr_array_morlet from mne.viz.utils import _fake_click from mne.tests.test_epochs import assert_metadata_equal data_path = op.join(op.dirname(__file__), '..', '..', 'io', 'tests', 'data') raw_fname = op.join(data_path, 'test_raw.fif') event_fname = op.join(data_path, 'test-eve.fif') raw_ctf_fname = op.join(data_path, 'test_ctf_raw.fif') def test_tfr_ctf(): """Test that TFRs can be calculated on CTF data.""" raw = read_raw_fif(raw_ctf_fname).crop(0, 1) raw.apply_gradient_compensation(3) events = mne.make_fixed_length_events(raw, duration=0.5) epochs = mne.Epochs(raw, events) for method in (tfr_multitaper, tfr_morlet): method(epochs, [10], 1) # smoke test def test_morlet(): """Test morlet with and without zero mean.""" Wz = morlet(1000, [10], 2., zero_mean=True) W = morlet(1000, [10], 2., zero_mean=False) assert (np.abs(np.mean(np.real(Wz[0]))) < 1e-5) assert (np.abs(np.mean(np.real(W[0]))) > 1e-3) def test_time_frequency(): """Test time-frequency transform (PSD and ITC).""" # Set parameters event_id = 1 tmin = -0.2 tmax = 0.498 # Allows exhaustive decimation testing # Setup for reading the raw data raw = read_raw_fif(raw_fname) events = read_events(event_fname) include = [] exclude = raw.info['bads'] + ['MEG 2443', 'EEG 053'] # bads + 2 more # picks MEG gradiometers picks = pick_types(raw.info, meg='grad', eeg=False, stim=False, include=include, exclude=exclude) picks = picks[:2] epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks) data = epochs.get_data() times = epochs.times nave = len(data) epochs_nopicks = Epochs(raw, events, event_id, tmin, tmax) freqs = np.arange(6, 20, 5) # define frequencies of interest n_cycles = freqs / 4. # Test first with a single epoch power, itc = tfr_morlet(epochs[0], freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=True) # Now compute evoked evoked = epochs.average() pytest.raises(ValueError, tfr_morlet, evoked, freqs, 1., return_itc=True) power, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=True) power_, itc_ = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=True, decim=slice(0, 2)) # Test picks argument and average parameter pytest.raises(ValueError, tfr_morlet, epochs, freqs=freqs, n_cycles=n_cycles, return_itc=True, average=False) power_picks, itc_picks = \ tfr_morlet(epochs_nopicks, freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=True, picks=picks, average=True) epochs_power_picks = \ tfr_morlet(epochs_nopicks, freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=False, picks=picks, average=False) power_picks_avg = epochs_power_picks.average() # the actual data arrays here are equivalent, too... assert_allclose(power.data, power_picks.data) assert_allclose(power.data, power_picks_avg.data) assert_allclose(itc.data, itc_picks.data) # test on evoked power_evoked = tfr_morlet(evoked, freqs, n_cycles, use_fft=True, return_itc=False) # one is squared magnitude of the average (evoked) and # the other is average of the squared magnitudes (epochs PSD) # so values shouldn't match, but shapes should assert_array_equal(power.data.shape, power_evoked.data.shape) pytest.raises(AssertionError, assert_allclose, power.data, power_evoked.data) # complex output pytest.raises(ValueError, tfr_morlet, epochs, freqs, n_cycles, return_itc=False, average=True, output="complex") pytest.raises(ValueError, tfr_morlet, epochs, freqs, n_cycles, output="complex", average=False, return_itc=True) epochs_power_complex = tfr_morlet(epochs, freqs, n_cycles, output="complex", average=False, return_itc=False) epochs_amplitude_2 = abs(epochs_power_complex) epochs_amplitude_3 = epochs_amplitude_2.copy() epochs_amplitude_3.data[:] = np.inf # test that it's actually copied # test that the power computed via `complex` is equivalent to power # computed within the method. assert_allclose(epochs_amplitude_2.data**2, epochs_power_picks.data) print(itc) # test repr print(itc.ch_names) # test property itc += power # test add itc -= power # test sub ret = itc * 23 # test mult itc = ret / 23 # test dic power = power.apply_baseline(baseline=(-0.1, 0), mode='logratio') assert 'meg' in power assert 'grad' in power assert 'mag' not in power assert 'eeg' not in power assert power.nave == nave assert itc.nave == nave assert (power.data.shape == (len(picks), len(freqs), len(times))) assert (power.data.shape == itc.data.shape) assert (power_.data.shape == (len(picks), len(freqs), 2)) assert (power_.data.shape == itc_.data.shape) assert (np.sum(itc.data >= 1) == 0) assert (np.sum(itc.data <= 0) == 0) # grand average itc2 = itc.copy() itc2.info['bads'] = [itc2.ch_names[0]] # test channel drop gave = grand_average([itc2, itc]) assert gave.data.shape == (itc2.data.shape[0] - 1, itc2.data.shape[1], itc2.data.shape[2]) assert itc2.ch_names[1:] == gave.ch_names assert gave.nave == 2 itc2.drop_channels(itc2.info["bads"]) assert_allclose(gave.data, itc2.data) itc2.data = np.ones(itc2.data.shape) itc.data = np.zeros(itc.data.shape) itc2.nave = 2 itc.nave = 1 itc.drop_channels([itc.ch_names[0]]) combined_itc = combine_tfr([itc2, itc]) assert_allclose(combined_itc.data, np.ones(combined_itc.data.shape) * 2 / 3) # more tests power, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=2, use_fft=False, return_itc=True) assert (power.data.shape == (len(picks), len(freqs), len(times))) assert (power.data.shape == itc.data.shape) assert (np.sum(itc.data >= 1) == 0) assert (np.sum(itc.data <= 0) == 0) tfr = tfr_morlet(epochs[0], freqs, use_fft=True, n_cycles=2, average=False, return_itc=False) tfr_data = tfr.data[0] assert (tfr_data.shape == (len(picks), len(freqs), len(times))) tfr2 = tfr_morlet(epochs[0], freqs, use_fft=True, n_cycles=2, decim=slice(0, 2), average=False, return_itc=False).data[0] assert (tfr2.shape == (len(picks), len(freqs), 2)) single_power = tfr_morlet(epochs, freqs, 2, average=False, return_itc=False).data single_power2 = tfr_morlet(epochs, freqs, 2, decim=slice(0, 2), average=False, return_itc=False).data single_power3 = tfr_morlet(epochs, freqs, 2, decim=slice(1, 3), average=False, return_itc=False).data single_power4 = tfr_morlet(epochs, freqs, 2, decim=slice(2, 4), average=False, return_itc=False).data assert_allclose(np.mean(single_power, axis=0), power.data) assert_allclose(np.mean(single_power2, axis=0), power.data[:, :, :2]) assert_allclose(np.mean(single_power3, axis=0), power.data[:, :, 1:3]) assert_allclose(np.mean(single_power4, axis=0), power.data[:, :, 2:4]) power_pick = power.pick_channels(power.ch_names[:10:2]) assert_equal(len(power_pick.ch_names), len(power.ch_names[:10:2])) assert_equal(power_pick.data.shape[0], len(power.ch_names[:10:2])) power_drop = power.drop_channels(power.ch_names[1:10:2]) assert_equal(power_drop.ch_names, power_pick.ch_names) assert_equal(power_pick.data.shape[0], len(power_drop.ch_names)) power_pick, power_drop = mne.equalize_channels([power_pick, power_drop]) assert_equal(power_pick.ch_names, power_drop.ch_names) assert_equal(power_pick.data.shape, power_drop.data.shape) # Test decimation: # 2: multiple of len(times) even # 3: multiple odd # 8: not multiple, even # 9: not multiple, odd for decim in [2, 3, 8, 9]: for use_fft in [True, False]: power, itc = tfr_morlet(epochs, freqs=freqs, n_cycles=2, use_fft=use_fft, return_itc=True, decim=decim) assert_equal(power.data.shape[2], np.ceil(float(len(times)) / decim)) freqs = list(range(50, 55)) decim = 2 _, n_chan, n_time = data.shape tfr = tfr_morlet(epochs[0], freqs, 2., decim=decim, average=False, return_itc=False).data[0] assert_equal(tfr.shape, (n_chan, len(freqs), n_time // decim)) # Test cwt modes Ws = morlet(512, [10, 20], n_cycles=2) pytest.raises(ValueError, cwt, data[0, :, :], Ws, mode='foo') for use_fft in [True, False]: for mode in ['same', 'valid', 'full']: cwt(data[0], Ws, use_fft=use_fft, mode=mode) # Test invalid frequency arguments with pytest.raises(ValueError, match=" 'freqs' must be greater than 0"): tfr_morlet(epochs, freqs=np.arange(0, 3), n_cycles=7) with pytest.raises(ValueError, match=" 'freqs' must be greater than 0"): tfr_morlet(epochs, freqs=np.arange(-4, -1), n_cycles=7) # Test decim parameter checks pytest.raises(TypeError, tfr_morlet, epochs, freqs=freqs, n_cycles=n_cycles, use_fft=True, return_itc=True, decim='decim') # When convolving in time, wavelets must not be longer than the data pytest.raises(ValueError, cwt, data[0, :, :Ws[0].size - 1], Ws, use_fft=False) with pytest.warns(UserWarning, match='one of the wavelets.*is longer'): cwt(data[0, :, :Ws[0].size - 1], Ws, use_fft=True) # Check for off-by-one errors when using wavelets with an even number of # samples psd = cwt(data[0], [Ws[0][:-1]], use_fft=False, mode='full') assert_equal(psd.shape, (2, 1, 420)) def test_dpsswavelet(): """Test DPSS tapers.""" freqs = np.arange(5, 25, 3) Ws = _make_dpss(1000, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, zero_mean=True) assert (len(Ws) == 3) # 3 tapers expected # Check that zero mean is true assert (np.abs(np.mean(np.real(Ws[0][0]))) < 1e-5) assert (len(Ws[0]) == len(freqs)) # As many wavelets as asked for @pytest.mark.slowtest def test_tfr_multitaper(): """Test tfr_multitaper.""" sfreq = 200.0 ch_names = ['SIM0001', 'SIM0002'] ch_types = ['grad', 'grad'] info = create_info(ch_names=ch_names, sfreq=sfreq, ch_types=ch_types) n_times = int(sfreq) # Second long epochs n_epochs = 3 seed = 42 rng = np.random.RandomState(seed) noise = 0.1 * rng.randn(n_epochs, len(ch_names), n_times) t = np.arange(n_times, dtype=np.float64) / sfreq signal = np.sin(np.pi * 2. * 50. * t) # 50 Hz sinusoid signal signal[np.logical_or(t < 0.45, t > 0.55)] = 0. # Hard windowing on_time = np.logical_and(t >= 0.45, t <= 0.55) signal[on_time] *= np.hanning(on_time.sum()) # Ramping dat = noise + signal reject = dict(grad=4000.) events = np.empty((n_epochs, 3), int) first_event_sample = 100 event_id = dict(sin50hz=1) for k in range(n_epochs): events[k, :] = first_event_sample + k * n_times, 0, event_id['sin50hz'] epochs = EpochsArray(data=dat, info=info, events=events, event_id=event_id, reject=reject) freqs = np.arange(35, 70, 5, dtype=np.float64) power, itc = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0) power2, itc2 = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, decim=slice(0, 2)) picks = np.arange(len(ch_names)) power_picks, itc_picks = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, picks=picks) power_epochs = tfr_multitaper(epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, return_itc=False, average=False) power_averaged = power_epochs.average() power_evoked = tfr_multitaper(epochs.average(), freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, return_itc=False, average=False).average() print(power_evoked) # test repr for EpochsTFR # Test channel picking power_epochs_picked = power_epochs.copy().drop_channels(['SIM0002']) assert_equal(power_epochs_picked.data.shape, (3, 1, 7, 200)) assert_equal(power_epochs_picked.ch_names, ['SIM0001']) pytest.raises(ValueError, tfr_multitaper, epochs, freqs=freqs, n_cycles=freqs / 2., return_itc=True, average=False) # test picks argument assert_allclose(power.data, power_picks.data) assert_allclose(power.data, power_averaged.data) assert_allclose(power.times, power_epochs.times) assert_allclose(power.times, power_averaged.times) assert_equal(power.nave, power_averaged.nave) assert_equal(power_epochs.data.shape, (3, 2, 7, 200)) assert_allclose(itc.data, itc_picks.data) # one is squared magnitude of the average (evoked) and # the other is average of the squared magnitudes (epochs PSD) # so values shouldn't match, but shapes should assert_array_equal(power.data.shape, power_evoked.data.shape) pytest.raises(AssertionError, assert_allclose, power.data, power_evoked.data) tmax = t[np.argmax(itc.data[0, freqs == 50, :])] fmax = freqs[np.argmax(power.data[1, :, t == 0.5])] assert (tmax > 0.3 and tmax < 0.7) assert not np.any(itc.data < 0.) assert (fmax > 40 and fmax < 60) assert (power2.data.shape == (len(picks), len(freqs), 2)) assert (power2.data.shape == itc2.data.shape) # Test decim parameter checks and compatibility between wavelets length # and instance length in the time dimension. pytest.raises(TypeError, tfr_multitaper, epochs, freqs=freqs, n_cycles=freqs / 2., time_bandwidth=4.0, decim=(1,)) pytest.raises(ValueError, tfr_multitaper, epochs, freqs=freqs, n_cycles=1000, time_bandwidth=4.0) # Test invalid frequency arguments with pytest.raises(ValueError, match=" 'freqs' must be greater than 0"): tfr_multitaper(epochs, freqs=np.arange(0, 3), n_cycles=7) with pytest.raises(ValueError, match=" 'freqs' must be greater than 0"): tfr_multitaper(epochs, freqs=np.arange(-4, -1), n_cycles=7) def test_crop(): """Test TFR cropping.""" data = np.zeros((3, 4, 5)) times = np.array([.1, .2, .3, .4, .5]) freqs = np.array([.10, .20, .30, .40]) info = mne.create_info(['MEG 001', 'MEG 002', 'MEG 003'], 1000., ['mag', 'mag', 'mag']) tfr = AverageTFR(info, data=data, times=times, freqs=freqs, nave=20, comment='test', method='crazy-tfr') tfr.crop(tmin=0.2) assert_array_equal(tfr.times, [0.2, 0.3, 0.4, 0.5]) assert tfr.data.ndim == 3 assert tfr.data.shape[-1] == 4 tfr.crop(fmax=0.3) assert_array_equal(tfr.freqs, [0.1, 0.2, 0.3]) assert tfr.data.ndim == 3 assert tfr.data.shape[-2] == 3 tfr.crop(tmin=0.3, tmax=0.4, fmin=0.1, fmax=0.2) assert_array_equal(tfr.times, [0.3, 0.4]) assert tfr.data.ndim == 3 assert tfr.data.shape[-1] == 2 assert_array_equal(tfr.freqs, [0.1, 0.2]) assert tfr.data.shape[-2] == 2 @requires_h5py @requires_pandas def test_io(tmpdir): """Test TFR IO capacities.""" from pandas import DataFrame tempdir = str(tmpdir) fname = op.join(tempdir, 'test-tfr.h5') data = np.zeros((3, 2, 3)) times = np.array([.1, .2, .3]) freqs = np.array([.10, .20]) info = mne.create_info(['MEG 001', 'MEG 002', 'MEG 003'], 1000., ['mag', 'mag', 'mag']) info['meas_date'] = datetime.datetime(year=2020, month=2, day=5, tzinfo=datetime.timezone.utc) info._check_consistency() tfr = AverageTFR(info, data=data, times=times, freqs=freqs, nave=20, comment='test', method='crazy-tfr') tfr.save(fname) tfr2 = read_tfrs(fname, condition='test') assert isinstance(tfr2.info, Info) assert isinstance(tfr2.info['dev_head_t'], Transform) assert_array_equal(tfr.data, tfr2.data) assert_array_equal(tfr.times, tfr2.times) assert_array_equal(tfr.freqs, tfr2.freqs) assert_equal(tfr.comment, tfr2.comment) assert_equal(tfr.nave, tfr2.nave) pytest.raises(IOError, tfr.save, fname) tfr.comment = None # test old meas_date info['meas_date'] = (1, 2) tfr.save(fname, overwrite=True) assert_equal(read_tfrs(fname, condition=0).comment, tfr.comment) tfr.comment = 'test-A' tfr2.comment = 'test-B' fname = op.join(tempdir, 'test2-tfr.h5') write_tfrs(fname, [tfr, tfr2]) tfr3 = read_tfrs(fname, condition='test-A') assert_equal(tfr.comment, tfr3.comment) assert (isinstance(tfr.info, mne.Info)) tfrs = read_tfrs(fname, condition=None) assert_equal(len(tfrs), 2) tfr4 = tfrs[1] assert_equal(tfr2.comment, tfr4.comment) pytest.raises(ValueError, read_tfrs, fname, condition='nonono') # Test save of EpochsTFR. n_events = 5 data = np.zeros((n_events, 3, 2, 3)) # create fake metadata rng = np.random.RandomState(42) rt = np.round(rng.uniform(size=(n_events,)), 3) trialtypes = np.array(['face', 'place']) trial = trialtypes[(rng.uniform(size=(n_events,)) > .5).astype(int)] meta = DataFrame(dict(RT=rt, Trial=trial)) # fake events and event_id events = np.zeros([n_events, 3]) events[:, 0] = np.arange(n_events) events[:, 2] = np.ones(n_events) event_id = {'a/b': 1} # fake selection n_dropped_epochs = 3 selection = np.arange(n_events + n_dropped_epochs)[n_dropped_epochs:] drop_log = tuple([('IGNORED',) for i in range(n_dropped_epochs)] + [() for i in range(n_events)]) tfr = EpochsTFR(info, data=data, times=times, freqs=freqs, comment='test', method='crazy-tfr', events=events, event_id=event_id, selection=selection, drop_log=drop_log, metadata=meta) fname_save = fname tfr.save(fname_save, True) fname_write = op.join(tempdir, 'test3-tfr.h5') write_tfrs(fname_write, tfr, overwrite=True) for fname in [fname_save, fname_write]: read_tfr = read_tfrs(fname)[0] assert_array_equal(tfr.data, read_tfr.data) assert_metadata_equal(tfr.metadata, read_tfr.metadata) assert_array_equal(tfr.events, read_tfr.events) assert tfr.event_id == read_tfr.event_id assert_array_equal(tfr.selection, read_tfr.selection) assert tfr.drop_log == read_tfr.drop_log with pytest.raises(NotImplementedError, match='condition not supported'): tfr = read_tfrs(fname, condition='a') def test_init_EpochsTFR(): """Test __init__ for EpochsTFR.""" # Create fake data: data = np.zeros((3, 3, 3, 3)) times = np.array([.1, .2, .3]) freqs = np.array([.10, .20, .30]) info = mne.create_info(['MEG 001', 'MEG 002', 'MEG 003'], 1000., ['mag', 'mag', 'mag']) data_x = data[:, :, :, 0] with pytest.raises(ValueError, match='data should be 4d. Got 3'): tfr = EpochsTFR(info, data=data_x, times=times, freqs=freqs) data_x = data[:, :-1, :, :] with pytest.raises(ValueError, match="channels and data size don't"): tfr = EpochsTFR(info, data=data_x, times=times, freqs=freqs) times_x = times[:-1] with pytest.raises(ValueError, match="times and data size don't match"): tfr = EpochsTFR(info, data=data, times=times_x, freqs=freqs) freqs_x = freqs[:-1] with pytest.raises(ValueError, match="frequencies and data size don't"): tfr = EpochsTFR(info, data=data, times=times_x, freqs=freqs_x) del(tfr) def test_plot(): """Test TFR plotting.""" data = np.zeros((3, 2, 3)) times = np.array([.1, .2, .3]) freqs = np.array([.10, .20]) info = mne.create_info(['MEG 001', 'MEG 002', 'MEG 003'], 1000., ['mag', 'mag', 'mag']) tfr = AverageTFR(info, data=data, times=times, freqs=freqs, nave=20, comment='test', method='crazy-tfr') # test title=auto, combine=None, and correct length of figure list picks = [1, 2] figs = tfr.plot(picks, title='auto', colorbar=False, mask=np.ones(tfr.data.shape[1:], bool)) assert len(figs) == len(picks) assert 'MEG' in figs[0].texts[0].get_text() plt.close('all') # test combine and title keyword figs = tfr.plot(picks, title='title', colorbar=False, combine='rms', mask=np.ones(tfr.data.shape[1:], bool)) assert len(figs) == 1 assert figs[0].texts[0].get_text() == 'title' figs = tfr.plot(picks, title='auto', colorbar=False, combine='mean', mask=np.ones(tfr.data.shape[1:], bool)) assert len(figs) == 1 assert figs[0].texts[0].get_text() == 'Mean of 2 sensors' with pytest.raises(ValueError, match='combine must be None'): tfr.plot(picks, colorbar=False, combine='something', mask=np.ones(tfr.data.shape[1:], bool)) plt.close('all') # test axes argument - first with list of axes ax = plt.subplot2grid((2, 2), (0, 0)) ax2 = plt.subplot2grid((2, 2), (0, 1)) ax3 = plt.subplot2grid((2, 2), (1, 0)) figs = tfr.plot(picks=[0, 1, 2], axes=[ax, ax2, ax3]) assert len(figs) == len([ax, ax2, ax3]) # and as a single axes figs = tfr.plot(picks=[0], axes=ax) assert len(figs) == 1 plt.close('all') # and invalid inputs with pytest.raises(ValueError, match='axes must be None'): tfr.plot(picks, colorbar=False, axes={}, mask=np.ones(tfr.data.shape[1:], bool)) # different number of axes and picks should throw a RuntimeError with pytest.raises(RuntimeError, match='There must be an axes'): tfr.plot(picks=[0], colorbar=False, axes=[ax, ax2], mask=np.ones(tfr.data.shape[1:], bool)) tfr.plot_topo(picks=[1, 2]) plt.close('all') # interactive mode on by default fig = tfr.plot(picks=[1], cmap='RdBu_r')[0] fig.canvas.key_press_event('up') fig.canvas.key_press_event(' ') fig.canvas.key_press_event('down') fig.canvas.key_press_event(' ') fig.canvas.key_press_event('+') fig.canvas.key_press_event(' ') fig.canvas.key_press_event('-') fig.canvas.key_press_event(' ') fig.canvas.key_press_event('pageup') fig.canvas.key_press_event(' ') fig.canvas.key_press_event('pagedown') cbar = fig.get_axes()[0].CB # Fake dragging with mouse. ax = cbar.cbar.ax _fake_click(fig, ax, (0.1, 0.1)) _fake_click(fig, ax, (0.1, 0.2), kind='motion') _fake_click(fig, ax, (0.1, 0.3), kind='release') _fake_click(fig, ax, (0.1, 0.1), button=3) _fake_click(fig, ax, (0.1, 0.2), button=3, kind='motion') _fake_click(fig, ax, (0.1, 0.3), kind='release') fig.canvas.scroll_event(0.5, 0.5, -0.5) # scroll down fig.canvas.scroll_event(0.5, 0.5, 0.5) # scroll up plt.close('all') def test_plot_joint(): """Test TFR joint plotting.""" raw = read_raw_fif(raw_fname) times = np.linspace(-0.1, 0.1, 200) n_freqs = 3 nave = 1 rng = np.random.RandomState(42) data = rng.randn(len(raw.ch_names), n_freqs, len(times)) tfr = AverageTFR(raw.info, data, times, np.arange(n_freqs), nave) topomap_args = {'res': 8, 'contours': 0, 'sensors': False} for combine in ('mean', 'rms'): with catch_logging() as log: tfr.plot_joint(title='auto', colorbar=True, combine=combine, topomap_args=topomap_args, verbose='debug') plt.close('all') log = log.getvalue() assert 'Plotting topomap for grad data' in log # check various timefreqs for timefreqs in ( {(tfr.times[0], tfr.freqs[1]): (0.1, 0.5), (tfr.times[-1], tfr.freqs[-1]): (0.2, 0.6)}, [(tfr.times[1], tfr.freqs[1])]): tfr.plot_joint(timefreqs=timefreqs, topomap_args=topomap_args) plt.close('all') # test bad timefreqs timefreqs = ([(-100, 1)], tfr.times[1], [1], [(tfr.times[1], tfr.freqs[1], tfr.freqs[1])]) for these_timefreqs in timefreqs: pytest.raises(ValueError, tfr.plot_joint, these_timefreqs) # test that the object is not internally modified tfr_orig = tfr.copy() tfr.plot_joint(baseline=(0, None), exclude=[tfr.ch_names[0]], topomap_args=topomap_args) plt.close('all') assert_array_equal(tfr.data, tfr_orig.data) assert set(tfr.ch_names) == set(tfr_orig.ch_names) assert set(tfr.times) == set(tfr_orig.times) # test tfr with picked channels tfr.pick_channels(tfr.ch_names[:-1]) tfr.plot_joint(title='auto', colorbar=True, topomap_args=topomap_args) def test_add_channels(): """Test tfr splitting / re-appending channel types.""" data = np.zeros((6, 2, 3)) times = np.array([.1, .2, .3]) freqs = np.array([.10, .20]) info = mne.create_info( ['MEG 001', 'MEG 002', 'MEG 003', 'EEG 001', 'EEG 002', 'STIM 001'], 1000., ['mag', 'mag', 'mag', 'eeg', 'eeg', 'stim']) tfr = AverageTFR(info, data=data, times=times, freqs=freqs, nave=20, comment='test', method='crazy-tfr') tfr_eeg = tfr.copy().pick_types(meg=False, eeg=True) tfr_meg = tfr.copy().pick_types(meg=True) tfr_stim = tfr.copy().pick_types(meg=False, stim=True) tfr_eeg_meg = tfr.copy().pick_types(meg=True, eeg=True) tfr_new = tfr_meg.copy().add_channels([tfr_eeg, tfr_stim]) assert all(ch in tfr_new.ch_names for ch in tfr_stim.ch_names + tfr_meg.ch_names) tfr_new = tfr_meg.copy().add_channels([tfr_eeg]) have_all = all(ch in tfr_new.ch_names for ch in tfr.ch_names if ch != 'STIM 001') assert have_all assert_array_equal(tfr_new.data, tfr_eeg_meg.data) assert all(ch not in tfr_new.ch_names for ch in tfr_stim.ch_names) # Now test errors tfr_badsf = tfr_eeg.copy() tfr_badsf.info['sfreq'] = 3.1415927 tfr_eeg = tfr_eeg.crop(-.1, .1) pytest.raises(RuntimeError, tfr_meg.add_channels, [tfr_badsf]) pytest.raises(AssertionError, tfr_meg.add_channels, [tfr_eeg]) pytest.raises(ValueError, tfr_meg.add_channels, [tfr_meg]) pytest.raises(TypeError, tfr_meg.add_channels, tfr_badsf) def test_compute_tfr(): """Test _compute_tfr function.""" # Set parameters event_id = 1 tmin = -0.2 tmax = 0.498 # Allows exhaustive decimation testing # Setup for reading the raw data raw = read_raw_fif(raw_fname) events = read_events(event_fname) exclude = raw.info['bads'] + ['MEG 2443', 'EEG 053'] # bads + 2 more # picks MEG gradiometers picks = pick_types(raw.info, meg='grad', eeg=False, stim=False, include=[], exclude=exclude) picks = picks[:2] epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks) data = epochs.get_data() sfreq = epochs.info['sfreq'] freqs = np.arange(10, 20, 3).astype(float) # Check all combination of options for func, use_fft, zero_mean, output in product( (tfr_array_multitaper, tfr_array_morlet), (False, True), (False, True), ('complex', 'power', 'phase', 'avg_power_itc', 'avg_power', 'itc')): # Check exception if (func == tfr_array_multitaper) and (output == 'phase'): pytest.raises(NotImplementedError, func, data, sfreq=sfreq, freqs=freqs, output=output) continue # Check runs out = func(data, sfreq=sfreq, freqs=freqs, use_fft=use_fft, zero_mean=zero_mean, n_cycles=2., output=output) # Check shapes shape = np.r_[data.shape[:2], len(freqs), data.shape[2]] if ('avg' in output) or ('itc' in output): assert_array_equal(shape[1:], out.shape) else: assert_array_equal(shape, out.shape) # Check types if output in ('complex', 'avg_power_itc'): assert_equal(np.complex128, out.dtype) else: assert_equal(np.float64, out.dtype) assert (np.all(np.isfinite(out))) # Check errors params for _data in (None, 'foo', data[0]): pytest.raises(ValueError, _compute_tfr, _data, freqs, sfreq) for _freqs in (None, 'foo', [[0]]): pytest.raises(ValueError, _compute_tfr, data, _freqs, sfreq) for _sfreq in (None, 'foo'): pytest.raises(ValueError, _compute_tfr, data, freqs, _sfreq) for key in ('output', 'method', 'use_fft', 'decim', 'n_jobs'): for value in (None, 'foo'): kwargs = {key: value} # FIXME pep8 pytest.raises(ValueError, _compute_tfr, data, freqs, sfreq, **kwargs) with pytest.raises(ValueError, match='above Nyquist'): _compute_tfr(data, [sfreq], sfreq) # No time_bandwidth param in morlet pytest.raises(ValueError, _compute_tfr, data, freqs, sfreq, method='morlet', time_bandwidth=1) # No phase in multitaper XXX Check ? pytest.raises(NotImplementedError, _compute_tfr, data, freqs, sfreq, method='multitaper', output='phase') # Inter-trial coherence tests out = _compute_tfr(data, freqs, sfreq, output='itc', n_cycles=2.) assert np.sum(out >= 1) == 0 assert np.sum(out <= 0) == 0 # Check decim shapes # 2: multiple of len(times) even # 3: multiple odd # 8: not multiple, even # 9: not multiple, odd for decim in (2, 3, 8, 9, slice(0, 2), slice(1, 3), slice(2, 4)): _decim = slice(None, None, decim) if isinstance(decim, int) else decim n_time = len(np.arange(data.shape[2])[_decim]) shape = np.r_[data.shape[:2], len(freqs), n_time] for method in ('multitaper', 'morlet'): # Single trials out = _compute_tfr(data, freqs, sfreq, method=method, decim=decim, n_cycles=2.) assert_array_equal(shape, out.shape) # Averages out = _compute_tfr(data, freqs, sfreq, method=method, decim=decim, output='avg_power', n_cycles=2.) assert_array_equal(shape[1:], out.shape) @pytest.mark.parametrize('method', ('multitaper', 'morlet')) @pytest.mark.parametrize('decim', (1, slice(1, None, 2), 3)) def test_compute_tfr_correct(method, decim): """Test that TFR actually gets us our freq back.""" sfreq = 1000. t = np.arange(1000) / sfreq f = 50. data = np.sin(2 * np.pi * 50. * t) data *= np.hanning(data.size) data = data[np.newaxis, np.newaxis] freqs = np.arange(10, 111, 10) assert f in freqs tfr = _compute_tfr(data, freqs, sfreq, method=method, decim=decim, n_cycles=2)[0, 0] assert freqs[np.argmax(np.abs(tfr).mean(-1))] == f def test_averaging_epochsTFR(): """Test that EpochsTFR averaging methods work.""" # Setup for reading the raw data event_id = 1 tmin = -0.2 tmax = 0.498 # Allows exhaustive decimation testing freqs = np.arange(6, 20, 5) # define frequencies of interest n_cycles = freqs / 4. raw = read_raw_fif(raw_fname) # only pick a few events for speed events = read_events(event_fname)[:4] include = [] exclude = raw.info['bads'] + ['MEG 2443', 'EEG 053'] # bads + 2 more # picks MEG gradiometers picks = pick_types(raw.info, meg='grad', eeg=False, stim=False, include=include, exclude=exclude) picks = picks[:2] epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks) # Obtain EpochsTFR power = tfr_morlet(epochs, freqs=freqs, n_cycles=n_cycles, average=False, use_fft=True, return_itc=False) # Test average methods for func, method in zip( [np.mean, np.median, np.mean], ['mean', 'median', lambda x: np.mean(x, axis=0)]): avgpower = power.average(method=method) np.testing.assert_array_equal(func(power.data, axis=0), avgpower.data) with pytest.raises(RuntimeError, match='You passed a function that ' 'resulted in data'): power.average(method=np.mean) @requires_pandas def test_getitem_epochsTFR(): """Test GetEpochsMixin in the context of EpochsTFR.""" from pandas import DataFrame # Setup for reading the raw data and select a few trials raw = read_raw_fif(raw_fname) events = read_events(event_fname) # create fake data, test with and without dropping epochs for n_drop_epochs in [0, 2]: n_events = 12 # create fake metadata rng = np.random.RandomState(42) rt = rng.uniform(size=(n_events,)) trialtypes = np.array(['face', 'place']) trial = trialtypes[(rng.uniform(size=(n_events,)) > .5).astype(int)] meta = DataFrame(dict(RT=rt, Trial=trial)) event_id = dict(a=1, b=2, c=3, d=4) epochs = Epochs(raw, events[:n_events], event_id=event_id, metadata=meta, decim=1) epochs.drop(np.arange(n_drop_epochs)) n_events -= n_drop_epochs freqs = np.arange(12., 17., 2.) # define frequencies of interest n_cycles = freqs / 2. # 0.5 second time windows for all frequencies # Choose time x (full) bandwidth product time_bandwidth = 4.0 # With 0.5 s time windows, this gives 8 Hz smoothing kwargs = dict(freqs=freqs, n_cycles=n_cycles, use_fft=True, time_bandwidth=time_bandwidth, return_itc=False, average=False, n_jobs=1) power = tfr_multitaper(epochs, **kwargs) # Check that power and epochs metadata is the same assert_metadata_equal(epochs.metadata, power.metadata) assert_metadata_equal(epochs[::2].metadata, power[::2].metadata) assert_metadata_equal(epochs['RT < .5'].metadata, power['RT < .5'].metadata) assert_array_equal(epochs.selection, power.selection) assert epochs.drop_log == power.drop_log # Check that get power is functioning assert_array_equal(power[3:6].data, power.data[3:6]) assert_array_equal(power[3:6].events, power.events[3:6]) assert_array_equal(epochs.selection[3:6], power.selection[3:6]) indx_check = (power.metadata['Trial'] == 'face') try: indx_check = indx_check.to_numpy() except Exception: pass # older Pandas indx_check = indx_check.nonzero() assert_array_equal(power['Trial == "face"'].events, power.events[indx_check]) assert_array_equal(power['Trial == "face"'].data, power.data[indx_check]) # Check that the wrong Key generates a Key Error for Metadata search with pytest.raises(KeyError): power['Trialz == "place"'] # Test length function assert len(power) == n_events assert len(power[3:6]) == 3 # Test iteration function for ind, power_ep in enumerate(power): assert_array_equal(power_ep, power.data[ind]) if ind == 5: break # Test that current state is maintained assert_array_equal(power.next(), power.data[ind + 1]) # Check decim affects sfreq power_decim = tfr_multitaper(epochs, decim=2, **kwargs) assert power.info['sfreq'] / 2. == power_decim.info['sfreq'] @requires_pandas def test_to_data_frame(): """Test EpochsTFR Pandas exporter.""" # Create fake EpochsTFR data: n_epos = 3 ch_names = ['EEG 001', 'EEG 002', 'EEG 003', 'EEG 004'] n_picks = len(ch_names) ch_types = ['eeg'] * n_picks n_freqs = 5 n_times = 6 data = np.random.rand(n_epos, n_picks, n_freqs, n_times) times = np.arange(6) srate = 1000. freqs = np.arange(5) events = np.zeros((n_epos, 3), dtype=int) events[:, 0] = np.arange(n_epos) events[:, 2] = np.arange(5, 5 + n_epos) event_id = {k: v for v, k in zip(events[:, 2], ['ha', 'he', 'hu'])} info = mne.create_info(ch_names, srate, ch_types) tfr = mne.time_frequency.EpochsTFR(info, data, times, freqs, events=events, event_id=event_id) # test index checking with pytest.raises(ValueError, match='options. Valid index options are'): tfr.to_data_frame(index=['foo', 'bar']) with pytest.raises(ValueError, match='"qux" is not a valid option'): tfr.to_data_frame(index='qux') with pytest.raises(TypeError, match='index must be `None` or a string '): tfr.to_data_frame(index=np.arange(400)) # test wide format df_wide = tfr.to_data_frame() assert all(np.in1d(tfr.ch_names, df_wide.columns)) assert all(np.in1d(['time', 'condition', 'freq', 'epoch'], df_wide.columns)) # test long format df_long = tfr.to_data_frame(long_format=True) expected = ('condition', 'epoch', 'freq', 'time', 'channel', 'ch_type', 'value') assert set(expected) == set(df_long.columns) assert set(tfr.ch_names) == set(df_long['channel']) assert(len(df_long) == tfr.data.size) # test long format w/ index df_long = tfr.to_data_frame(long_format=True, index=['freq']) del df_wide, df_long # test whether data is in correct shape df = tfr.to_data_frame(index=['condition', 'epoch', 'freq', 'time']) data = tfr.data assert_array_equal(df.values[:, 0], data[:, 0, :, :].reshape(1, -1).squeeze()) # compare arbitrary observation: assert df.loc[('he', slice(None), freqs[1], times[2] * srate), ch_names[3]].iloc[0] == data[1, 3, 1, 2] # Check also for AverageTFR: tfr = tfr.average() with pytest.raises(ValueError, match='options. Valid index options are'): tfr.to_data_frame(index=['epoch', 'condition']) with pytest.raises(ValueError, match='"epoch" is not a valid option'): tfr.to_data_frame(index='epoch') with pytest.raises(TypeError, match='index must be `None` or a string '): tfr.to_data_frame(index=np.arange(400)) # test wide format df_wide = tfr.to_data_frame() assert all(np.in1d(tfr.ch_names, df_wide.columns)) assert all(np.in1d(['time', 'freq'], df_wide.columns)) # test long format df_long = tfr.to_data_frame(long_format=True) expected = ('freq', 'time', 'channel', 'ch_type', 'value') assert set(expected) == set(df_long.columns) assert set(tfr.ch_names) == set(df_long['channel']) assert(len(df_long) == tfr.data.size) # test long format w/ index df_long = tfr.to_data_frame(long_format=True, index=['freq']) del df_wide, df_long # test whether data is in correct shape df = tfr.to_data_frame(index=['freq', 'time']) data = tfr.data assert_array_equal(df.values[:, 0], data[0, :, :].reshape(1, -1).squeeze()) # compare arbitrary observation: assert df.loc[(freqs[1], times[2] * srate), ch_names[3]] == \ data[3, 1, 2] @requires_pandas @pytest.mark.parametrize('index', ('time', ['condition', 'time', 'freq'], ['freq', 'time'], ['time', 'freq'], None)) def test_to_data_frame_index(index): """Test index creation in epochs Pandas exporter.""" # Create fake EpochsTFR data: n_epos = 3 ch_names = ['EEG 001', 'EEG 002', 'EEG 003', 'EEG 004'] n_picks = len(ch_names) ch_types = ['eeg'] * n_picks n_freqs = 5 n_times = 6 data = np.random.rand(n_epos, n_picks, n_freqs, n_times) times = np.arange(6) freqs = np.arange(5) events = np.zeros((n_epos, 3), dtype=int) events[:, 0] = np.arange(n_epos) events[:, 2] = np.arange(5, 8) event_id = {k: v for v, k in zip(events[:, 2], ['ha', 'he', 'hu'])} info = mne.create_info(ch_names, 1000., ch_types) tfr = mne.time_frequency.EpochsTFR(info, data, times, freqs, events=events, event_id=event_id) df = tfr.to_data_frame(picks=[0, 2, 3], index=index) # test index order/hierarchy preservation if not isinstance(index, list): index = [index] assert (df.index.names == index) # test that non-indexed data were present as columns non_index = list(set(['condition', 'time', 'freq', 'epoch']) - set(index)) if len(non_index): assert all(np.in1d(non_index, df.columns)) @requires_pandas @pytest.mark.parametrize('time_format', (None, 'ms', 'timedelta')) def test_to_data_frame_time_format(time_format): """Test time conversion in epochs Pandas exporter.""" from pandas import Timedelta n_epos = 3 ch_names = ['EEG 001', 'EEG 002', 'EEG 003', 'EEG 004'] n_picks = len(ch_names) ch_types = ['eeg'] * n_picks n_freqs = 5 n_times = 6 data = np.random.rand(n_epos, n_picks, n_freqs, n_times) times = np.arange(6) freqs = np.arange(5) events = np.zeros((n_epos, 3), dtype=int) events[:, 0] = np.arange(n_epos) events[:, 2] = np.arange(5, 8) event_id = {k: v for v, k in zip(events[:, 2], ['ha', 'he', 'hu'])} info = mne.create_info(ch_names, 1000., ch_types) tfr = mne.time_frequency.EpochsTFR(info, data, times, freqs, events=events, event_id=event_id) # test time_format df = tfr.to_data_frame(time_format=time_format) dtypes = {None: np.float64, 'ms': np.int64, 'timedelta': Timedelta} assert isinstance(df['time'].iloc[0], dtypes[time_format])
rkmaddox/mne-python
mne/time_frequency/tests/test_tfr.py
mne/label.py
# -*- encoding: utf-8 -*- from abjad import * def test_indicatortools_Clef_middle_c_position_01(): assert Clef('treble').middle_c_position == pitchtools.StaffPosition(-6) assert Clef('alto').middle_c_position == pitchtools.StaffPosition(0) assert Clef('tenor').middle_c_position == pitchtools.StaffPosition(2) assert Clef('bass').middle_c_position == pitchtools.StaffPosition(6) assert Clef('treble^8').middle_c_position == pitchtools.StaffPosition(-13) assert Clef('alto^15').middle_c_position == pitchtools.StaffPosition(-13) assert Clef('tenor_8').middle_c_position == pitchtools.StaffPosition(9) assert Clef('bass_15').middle_c_position == pitchtools.StaffPosition(19)
# -*- encoding: utf-8 -*- import pytest from abjad import * def test_indicatortools_Tempo___mul___01(): tempo = Tempo(Duration(1, 4), 60) result = tempo * Duration(1, 2) assert result == Tempo(Duration(1, 4), 30) result = tempo * Duration(2, 3) assert result == Tempo(Duration(1, 4), 40) result = tempo * Duration(3, 4) assert result == Tempo(Duration(1, 4), 45) result = tempo * Duration(4, 5) assert result == Tempo(Duration(1, 4), 48) result = tempo * Duration(5, 6) assert result == Tempo(Duration(1, 4), 50) result = tempo * Duration(6, 7) assert result == Tempo( Duration(1, 4), Duration(360, 7)) def test_indicatortools_Tempo___mul___02(): tempo = Tempo(Duration(1, 4), 60) result = tempo * 1 assert result == Tempo(Duration(1, 4), 60) result = tempo * 2 assert result == Tempo(Duration(1, 4), 120) result = tempo * 3 assert result == Tempo(Duration(1, 4), 180) result = tempo * 4 assert result == Tempo(Duration(1, 4), 240) def test_indicatortools_Tempo___mul___03(): tempo_1 = Tempo(textual_indication='Langsam') pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)") def test_indicatortools_Tempo___mul___04(): tempo_1 = Tempo(Duration(1, 8), (90, 92)) pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)")
mscuthbert/abjad
abjad/tools/indicatortools/test/test_indicatortools_Tempo___mul__.py
abjad/tools/indicatortools/test/test_indicatortools_Clef_middle_c_position.py
# -*- encoding: utf-8 -*- from abjad.tools import indicatortools from abjad.tools import pitchtools from abjad.tools import scoretools from abjad.tools.topleveltools import iterate def iterate_out_of_range_notes_and_chords(expr): '''Iterates notes and chords in `expr` outside traditional instrument ranges: :: >>> staff = Staff("c'8 r8 <d fs>8 r8") >>> violin = instrumenttools.Violin() >>> attach(violin, staff) :: >>> list( ... instrumenttools.iterate_out_of_range_notes_and_chords( ... staff)) [Chord('<d fs>8')] Returns generator. ''' from abjad.tools import instrumenttools prototype = (scoretools.Note, scoretools.Chord) for note_or_chord in iterate(expr).by_class(prototype): instrument = note_or_chord._get_effective( instrumenttools.Instrument) if instrument is None: message = 'no instrument found.' raise ValueError(message) if note_or_chord not in instrument.pitch_range: yield note_or_chord
# -*- encoding: utf-8 -*- import pytest from abjad import * def test_indicatortools_Tempo___mul___01(): tempo = Tempo(Duration(1, 4), 60) result = tempo * Duration(1, 2) assert result == Tempo(Duration(1, 4), 30) result = tempo * Duration(2, 3) assert result == Tempo(Duration(1, 4), 40) result = tempo * Duration(3, 4) assert result == Tempo(Duration(1, 4), 45) result = tempo * Duration(4, 5) assert result == Tempo(Duration(1, 4), 48) result = tempo * Duration(5, 6) assert result == Tempo(Duration(1, 4), 50) result = tempo * Duration(6, 7) assert result == Tempo( Duration(1, 4), Duration(360, 7)) def test_indicatortools_Tempo___mul___02(): tempo = Tempo(Duration(1, 4), 60) result = tempo * 1 assert result == Tempo(Duration(1, 4), 60) result = tempo * 2 assert result == Tempo(Duration(1, 4), 120) result = tempo * 3 assert result == Tempo(Duration(1, 4), 180) result = tempo * 4 assert result == Tempo(Duration(1, 4), 240) def test_indicatortools_Tempo___mul___03(): tempo_1 = Tempo(textual_indication='Langsam') pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)") def test_indicatortools_Tempo___mul___04(): tempo_1 = Tempo(Duration(1, 8), (90, 92)) pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)")
mscuthbert/abjad
abjad/tools/indicatortools/test/test_indicatortools_Tempo___mul__.py
abjad/tools/instrumenttools/iterate_out_of_range_notes_and_chords.py
# -*- encoding: utf-8 -*- from abjad.tools.datastructuretools.TreeNode import TreeNode class ReSTHorizontalRule(TreeNode): r'''A ReST horizontal rule. :: >>> rule = documentationtools.ReSTHorizontalRule() >>> rule ReSTHorizontalRule() :: >>> print(rule.rest_format) -------- ''' ### CLASS VARIABLES ### __documentation_section__ = 'reStructuredText' ### PRIVATE PROPERTIES ### @property def _rest_format_contributions(self): return ['--------'] ### PUBLIC PROPERTIES ### @property def rest_format(self): r'''ReST format of ReSt horizontal rule. Returns text. ''' return '\n'.join(self._rest_format_contributions)
# -*- encoding: utf-8 -*- import pytest from abjad import * def test_indicatortools_Tempo___mul___01(): tempo = Tempo(Duration(1, 4), 60) result = tempo * Duration(1, 2) assert result == Tempo(Duration(1, 4), 30) result = tempo * Duration(2, 3) assert result == Tempo(Duration(1, 4), 40) result = tempo * Duration(3, 4) assert result == Tempo(Duration(1, 4), 45) result = tempo * Duration(4, 5) assert result == Tempo(Duration(1, 4), 48) result = tempo * Duration(5, 6) assert result == Tempo(Duration(1, 4), 50) result = tempo * Duration(6, 7) assert result == Tempo( Duration(1, 4), Duration(360, 7)) def test_indicatortools_Tempo___mul___02(): tempo = Tempo(Duration(1, 4), 60) result = tempo * 1 assert result == Tempo(Duration(1, 4), 60) result = tempo * 2 assert result == Tempo(Duration(1, 4), 120) result = tempo * 3 assert result == Tempo(Duration(1, 4), 180) result = tempo * 4 assert result == Tempo(Duration(1, 4), 240) def test_indicatortools_Tempo___mul___03(): tempo_1 = Tempo(textual_indication='Langsam') pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)") def test_indicatortools_Tempo___mul___04(): tempo_1 = Tempo(Duration(1, 8), (90, 92)) pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)")
mscuthbert/abjad
abjad/tools/indicatortools/test/test_indicatortools_Tempo___mul__.py
abjad/tools/documentationtools/ReSTHorizontalRule.py
# -*- encoding: utf-8 -*- from abjad import * def test_pitchtools_NumberedPitch_pitch_number_01(): assert pitchtools.NumberedPitch("cff''").pitch_number == 10 assert pitchtools.NumberedPitch("ctqf''").pitch_number == 10.5 assert pitchtools.NumberedPitch("cf''").pitch_number == 11 assert pitchtools.NumberedPitch("cqf''").pitch_number == 11.5 assert pitchtools.NumberedPitch("c''").pitch_number == 12 assert pitchtools.NumberedPitch("cqs''").pitch_number == 12.5 assert pitchtools.NumberedPitch("cs''").pitch_number == 13 assert pitchtools.NumberedPitch("ctqs''").pitch_number == 13.5 assert pitchtools.NumberedPitch("css''").pitch_number == 14 assert pitchtools.NumberedPitch("d''").pitch_number == 14
# -*- encoding: utf-8 -*- import pytest from abjad import * def test_indicatortools_Tempo___mul___01(): tempo = Tempo(Duration(1, 4), 60) result = tempo * Duration(1, 2) assert result == Tempo(Duration(1, 4), 30) result = tempo * Duration(2, 3) assert result == Tempo(Duration(1, 4), 40) result = tempo * Duration(3, 4) assert result == Tempo(Duration(1, 4), 45) result = tempo * Duration(4, 5) assert result == Tempo(Duration(1, 4), 48) result = tempo * Duration(5, 6) assert result == Tempo(Duration(1, 4), 50) result = tempo * Duration(6, 7) assert result == Tempo( Duration(1, 4), Duration(360, 7)) def test_indicatortools_Tempo___mul___02(): tempo = Tempo(Duration(1, 4), 60) result = tempo * 1 assert result == Tempo(Duration(1, 4), 60) result = tempo * 2 assert result == Tempo(Duration(1, 4), 120) result = tempo * 3 assert result == Tempo(Duration(1, 4), 180) result = tempo * 4 assert result == Tempo(Duration(1, 4), 240) def test_indicatortools_Tempo___mul___03(): tempo_1 = Tempo(textual_indication='Langsam') pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)") def test_indicatortools_Tempo___mul___04(): tempo_1 = Tempo(Duration(1, 8), (90, 92)) pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)")
mscuthbert/abjad
abjad/tools/indicatortools/test/test_indicatortools_Tempo___mul__.py
abjad/tools/pitchtools/test/test_pitchtools_NumberedPitch_pitch_number.py
# -*- encoding: utf-8 -*- import functools from abjad.tools import durationtools from abjad.tools.schemetools.Scheme import Scheme @functools.total_ordering class SchemeMoment(Scheme): r'''A LilyPond scheme moment. Initializes with two integers: :: >>> moment = schemetools.SchemeMoment(1, 68) >>> moment SchemeMoment(1, 68) Scheme moments are immutable. ''' ### CLASS VARIABLES ### __slots__ = ( ) ### INITIALIZER ### def __init__(self, *args, **kwargs): if len(args) == 1 and durationtools.Duration.is_token(args[0]): args = durationtools.Duration(args[0]) elif len(args) == 1 and isinstance(args[0], type(self)): args = args[0].duration elif len(args) == 2 and \ isinstance(args[0], int) and isinstance(args[1], int): args = durationtools.Duration(args) elif len(args) == 0: args = durationtools.Duration((1, 4)) else: message = 'can not intialize {}: {!r}.' message = message.format(type(self).__name__, args) raise TypeError(message) Scheme.__init__(self, args, **kwargs) ### SPECIAL METHODS ### def __eq__(self, arg): r'''Is true when `arg` is a scheme moment with the same value as that of this scheme moment. :: >>> moment == schemetools.SchemeMoment(1, 68) True Otherwise false. >>> moment == schemetools.SchemeMoment(1, 54) False Returns boolean. ''' if isinstance(arg, type(self)): if self._value == arg._value: return True return False def __getnewargs__(self): r'''Gets new arguments. Returns tuple. ''' return (self._value,) def __hash__(self): r'''Hashes scheme moment. Required to be explicitly re-defined on Python 3 if __eq__ changes. Returns integer. ''' return super(SchemeMoment, self).__hash__() def __lt__(self, arg): r'''Is true when `arg` is a scheme moment with value greater than that of this scheme moment. :: >>> moment < schemetools.SchemeMoment(1, 32) True Otherwise false: :: >>> moment < schemetools.SchemeMoment(1, 78) False Returns boolean. ''' if isinstance(arg, type(self)): if self._value < arg._value: return True return False ### PRIVATE PROPERTIES ### @property def _formatted_value(self): numerator, denominator = self._value.numerator, self._value.denominator return '(ly:make-moment {} {})'.format(numerator, denominator) @property def _storage_format_specification(self): from abjad.tools import systemtools return systemtools.StorageFormatSpecification( self, positional_argument_values=( self._value.numerator, self._value.denominator, ), ) ### PUBLIC PROPERTIES ### @property def duration(self): r'''Duration of scheme moment. :: >>> scheme_moment = schemetools.SchemeMoment(1, 68) >>> scheme_moment.duration Duration(1, 68) Returns duration. ''' return self._value
# -*- encoding: utf-8 -*- import pytest from abjad import * def test_indicatortools_Tempo___mul___01(): tempo = Tempo(Duration(1, 4), 60) result = tempo * Duration(1, 2) assert result == Tempo(Duration(1, 4), 30) result = tempo * Duration(2, 3) assert result == Tempo(Duration(1, 4), 40) result = tempo * Duration(3, 4) assert result == Tempo(Duration(1, 4), 45) result = tempo * Duration(4, 5) assert result == Tempo(Duration(1, 4), 48) result = tempo * Duration(5, 6) assert result == Tempo(Duration(1, 4), 50) result = tempo * Duration(6, 7) assert result == Tempo( Duration(1, 4), Duration(360, 7)) def test_indicatortools_Tempo___mul___02(): tempo = Tempo(Duration(1, 4), 60) result = tempo * 1 assert result == Tempo(Duration(1, 4), 60) result = tempo * 2 assert result == Tempo(Duration(1, 4), 120) result = tempo * 3 assert result == Tempo(Duration(1, 4), 180) result = tempo * 4 assert result == Tempo(Duration(1, 4), 240) def test_indicatortools_Tempo___mul___03(): tempo_1 = Tempo(textual_indication='Langsam') pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)") def test_indicatortools_Tempo___mul___04(): tempo_1 = Tempo(Duration(1, 8), (90, 92)) pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)")
mscuthbert/abjad
abjad/tools/indicatortools/test/test_indicatortools_Tempo___mul__.py
abjad/tools/schemetools/SchemeMoment.py
# -*- encoding: utf-8 -*- from abjad import * def configure_lilypond_file(lilypond_file): r'''Configures LilyPond file. ''' lilypond_file.global_staff_size = 8 context_block = lilypondfiletools.ContextBlock( source_context_name=r'Staff \RemoveEmptyStaves', ) override(context_block).vertical_axis_group.remove_first = True lilypond_file.layout_block.items.append(context_block) slash_separator = indicatortools.LilyPondCommand('slashSeparator') lilypond_file.paper_block.system_separator_markup = slash_separator bottom_margin = lilypondfiletools.LilyPondDimension(0.5, 'in') lilypond_file.paper_block.bottom_margin = bottom_margin top_margin = lilypondfiletools.LilyPondDimension(0.5, 'in') lilypond_file.paper_block.top_margin = top_margin left_margin = lilypondfiletools.LilyPondDimension(0.75, 'in') lilypond_file.paper_block.left_margin = left_margin right_margin = lilypondfiletools.LilyPondDimension(0.5, 'in') lilypond_file.paper_block.right_margin = right_margin paper_width = lilypondfiletools.LilyPondDimension(5.25, 'in') lilypond_file.paper_block.paper_width = paper_width paper_height = lilypondfiletools.LilyPondDimension(7.25, 'in') lilypond_file.paper_block.paper_height = paper_height lilypond_file.header_block.composer = markuptools.Markup('Arvo Pärt') title = 'Cantus in Memory of Benjamin Britten (1980)' lilypond_file.header_block.title = markuptools.Markup(title)
# -*- encoding: utf-8 -*- import pytest from abjad import * def test_indicatortools_Tempo___mul___01(): tempo = Tempo(Duration(1, 4), 60) result = tempo * Duration(1, 2) assert result == Tempo(Duration(1, 4), 30) result = tempo * Duration(2, 3) assert result == Tempo(Duration(1, 4), 40) result = tempo * Duration(3, 4) assert result == Tempo(Duration(1, 4), 45) result = tempo * Duration(4, 5) assert result == Tempo(Duration(1, 4), 48) result = tempo * Duration(5, 6) assert result == Tempo(Duration(1, 4), 50) result = tempo * Duration(6, 7) assert result == Tempo( Duration(1, 4), Duration(360, 7)) def test_indicatortools_Tempo___mul___02(): tempo = Tempo(Duration(1, 4), 60) result = tempo * 1 assert result == Tempo(Duration(1, 4), 60) result = tempo * 2 assert result == Tempo(Duration(1, 4), 120) result = tempo * 3 assert result == Tempo(Duration(1, 4), 180) result = tempo * 4 assert result == Tempo(Duration(1, 4), 240) def test_indicatortools_Tempo___mul___03(): tempo_1 = Tempo(textual_indication='Langsam') pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)") def test_indicatortools_Tempo___mul___04(): tempo_1 = Tempo(Duration(1, 8), (90, 92)) pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)")
mscuthbert/abjad
abjad/tools/indicatortools/test/test_indicatortools_Tempo___mul__.py
abjad/demos/part/configure_lilypond_file.py
# -*- encoding: utf-8 -*- from abjad import * def test_selectiontools_Selection__get_component_01(): staff = Staff("abj: | 2/8 c'8 d'8 || 2/8 e'8 f'8 || 2/8 g'8 a'8 |") assert select(staff)._get_component(Measure, 0) is staff[0] assert select(staff)._get_component(Measure, 1) is staff[1] assert select(staff)._get_component(Measure, 2) is staff[2] def test_selectiontools_Selection__get_component_02(): staff = Staff("abj: | 2/8 c'8 d'8 || 2/8 e'8 f'8 || 2/8 g'8 a'8 |") assert select(staff)._get_component(Measure, -1) is staff[2] assert select(staff)._get_component(Measure, -2) is staff[1] assert select(staff)._get_component(Measure, -3) is staff[0] def test_selectiontools_Selection__get_component_03(): r'''Read forwards for positive n. ''' staff = Staff("abj: | 2/8 c'8 d'8 || 2/8 e'8 f'8 || 2/8 g'8 a'8 |") r''' \new Staff { { \time 2/8 c'8 d'8 } { \time 2/8 e'8 f'8 } { \time 2/8 g'8 a'8 } } ''' assert select(staff)._get_component(scoretools.Leaf, 0) is staff[0][0] assert select(staff)._get_component(scoretools.Leaf, 1) is staff[0][1] assert select(staff)._get_component(scoretools.Leaf, 2) is staff[1][0] assert select(staff)._get_component(scoretools.Leaf, 3) is staff[1][1] assert select(staff)._get_component(scoretools.Leaf, 4) is staff[2][0] assert select(staff)._get_component(scoretools.Leaf, 5) is staff[2][1] def test_selectiontools_Selection__get_component_04(): r'''Read backwards for negative n. ''' staff = Staff("abj: | 2/8 c'8 d'8 || 2/8 e'8 f'8 || 2/8 g'8 a'8 |") r''' \new Staff { { \time 2/8 c'8 d'8 } { \time 2/8 e'8 f'8 } { \time 2/8 g'8 a'8 } } ''' assert select(staff)._get_component(scoretools.Leaf, -1) is staff[2][1] assert select(staff)._get_component(scoretools.Leaf, -2) is staff[2][0] assert select(staff)._get_component(scoretools.Leaf, -3) is staff[1][1] assert select(staff)._get_component(scoretools.Leaf, -4) is staff[1][0] assert select(staff)._get_component(scoretools.Leaf, -5) is staff[0][1] assert select(staff)._get_component(scoretools.Leaf, -6) is staff[0][0] def test_selectiontools_Selection__get_component_05(): staff = Staff(r''' c'16 r16 d'8 r8 e'8. r8. f'4 r4 ''') notes = [staff[0], staff[2], staff[4], staff[6]] rests = [staff[1], staff[3], staff[5], staff[7]] assert select(staff)._get_component(Note, 0) is notes[0] assert select(staff)._get_component(Note, 1) is notes[1] assert select(staff)._get_component(Note, 2) is notes[2] assert select(staff)._get_component(Note, 3) is notes[3] assert select(staff)._get_component(Rest, 0) is rests[0] assert select(staff)._get_component(Rest, 1) is rests[1] assert select(staff)._get_component(Rest, 2) is rests[2] assert select(staff)._get_component(Rest, 3) is rests[3] assert select(staff)._get_component(Staff, 0) is staff def test_selectiontools_Selection__get_component_06(): r'''Iterates backwards with negative values of n. ''' staff = Staff(r''' c'16 r16 d'8 r8 e'8. r8. f'4 r4 ''') notes = [staff[0], staff[2], staff[4], staff[6]] rests = [staff[1], staff[3], staff[5], staff[7]] assert select(staff)._get_component(Note, -1) is notes[3] assert select(staff)._get_component(Note, -2) is notes[2] assert select(staff)._get_component(Note, -3) is notes[1] assert select(staff)._get_component(Note, -4) is notes[0] assert select(staff)._get_component(Rest, -1) is rests[3] assert select(staff)._get_component(Rest, -2) is rests[2] assert select(staff)._get_component(Rest, -3) is rests[1] assert select(staff)._get_component(Rest, -4) is rests[0]
# -*- encoding: utf-8 -*- import pytest from abjad import * def test_indicatortools_Tempo___mul___01(): tempo = Tempo(Duration(1, 4), 60) result = tempo * Duration(1, 2) assert result == Tempo(Duration(1, 4), 30) result = tempo * Duration(2, 3) assert result == Tempo(Duration(1, 4), 40) result = tempo * Duration(3, 4) assert result == Tempo(Duration(1, 4), 45) result = tempo * Duration(4, 5) assert result == Tempo(Duration(1, 4), 48) result = tempo * Duration(5, 6) assert result == Tempo(Duration(1, 4), 50) result = tempo * Duration(6, 7) assert result == Tempo( Duration(1, 4), Duration(360, 7)) def test_indicatortools_Tempo___mul___02(): tempo = Tempo(Duration(1, 4), 60) result = tempo * 1 assert result == Tempo(Duration(1, 4), 60) result = tempo * 2 assert result == Tempo(Duration(1, 4), 120) result = tempo * 3 assert result == Tempo(Duration(1, 4), 180) result = tempo * 4 assert result == Tempo(Duration(1, 4), 240) def test_indicatortools_Tempo___mul___03(): tempo_1 = Tempo(textual_indication='Langsam') pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)") def test_indicatortools_Tempo___mul___04(): tempo_1 = Tempo(Duration(1, 8), (90, 92)) pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)")
mscuthbert/abjad
abjad/tools/indicatortools/test/test_indicatortools_Tempo___mul__.py
abjad/tools/selectiontools/test/test_selectiontools_Selection__get_component.py
# -*- encoding: utf-8 -*- import sys from abjad import * def test_stringtools_strip_diacritics_01(): if sys.version_info[0] == 2: binary_string = 'Dvo\xc5\x99\xc3\xa1k' else: binary_string = 'Dvořák' ascii_string = stringtools.strip_diacritics(binary_string) assert ascii_string == 'Dvorak'
# -*- encoding: utf-8 -*- import pytest from abjad import * def test_indicatortools_Tempo___mul___01(): tempo = Tempo(Duration(1, 4), 60) result = tempo * Duration(1, 2) assert result == Tempo(Duration(1, 4), 30) result = tempo * Duration(2, 3) assert result == Tempo(Duration(1, 4), 40) result = tempo * Duration(3, 4) assert result == Tempo(Duration(1, 4), 45) result = tempo * Duration(4, 5) assert result == Tempo(Duration(1, 4), 48) result = tempo * Duration(5, 6) assert result == Tempo(Duration(1, 4), 50) result = tempo * Duration(6, 7) assert result == Tempo( Duration(1, 4), Duration(360, 7)) def test_indicatortools_Tempo___mul___02(): tempo = Tempo(Duration(1, 4), 60) result = tempo * 1 assert result == Tempo(Duration(1, 4), 60) result = tempo * 2 assert result == Tempo(Duration(1, 4), 120) result = tempo * 3 assert result == Tempo(Duration(1, 4), 180) result = tempo * 4 assert result == Tempo(Duration(1, 4), 240) def test_indicatortools_Tempo___mul___03(): tempo_1 = Tempo(textual_indication='Langsam') pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)") def test_indicatortools_Tempo___mul___04(): tempo_1 = Tempo(Duration(1, 8), (90, 92)) pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)")
mscuthbert/abjad
abjad/tools/indicatortools/test/test_indicatortools_Tempo___mul__.py
abjad/tools/stringtools/test/test_stringtools_strip_diacritics.py
# -*- encoding: utf-8 -*- from abjad.tools import durationtools from abjad.tools import mathtools from abjad.tools import sequencetools from abjad.tools.pitchtools.Segment import Segment from abjad.tools.topleveltools import new class IntervalSegment(Segment): r'''An interval segment. :: >>> intervals = 'm2 M10 -aug4 P5' >>> pitchtools.IntervalSegment(intervals) IntervalSegment(['+m2', '+M10', '-aug4', '+P5']) :: >>> pitch_segment = pitchtools.PitchSegment("c d e f g a b c'") >>> pitchtools.IntervalSegment(pitch_segment) IntervalSegment(['+M2', '+M2', '+m2', '+M2', '+M2', '+M2', '+m2']) ''' ### CLASS VARIABLES ### __slots__ = () ### INITIALIZER ### def __init__( self, items=None, item_class=None, ): from abjad.tools import pitchtools if isinstance(items, pitchtools.PitchSegment): intervals = [] for one, two in sequencetools.iterate_sequence_nwise(items): intervals.append(one - two) items = intervals Segment.__init__( self, items=items, item_class=item_class, ) ### PRIVATE PROPERTIES ### @property def _named_item_class(self): from abjad.tools import pitchtools return pitchtools.NamedInterval @property def _numbered_item_class(self): from abjad.tools import pitchtools return pitchtools.NumberedInterval @property def _parent_item_class(self): from abjad.tools import pitchtools return pitchtools.Interval @property def _repr_specification(self): items = [] if self.item_class.__name__.startswith('Named'): items = [str(x) for x in self] else: items = [x.number for x in self] return new( self._storage_format_specification, is_indented=False, keyword_argument_names=(), positional_argument_values=( items, ), ) ### PUBLIC METHODS ### @classmethod def from_selection( cls, selection, item_class=None, ): r'''Makes interval segment from component `selection`. :: >>> staff = Staff("c'8 d'8 e'8 f'8 g'8 a'8 b'8 c''8") >>> pitchtools.IntervalSegment.from_selection( ... staff, item_class=pitchtools.NumberedInterval) IntervalSegment([2, 2, 1, 2, 2, 2, 1]) Returns interval segment. ''' from abjad.tools import pitchtools pitch_segment = pitchtools.PitchSegment.from_selection(selection) intervals = (-x for x in mathtools.difference_series(pitch_segment)) return cls( items=intervals, item_class=item_class, ) def rotate(self, n): r'''Rotates interval segment by `n`. Returns new interval segment. ''' return new(self, self[-n:] + self[:-n]) ### PUBLIC PROPERTIES ### @property def has_duplicates(self): r'''True if segment has duplicate items. Otherwise false. :: >>> intervals = 'm2 M3 -aug4 m2 P5' >>> segment = pitchtools.IntervalSegment(intervals) >>> segment.has_duplicates True :: >>> intervals = 'M3 -aug4 m2 P5' >>> segment = pitchtools.IntervalSegment(intervals) >>> segment.has_duplicates False Returns boolean. ''' from abjad.tools import pitchtools return len(pitchtools.IntervalSet(self)) < len(self) @property def slope(self): r'''Slope of interval segment. The slope of a interval segment is the sum of its intervals divided by its length: :: >>> pitchtools.IntervalSegment([1, 2]).slope Multiplier(3, 2) Returns multiplier. ''' return durationtools.Multiplier.from_float( sum([x.number for x in self])) / len(self) @property def spread(self): r'''Spread of interval segment. The maximum interval spanned by any combination of the intervals within a numbered interval segment. :: >>> pitchtools.IntervalSegment([1, 2, -3, 1, -2, 1]).spread NumberedInterval(4.0) :: >>> pitchtools.IntervalSegment([1, 1, 1, 2, -3, -2]).spread NumberedInterval(5.0) Returns numbered interval. ''' from abjad.tools import pitchtools current = maximum = minimum = 0 for x in self: current += float(x) if maximum < current: maximum = current if current < minimum: minimum = current return pitchtools.NumberedInterval(maximum - minimum)
# -*- encoding: utf-8 -*- import pytest from abjad import * def test_indicatortools_Tempo___mul___01(): tempo = Tempo(Duration(1, 4), 60) result = tempo * Duration(1, 2) assert result == Tempo(Duration(1, 4), 30) result = tempo * Duration(2, 3) assert result == Tempo(Duration(1, 4), 40) result = tempo * Duration(3, 4) assert result == Tempo(Duration(1, 4), 45) result = tempo * Duration(4, 5) assert result == Tempo(Duration(1, 4), 48) result = tempo * Duration(5, 6) assert result == Tempo(Duration(1, 4), 50) result = tempo * Duration(6, 7) assert result == Tempo( Duration(1, 4), Duration(360, 7)) def test_indicatortools_Tempo___mul___02(): tempo = Tempo(Duration(1, 4), 60) result = tempo * 1 assert result == Tempo(Duration(1, 4), 60) result = tempo * 2 assert result == Tempo(Duration(1, 4), 120) result = tempo * 3 assert result == Tempo(Duration(1, 4), 180) result = tempo * 4 assert result == Tempo(Duration(1, 4), 240) def test_indicatortools_Tempo___mul___03(): tempo_1 = Tempo(textual_indication='Langsam') pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)") def test_indicatortools_Tempo___mul___04(): tempo_1 = Tempo(Duration(1, 8), (90, 92)) pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)")
mscuthbert/abjad
abjad/tools/indicatortools/test/test_indicatortools_Tempo___mul__.py
abjad/tools/pitchtools/IntervalSegment.py
# -*- encoding: utf-8 -*- from abjad import * def test_pitchtools_yield_all_pitch_class_sets_01(): U_star = pitchtools.yield_all_pitch_class_sets() assert len(U_star) == 4096 assert pitchtools.PitchClassSet([0, 1, 2]) in U_star assert pitchtools.PitchClassSet([1, 2, 3]) in U_star assert pitchtools.PitchClassSet([3, 4, 8, 9, 11]) in U_star assert pitchtools.PitchClassSet(range(12)) in U_star
# -*- encoding: utf-8 -*- import pytest from abjad import * def test_indicatortools_Tempo___mul___01(): tempo = Tempo(Duration(1, 4), 60) result = tempo * Duration(1, 2) assert result == Tempo(Duration(1, 4), 30) result = tempo * Duration(2, 3) assert result == Tempo(Duration(1, 4), 40) result = tempo * Duration(3, 4) assert result == Tempo(Duration(1, 4), 45) result = tempo * Duration(4, 5) assert result == Tempo(Duration(1, 4), 48) result = tempo * Duration(5, 6) assert result == Tempo(Duration(1, 4), 50) result = tempo * Duration(6, 7) assert result == Tempo( Duration(1, 4), Duration(360, 7)) def test_indicatortools_Tempo___mul___02(): tempo = Tempo(Duration(1, 4), 60) result = tempo * 1 assert result == Tempo(Duration(1, 4), 60) result = tempo * 2 assert result == Tempo(Duration(1, 4), 120) result = tempo * 3 assert result == Tempo(Duration(1, 4), 180) result = tempo * 4 assert result == Tempo(Duration(1, 4), 240) def test_indicatortools_Tempo___mul___03(): tempo_1 = Tempo(textual_indication='Langsam') pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)") def test_indicatortools_Tempo___mul___04(): tempo_1 = Tempo(Duration(1, 8), (90, 92)) pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)")
mscuthbert/abjad
abjad/tools/indicatortools/test/test_indicatortools_Tempo___mul__.py
abjad/tools/pitchtools/test/test_pitchtools_yield_all_pitch_class_sets.py
# -*- encoding: utf-8 -*- from abjad import * def test_pitchtools_NumberedPitchClass___add___01(): r'''Ascending numbered interval added to pitch-class. ''' pc = pitchtools.NumberedPitchClass(0) MCI = pitchtools.NumberedInterval assert pc + MCI(1) == pitchtools.NumberedPitchClass(1) assert pc + MCI(2) == pitchtools.NumberedPitchClass(2) assert pc + MCI(3) == pitchtools.NumberedPitchClass(3) assert pc + MCI(4) == pitchtools.NumberedPitchClass(4) assert pc + MCI(5) == pitchtools.NumberedPitchClass(5) assert pc + MCI(6) == pitchtools.NumberedPitchClass(6) assert pc + MCI(7) == pitchtools.NumberedPitchClass(7) assert pc + MCI(8) == pitchtools.NumberedPitchClass(8) assert pc + MCI(9) == pitchtools.NumberedPitchClass(9) assert pc + MCI(10) == pitchtools.NumberedPitchClass(10) assert pc + MCI(11) == pitchtools.NumberedPitchClass(11) def test_pitchtools_NumberedPitchClass___add___02(): r'''Ascending numbered interval added to pitch-class. ''' pc = pitchtools.NumberedPitchClass(0) MCI = pitchtools.NumberedInterval assert pc + MCI(12) == pitchtools.NumberedPitchClass(0) assert pc + MCI(13) == pitchtools.NumberedPitchClass(1) assert pc + MCI(14) == pitchtools.NumberedPitchClass(2) assert pc + MCI(15) == pitchtools.NumberedPitchClass(3) assert pc + MCI(16) == pitchtools.NumberedPitchClass(4) assert pc + MCI(17) == pitchtools.NumberedPitchClass(5) assert pc + MCI(18) == pitchtools.NumberedPitchClass(6) assert pc + MCI(19) == pitchtools.NumberedPitchClass(7) assert pc + MCI(20) == pitchtools.NumberedPitchClass(8) assert pc + MCI(21) == pitchtools.NumberedPitchClass(9) assert pc + MCI(22) == pitchtools.NumberedPitchClass(10) assert pc + MCI(23) == pitchtools.NumberedPitchClass(11) def test_pitchtools_NumberedPitchClass___add___03(): r'''Descending numbered interval added to pitch-class. ''' pc = pitchtools.NumberedPitchClass(0) MCI = pitchtools.NumberedInterval assert pc + MCI(-1) == pitchtools.NumberedPitchClass(11) assert pc + MCI(-2) == pitchtools.NumberedPitchClass(10) assert pc + MCI(-3) == pitchtools.NumberedPitchClass(9) assert pc + MCI(-4) == pitchtools.NumberedPitchClass(8) assert pc + MCI(-5) == pitchtools.NumberedPitchClass(7) assert pc + MCI(-6) == pitchtools.NumberedPitchClass(6) assert pc + MCI(-7) == pitchtools.NumberedPitchClass(5) assert pc + MCI(-8) == pitchtools.NumberedPitchClass(4) assert pc + MCI(-9) == pitchtools.NumberedPitchClass(3) assert pc + MCI(-10) == pitchtools.NumberedPitchClass(2) assert pc + MCI(-11) == pitchtools.NumberedPitchClass(1) def test_pitchtools_NumberedPitchClass___add___04(): r'''Descending numbered interval added to pitch-class. ''' pc = pitchtools.NumberedPitchClass(0) MCI = pitchtools.NumberedInterval assert pc + MCI(-12) == pitchtools.NumberedPitchClass(0) assert pc + MCI(-13) == pitchtools.NumberedPitchClass(11) assert pc + MCI(-14) == pitchtools.NumberedPitchClass(10) assert pc + MCI(-15) == pitchtools.NumberedPitchClass(9) assert pc + MCI(-16) == pitchtools.NumberedPitchClass(8) assert pc + MCI(-17) == pitchtools.NumberedPitchClass(7) assert pc + MCI(-18) == pitchtools.NumberedPitchClass(6) assert pc + MCI(-19) == pitchtools.NumberedPitchClass(5) assert pc + MCI(-20) == pitchtools.NumberedPitchClass(4) assert pc + MCI(-21) == pitchtools.NumberedPitchClass(3) assert pc + MCI(-22) == pitchtools.NumberedPitchClass(2) assert pc + MCI(-23) == pitchtools.NumberedPitchClass(1) def test_pitchtools_NumberedPitchClass___add___05(): r'''numbered unison added to pitch-class. ''' pc = pitchtools.NumberedPitchClass(0) MCI = pitchtools.NumberedInterval assert pc + MCI(0) == pitchtools.NumberedPitchClass(0)
# -*- encoding: utf-8 -*- import pytest from abjad import * def test_indicatortools_Tempo___mul___01(): tempo = Tempo(Duration(1, 4), 60) result = tempo * Duration(1, 2) assert result == Tempo(Duration(1, 4), 30) result = tempo * Duration(2, 3) assert result == Tempo(Duration(1, 4), 40) result = tempo * Duration(3, 4) assert result == Tempo(Duration(1, 4), 45) result = tempo * Duration(4, 5) assert result == Tempo(Duration(1, 4), 48) result = tempo * Duration(5, 6) assert result == Tempo(Duration(1, 4), 50) result = tempo * Duration(6, 7) assert result == Tempo( Duration(1, 4), Duration(360, 7)) def test_indicatortools_Tempo___mul___02(): tempo = Tempo(Duration(1, 4), 60) result = tempo * 1 assert result == Tempo(Duration(1, 4), 60) result = tempo * 2 assert result == Tempo(Duration(1, 4), 120) result = tempo * 3 assert result == Tempo(Duration(1, 4), 180) result = tempo * 4 assert result == Tempo(Duration(1, 4), 240) def test_indicatortools_Tempo___mul___03(): tempo_1 = Tempo(textual_indication='Langsam') pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)") def test_indicatortools_Tempo___mul___04(): tempo_1 = Tempo(Duration(1, 8), (90, 92)) pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)")
mscuthbert/abjad
abjad/tools/indicatortools/test/test_indicatortools_Tempo___mul__.py
abjad/tools/pitchtools/test/test_pitchtools_NumberedPitchClass___add__.py
# -*- encoding: utf-8 -*- from abjad import * def test_schemetools_Scheme_format_scheme_value_01(): assert schemetools.Scheme.format_scheme_value(1) == '1' assert schemetools.Scheme.format_scheme_value(True) == '#t' assert schemetools.Scheme.format_scheme_value(False) == '#f' assert schemetools.Scheme.format_scheme_value('foo bar') == '"foo bar"' assert schemetools.Scheme.format_scheme_value('baz') == 'baz' assert schemetools.Scheme.format_scheme_value([1, 2, 3]) == '(1 2 3)'
# -*- encoding: utf-8 -*- import pytest from abjad import * def test_indicatortools_Tempo___mul___01(): tempo = Tempo(Duration(1, 4), 60) result = tempo * Duration(1, 2) assert result == Tempo(Duration(1, 4), 30) result = tempo * Duration(2, 3) assert result == Tempo(Duration(1, 4), 40) result = tempo * Duration(3, 4) assert result == Tempo(Duration(1, 4), 45) result = tempo * Duration(4, 5) assert result == Tempo(Duration(1, 4), 48) result = tempo * Duration(5, 6) assert result == Tempo(Duration(1, 4), 50) result = tempo * Duration(6, 7) assert result == Tempo( Duration(1, 4), Duration(360, 7)) def test_indicatortools_Tempo___mul___02(): tempo = Tempo(Duration(1, 4), 60) result = tempo * 1 assert result == Tempo(Duration(1, 4), 60) result = tempo * 2 assert result == Tempo(Duration(1, 4), 120) result = tempo * 3 assert result == Tempo(Duration(1, 4), 180) result = tempo * 4 assert result == Tempo(Duration(1, 4), 240) def test_indicatortools_Tempo___mul___03(): tempo_1 = Tempo(textual_indication='Langsam') pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)") def test_indicatortools_Tempo___mul___04(): tempo_1 = Tempo(Duration(1, 8), (90, 92)) pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)")
mscuthbert/abjad
abjad/tools/indicatortools/test/test_indicatortools_Tempo___mul__.py
abjad/tools/schemetools/test/test_schemetools_Scheme_format_scheme_value.py
# -*- encoding: utf-8 -*- import abc from abjad.tools.abctools.AbjadObject import AbjadObject class TypedCollection(AbjadObject): r'''Abstract base class for typed collections. ''' ### CLASS VARIABLES ### __slots__ = ( '_collection', '_item_class', ) ### INITIALIZER ### @abc.abstractmethod def __init__(self, items=None, item_class=None): assert isinstance(item_class, (type(None), type)) self._item_class = item_class ### SPECIAL METHODS ### def __contains__(self, item): r'''Is true when typed collection container `item`. Otherwise false. Returns boolean. ''' try: item = self._item_coercer(item) except ValueError: return False return self._collection.__contains__(item) def __eq__(self, expr): r'''Is true when `expr` is a typed collection with items that compare equal to those of this typed collection. Otherwise false. Returns boolean. ''' if isinstance(expr, type(self)): return self._collection == expr._collection elif isinstance(expr, type(self._collection)): return self._collection == expr return False def __format__(self, format_specification=''): r'''Formats typed collection. Set `format_specification` to `''` or `'storage'`. Interprets `''` equal to `'storage'`. Returns string. ''' from abjad.tools import systemtools if format_specification in ('', 'storage'): return systemtools.StorageFormatManager.get_storage_format(self) return str(self) def __getnewargs__(self): r'''Gets new arguments. Returns tuple. ''' return (self._collection, self.item_class) def __hash__(self): r'''Hashes typed collection. Required to be explicitly re-defined on Python 3 if __eq__ changes. Returns integer. ''' return super(TypedCollection, self).__hash__() def __iter__(self): r'''Iterates typed collection. Returns generator. ''' return self._collection.__iter__() def __len__(self): r'''Length of typed collection. Returns nonnegative integer. ''' return len(self._collection) def __ne__(self, expr): r'''Is true when `expr` is not a typed collection with items equal to this typed collection. Otherwise false. Returns boolean. ''' return not self.__eq__(expr) ### PRIVATE METHODS ### def _on_insertion(self, item): r'''Override to operate on item after insertion into collection. ''' pass def _on_removal(self, item): r'''Override to operate on item after removal from collection. ''' pass ### PRIVATE PROPERTIES ### @property def _item_coercer(self): def coerce_(x): if isinstance(x, self._item_class): return x return self._item_class(x) if self._item_class is None: return lambda x: x return coerce_ @property def _repr_specification(self): from abjad.tools import systemtools manager = systemtools.StorageFormatManager names = manager.get_signature_keyword_argument_names(self) keyword_argument_names = list(names) if 'items' in keyword_argument_names: keyword_argument_names.remove('items') keyword_argument_names = tuple(keyword_argument_names) positional_argument_values = ( self._collection, ) return systemtools.StorageFormatSpecification( self, is_indented=False, keyword_argument_names=keyword_argument_names, positional_argument_values=positional_argument_values, ) @property def _storage_format_specification(self): from abjad.tools import systemtools manager = systemtools.StorageFormatManager names = manager.get_signature_keyword_argument_names(self) keyword_argument_names = list(names) if 'items' in keyword_argument_names: keyword_argument_names.remove('items') keyword_argument_names = tuple(keyword_argument_names) positional_argument_values = ( self._collection, ) return systemtools.StorageFormatSpecification( self, keyword_argument_names=keyword_argument_names, positional_argument_values=positional_argument_values, ) ### PUBLIC PROPERTIES ### @property def item_class(self): r'''Item class to coerce items into. ''' return self._item_class @property def items(self): r'''Gets collection items. ''' return [x for x in self]
# -*- encoding: utf-8 -*- import pytest from abjad import * def test_indicatortools_Tempo___mul___01(): tempo = Tempo(Duration(1, 4), 60) result = tempo * Duration(1, 2) assert result == Tempo(Duration(1, 4), 30) result = tempo * Duration(2, 3) assert result == Tempo(Duration(1, 4), 40) result = tempo * Duration(3, 4) assert result == Tempo(Duration(1, 4), 45) result = tempo * Duration(4, 5) assert result == Tempo(Duration(1, 4), 48) result = tempo * Duration(5, 6) assert result == Tempo(Duration(1, 4), 50) result = tempo * Duration(6, 7) assert result == Tempo( Duration(1, 4), Duration(360, 7)) def test_indicatortools_Tempo___mul___02(): tempo = Tempo(Duration(1, 4), 60) result = tempo * 1 assert result == Tempo(Duration(1, 4), 60) result = tempo * 2 assert result == Tempo(Duration(1, 4), 120) result = tempo * 3 assert result == Tempo(Duration(1, 4), 180) result = tempo * 4 assert result == Tempo(Duration(1, 4), 240) def test_indicatortools_Tempo___mul___03(): tempo_1 = Tempo(textual_indication='Langsam') pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)") def test_indicatortools_Tempo___mul___04(): tempo_1 = Tempo(Duration(1, 8), (90, 92)) pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)")
mscuthbert/abjad
abjad/tools/indicatortools/test/test_indicatortools_Tempo___mul__.py
abjad/tools/datastructuretools/TypedCollection.py
# -*- encoding: utf-8 -*- def timespan_2_overlaps_all_of_timespan_1( timespan_1=None, timespan_2=None, hold=False, ): r'''Makes time relation indicating that `timespan_2` overlaps all of `timespan_1`. :: >>> relation = timespantools.timespan_2_overlaps_all_of_timespan_1() >>> print(format(relation)) timespantools.TimespanTimespanTimeRelation( inequality=timespantools.CompoundInequality( [ timespantools.SimpleInequality('timespan_2.start_offset < timespan_1.start_offset'), timespantools.SimpleInequality('timespan_1.stop_offset < timespan_2.stop_offset'), ], logical_operator='and', ), ) Returns time relation or boolean. ''' from abjad.tools import timespantools inequality = timespantools.CompoundInequality([ 'timespan_2.start_offset < timespan_1.start_offset', 'timespan_1.stop_offset < timespan_2.stop_offset', ]) time_relation = timespantools.TimespanTimespanTimeRelation( inequality, timespan_1=timespan_1, timespan_2=timespan_2, ) if time_relation.is_fully_loaded and not hold: return time_relation() else: return time_relation
# -*- encoding: utf-8 -*- import pytest from abjad import * def test_indicatortools_Tempo___mul___01(): tempo = Tempo(Duration(1, 4), 60) result = tempo * Duration(1, 2) assert result == Tempo(Duration(1, 4), 30) result = tempo * Duration(2, 3) assert result == Tempo(Duration(1, 4), 40) result = tempo * Duration(3, 4) assert result == Tempo(Duration(1, 4), 45) result = tempo * Duration(4, 5) assert result == Tempo(Duration(1, 4), 48) result = tempo * Duration(5, 6) assert result == Tempo(Duration(1, 4), 50) result = tempo * Duration(6, 7) assert result == Tempo( Duration(1, 4), Duration(360, 7)) def test_indicatortools_Tempo___mul___02(): tempo = Tempo(Duration(1, 4), 60) result = tempo * 1 assert result == Tempo(Duration(1, 4), 60) result = tempo * 2 assert result == Tempo(Duration(1, 4), 120) result = tempo * 3 assert result == Tempo(Duration(1, 4), 180) result = tempo * 4 assert result == Tempo(Duration(1, 4), 240) def test_indicatortools_Tempo___mul___03(): tempo_1 = Tempo(textual_indication='Langsam') pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)") def test_indicatortools_Tempo___mul___04(): tempo_1 = Tempo(Duration(1, 8), (90, 92)) pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)")
mscuthbert/abjad
abjad/tools/indicatortools/test/test_indicatortools_Tempo___mul__.py
abjad/tools/timespantools/timespan_2_overlaps_all_of_timespan_1.py
# -*- encoding: utf-8 -*- from abjad import * def test_pitchtools_PitchClassSet_multiply_01(): assert pitchtools.PitchClassSet([0, 1, 5]).multiply(5) == \ pitchtools.PitchClassSet([0, 1, 5]) assert pitchtools.PitchClassSet([1, 2, 6]).multiply(5) == \ pitchtools.PitchClassSet([5, 6, 10]) assert pitchtools.PitchClassSet([2, 3, 7]).multiply(5) == \ pitchtools.PitchClassSet([3, 10, 11])
# -*- encoding: utf-8 -*- import pytest from abjad import * def test_indicatortools_Tempo___mul___01(): tempo = Tempo(Duration(1, 4), 60) result = tempo * Duration(1, 2) assert result == Tempo(Duration(1, 4), 30) result = tempo * Duration(2, 3) assert result == Tempo(Duration(1, 4), 40) result = tempo * Duration(3, 4) assert result == Tempo(Duration(1, 4), 45) result = tempo * Duration(4, 5) assert result == Tempo(Duration(1, 4), 48) result = tempo * Duration(5, 6) assert result == Tempo(Duration(1, 4), 50) result = tempo * Duration(6, 7) assert result == Tempo( Duration(1, 4), Duration(360, 7)) def test_indicatortools_Tempo___mul___02(): tempo = Tempo(Duration(1, 4), 60) result = tempo * 1 assert result == Tempo(Duration(1, 4), 60) result = tempo * 2 assert result == Tempo(Duration(1, 4), 120) result = tempo * 3 assert result == Tempo(Duration(1, 4), 180) result = tempo * 4 assert result == Tempo(Duration(1, 4), 240) def test_indicatortools_Tempo___mul___03(): tempo_1 = Tempo(textual_indication='Langsam') pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)") def test_indicatortools_Tempo___mul___04(): tempo_1 = Tempo(Duration(1, 8), (90, 92)) pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)")
mscuthbert/abjad
abjad/tools/indicatortools/test/test_indicatortools_Tempo___mul__.py
abjad/tools/pitchtools/test/test_pitchtools_PitchClassSet_multiply.py
# -*- encoding: utf-8 -*- from abjad import * def test_scoretools_Container_index_01(): r'''Elements that compare equal return different indices in container. ''' container = Container(4 * Note("c'4")) assert container.index(container[0]) == 0 assert container.index(container[1]) == 1 assert container.index(container[2]) == 2 assert container.index(container[3]) == 3
# -*- encoding: utf-8 -*- import pytest from abjad import * def test_indicatortools_Tempo___mul___01(): tempo = Tempo(Duration(1, 4), 60) result = tempo * Duration(1, 2) assert result == Tempo(Duration(1, 4), 30) result = tempo * Duration(2, 3) assert result == Tempo(Duration(1, 4), 40) result = tempo * Duration(3, 4) assert result == Tempo(Duration(1, 4), 45) result = tempo * Duration(4, 5) assert result == Tempo(Duration(1, 4), 48) result = tempo * Duration(5, 6) assert result == Tempo(Duration(1, 4), 50) result = tempo * Duration(6, 7) assert result == Tempo( Duration(1, 4), Duration(360, 7)) def test_indicatortools_Tempo___mul___02(): tempo = Tempo(Duration(1, 4), 60) result = tempo * 1 assert result == Tempo(Duration(1, 4), 60) result = tempo * 2 assert result == Tempo(Duration(1, 4), 120) result = tempo * 3 assert result == Tempo(Duration(1, 4), 180) result = tempo * 4 assert result == Tempo(Duration(1, 4), 240) def test_indicatortools_Tempo___mul___03(): tempo_1 = Tempo(textual_indication='Langsam') pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)") def test_indicatortools_Tempo___mul___04(): tempo_1 = Tempo(Duration(1, 8), (90, 92)) pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)")
mscuthbert/abjad
abjad/tools/indicatortools/test/test_indicatortools_Tempo___mul__.py
abjad/tools/scoretools/test/test_scoretools_Container_index.py
# -*- encoding: utf-8 -*- from abjad import * def test_pitchtools_list_pitch_numbers_in_expr_01(): tuplet = scoretools.FixedDurationTuplet(Duration(2, 8), "c'8 d'8 e'8") assert pitchtools.list_pitch_numbers_in_expr(tuplet) == (0, 2, 4) def test_pitchtools_list_pitch_numbers_in_expr_02(): staff = Staff("c'8 d'8 e'8 f'8") assert pitchtools.list_pitch_numbers_in_expr(staff) == (0, 2, 4, 5)
# -*- encoding: utf-8 -*- import pytest from abjad import * def test_indicatortools_Tempo___mul___01(): tempo = Tempo(Duration(1, 4), 60) result = tempo * Duration(1, 2) assert result == Tempo(Duration(1, 4), 30) result = tempo * Duration(2, 3) assert result == Tempo(Duration(1, 4), 40) result = tempo * Duration(3, 4) assert result == Tempo(Duration(1, 4), 45) result = tempo * Duration(4, 5) assert result == Tempo(Duration(1, 4), 48) result = tempo * Duration(5, 6) assert result == Tempo(Duration(1, 4), 50) result = tempo * Duration(6, 7) assert result == Tempo( Duration(1, 4), Duration(360, 7)) def test_indicatortools_Tempo___mul___02(): tempo = Tempo(Duration(1, 4), 60) result = tempo * 1 assert result == Tempo(Duration(1, 4), 60) result = tempo * 2 assert result == Tempo(Duration(1, 4), 120) result = tempo * 3 assert result == Tempo(Duration(1, 4), 180) result = tempo * 4 assert result == Tempo(Duration(1, 4), 240) def test_indicatortools_Tempo___mul___03(): tempo_1 = Tempo(textual_indication='Langsam') pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)") def test_indicatortools_Tempo___mul___04(): tempo_1 = Tempo(Duration(1, 8), (90, 92)) pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)")
mscuthbert/abjad
abjad/tools/indicatortools/test/test_indicatortools_Tempo___mul__.py
abjad/tools/pitchtools/test/test_pitchtools_list_pitch_numbers_in_expr.py
# -*- encoding: utf-8 -*- from abjad import * def test_rhythmtreetools_RhythmTreeContainer_insert_01(): leaf_a = rhythmtreetools.RhythmTreeLeaf(preprolated_duration=3) leaf_b = rhythmtreetools.RhythmTreeLeaf(preprolated_duration=3) leaf_c = rhythmtreetools.RhythmTreeLeaf(preprolated_duration=2) container = rhythmtreetools.RhythmTreeContainer() assert container.children == () container.insert(0, leaf_a) assert container.children == (leaf_a,) container.insert(0, leaf_b) assert container.children == (leaf_b, leaf_a) container.insert(1, leaf_c) assert container.children == (leaf_b, leaf_c, leaf_a)
# -*- encoding: utf-8 -*- import pytest from abjad import * def test_indicatortools_Tempo___mul___01(): tempo = Tempo(Duration(1, 4), 60) result = tempo * Duration(1, 2) assert result == Tempo(Duration(1, 4), 30) result = tempo * Duration(2, 3) assert result == Tempo(Duration(1, 4), 40) result = tempo * Duration(3, 4) assert result == Tempo(Duration(1, 4), 45) result = tempo * Duration(4, 5) assert result == Tempo(Duration(1, 4), 48) result = tempo * Duration(5, 6) assert result == Tempo(Duration(1, 4), 50) result = tempo * Duration(6, 7) assert result == Tempo( Duration(1, 4), Duration(360, 7)) def test_indicatortools_Tempo___mul___02(): tempo = Tempo(Duration(1, 4), 60) result = tempo * 1 assert result == Tempo(Duration(1, 4), 60) result = tempo * 2 assert result == Tempo(Duration(1, 4), 120) result = tempo * 3 assert result == Tempo(Duration(1, 4), 180) result = tempo * 4 assert result == Tempo(Duration(1, 4), 240) def test_indicatortools_Tempo___mul___03(): tempo_1 = Tempo(textual_indication='Langsam') pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)") def test_indicatortools_Tempo___mul___04(): tempo_1 = Tempo(Duration(1, 8), (90, 92)) pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)")
mscuthbert/abjad
abjad/tools/indicatortools/test/test_indicatortools_Tempo___mul__.py
abjad/tools/rhythmtreetools/test/test_rhythmtreetools_RhythmTreeContainer_insert.py
# -*- encoding: utf-8 -*- import six from abjad.tools.stringtools.strip_diacritics import strip_diacritics def to_accent_free_snake_case(string): '''Changes `string` to accent-free snake case. .. container:: example :: >>> stringtools.to_accent_free_snake_case('Déja vu') 'deja_vu' Strips accents from accented characters. Changes all punctuation (including spaces) to underscore. Sets to lowercase. Returns string. ''' assert isinstance(string, six.string_types) result = strip_diacritics(string) result = result.replace(' ', '_') result = result.replace("'", '_') result = result.lower() return result
# -*- encoding: utf-8 -*- import pytest from abjad import * def test_indicatortools_Tempo___mul___01(): tempo = Tempo(Duration(1, 4), 60) result = tempo * Duration(1, 2) assert result == Tempo(Duration(1, 4), 30) result = tempo * Duration(2, 3) assert result == Tempo(Duration(1, 4), 40) result = tempo * Duration(3, 4) assert result == Tempo(Duration(1, 4), 45) result = tempo * Duration(4, 5) assert result == Tempo(Duration(1, 4), 48) result = tempo * Duration(5, 6) assert result == Tempo(Duration(1, 4), 50) result = tempo * Duration(6, 7) assert result == Tempo( Duration(1, 4), Duration(360, 7)) def test_indicatortools_Tempo___mul___02(): tempo = Tempo(Duration(1, 4), 60) result = tempo * 1 assert result == Tempo(Duration(1, 4), 60) result = tempo * 2 assert result == Tempo(Duration(1, 4), 120) result = tempo * 3 assert result == Tempo(Duration(1, 4), 180) result = tempo * 4 assert result == Tempo(Duration(1, 4), 240) def test_indicatortools_Tempo___mul___03(): tempo_1 = Tempo(textual_indication='Langsam') pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)") def test_indicatortools_Tempo___mul___04(): tempo_1 = Tempo(Duration(1, 8), (90, 92)) pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)")
mscuthbert/abjad
abjad/tools/indicatortools/test/test_indicatortools_Tempo___mul__.py
abjad/tools/stringtools/to_accent_free_snake_case.py
# -*- encoding: utf-8 -*- import copy from abjad import * def test_pitchtools_NamedPitch___copy___01(): pitch = NamedPitch(13) new = copy.copy(pitch) assert new is not pitch assert new.accidental is not pitch.accidental
# -*- encoding: utf-8 -*- import pytest from abjad import * def test_indicatortools_Tempo___mul___01(): tempo = Tempo(Duration(1, 4), 60) result = tempo * Duration(1, 2) assert result == Tempo(Duration(1, 4), 30) result = tempo * Duration(2, 3) assert result == Tempo(Duration(1, 4), 40) result = tempo * Duration(3, 4) assert result == Tempo(Duration(1, 4), 45) result = tempo * Duration(4, 5) assert result == Tempo(Duration(1, 4), 48) result = tempo * Duration(5, 6) assert result == Tempo(Duration(1, 4), 50) result = tempo * Duration(6, 7) assert result == Tempo( Duration(1, 4), Duration(360, 7)) def test_indicatortools_Tempo___mul___02(): tempo = Tempo(Duration(1, 4), 60) result = tempo * 1 assert result == Tempo(Duration(1, 4), 60) result = tempo * 2 assert result == Tempo(Duration(1, 4), 120) result = tempo * 3 assert result == Tempo(Duration(1, 4), 180) result = tempo * 4 assert result == Tempo(Duration(1, 4), 240) def test_indicatortools_Tempo___mul___03(): tempo_1 = Tempo(textual_indication='Langsam') pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)") def test_indicatortools_Tempo___mul___04(): tempo_1 = Tempo(Duration(1, 8), (90, 92)) pytest.raises(ImpreciseTempoError, "tempo_1 * Duration(1, 2)")
mscuthbert/abjad
abjad/tools/indicatortools/test/test_indicatortools_Tempo___mul__.py
abjad/tools/pitchtools/test/test_pitchtools_NamedPitch___copy__.py
"""Interfaces with TotalConnect sensors.""" import logging from homeassistant.components.binary_sensor import ( DEVICE_CLASS_DOOR, DEVICE_CLASS_GAS, DEVICE_CLASS_SMOKE, BinarySensorEntity, ) from .const import DOMAIN _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass, entry, async_add_entities) -> None: """Set up TotalConnect device sensors based on a config entry.""" sensors = [] client_locations = hass.data[DOMAIN][entry.entry_id].locations for location_id, location in client_locations.items(): for zone_id, zone in location.zones.items(): sensors.append(TotalConnectBinarySensor(zone_id, location_id, zone)) async_add_entities(sensors, True) class TotalConnectBinarySensor(BinarySensorEntity): """Represent an TotalConnect zone.""" def __init__(self, zone_id, location_id, zone): """Initialize the TotalConnect status.""" self._zone_id = zone_id self._location_id = location_id self._zone = zone self._name = self._zone.description self._unique_id = f"{location_id} {zone_id}" self._is_on = None self._is_tampered = None self._is_low_battery = None @property def unique_id(self): """Return the unique id.""" return self._unique_id @property def name(self): """Return the name of the device.""" return self._name def update(self): """Return the state of the device.""" self._is_tampered = self._zone.is_tampered() self._is_low_battery = self._zone.is_low_battery() if self._zone.is_faulted() or self._zone.is_triggered(): self._is_on = True else: self._is_on = False @property def is_on(self): """Return true if the binary sensor is on.""" return self._is_on @property def device_class(self): """Return the class of this device, from component DEVICE_CLASSES.""" if self._zone.is_type_security(): return DEVICE_CLASS_DOOR if self._zone.is_type_fire(): return DEVICE_CLASS_SMOKE if self._zone.is_type_carbon_monoxide(): return DEVICE_CLASS_GAS return None @property def device_state_attributes(self): """Return the state attributes.""" attributes = { "zone_id": self._zone_id, "location_id": self._location_id, "low_battery": self._is_low_battery, "tampered": self._is_tampered, } return attributes
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/totalconnect/binary_sensor.py
"""Device tracker for BMW Connected Drive vehicles.""" import logging from homeassistant.util import slugify from . import DOMAIN as BMW_DOMAIN _LOGGER = logging.getLogger(__name__) def setup_scanner(hass, config, see, discovery_info=None): """Set up the BMW tracker.""" accounts = hass.data[BMW_DOMAIN] _LOGGER.debug("Found BMW accounts: %s", ", ".join([a.name for a in accounts])) for account in accounts: for vehicle in account.account.vehicles: tracker = BMWDeviceTracker(see, vehicle) account.add_update_listener(tracker.update) tracker.update() return True class BMWDeviceTracker: """BMW Connected Drive device tracker.""" def __init__(self, see, vehicle): """Initialize the Tracker.""" self._see = see self.vehicle = vehicle def update(self) -> None: """Update the device info. Only update the state in Home Assistant if tracking in the car is enabled. """ dev_id = slugify(self.vehicle.name) if not self.vehicle.state.is_vehicle_tracking_enabled: _LOGGER.debug("Tracking is disabled for vehicle %s", dev_id) return _LOGGER.debug("Updating %s", dev_id) attrs = {"vin": self.vehicle.vin} self._see( dev_id=dev_id, host_name=self.vehicle.name, gps=self.vehicle.state.gps_position, attributes=attrs, icon="mdi:car", )
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/bmw_connected_drive/device_tracker.py
"""Support for HomematicIP Cloud binary sensor.""" import logging from typing import Any, Dict from homematicip.aio.device import ( AsyncAccelerationSensor, AsyncContactInterface, AsyncDevice, AsyncFullFlushContactInterface, AsyncMotionDetectorIndoor, AsyncMotionDetectorOutdoor, AsyncMotionDetectorPushButton, AsyncPluggableMainsFailureSurveillance, AsyncPresenceDetectorIndoor, AsyncRotaryHandleSensor, AsyncShutterContact, AsyncShutterContactMagnetic, AsyncSmokeDetector, AsyncTiltVibrationSensor, AsyncWaterSensor, AsyncWeatherSensor, AsyncWeatherSensorPlus, AsyncWeatherSensorPro, ) from homematicip.aio.group import AsyncSecurityGroup, AsyncSecurityZoneGroup from homematicip.base.enums import SmokeDetectorAlarmType, WindowState from homeassistant.components.binary_sensor import ( DEVICE_CLASS_BATTERY, DEVICE_CLASS_DOOR, DEVICE_CLASS_LIGHT, DEVICE_CLASS_MOISTURE, DEVICE_CLASS_MOTION, DEVICE_CLASS_MOVING, DEVICE_CLASS_OPENING, DEVICE_CLASS_POWER, DEVICE_CLASS_PRESENCE, DEVICE_CLASS_SAFETY, DEVICE_CLASS_SMOKE, BinarySensorEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.helpers.typing import HomeAssistantType from . import DOMAIN as HMIPC_DOMAIN, HomematicipGenericEntity from .hap import HomematicipHAP _LOGGER = logging.getLogger(__name__) ATTR_ACCELERATION_SENSOR_MODE = "acceleration_sensor_mode" ATTR_ACCELERATION_SENSOR_NEUTRAL_POSITION = "acceleration_sensor_neutral_position" ATTR_ACCELERATION_SENSOR_SENSITIVITY = "acceleration_sensor_sensitivity" ATTR_ACCELERATION_SENSOR_TRIGGER_ANGLE = "acceleration_sensor_trigger_angle" ATTR_INTRUSION_ALARM = "intrusion_alarm" ATTR_MOISTURE_DETECTED = "moisture_detected" ATTR_MOTION_DETECTED = "motion_detected" ATTR_POWER_MAINS_FAILURE = "power_mains_failure" ATTR_PRESENCE_DETECTED = "presence_detected" ATTR_SMOKE_DETECTOR_ALARM = "smoke_detector_alarm" ATTR_TODAY_SUNSHINE_DURATION = "today_sunshine_duration_in_minutes" ATTR_WATER_LEVEL_DETECTED = "water_level_detected" ATTR_WINDOW_STATE = "window_state" GROUP_ATTRIBUTES = { "moistureDetected": ATTR_MOISTURE_DETECTED, "motionDetected": ATTR_MOTION_DETECTED, "powerMainsFailure": ATTR_POWER_MAINS_FAILURE, "presenceDetected": ATTR_PRESENCE_DETECTED, "waterlevelDetected": ATTR_WATER_LEVEL_DETECTED, } SAM_DEVICE_ATTRIBUTES = { "accelerationSensorNeutralPosition": ATTR_ACCELERATION_SENSOR_NEUTRAL_POSITION, "accelerationSensorMode": ATTR_ACCELERATION_SENSOR_MODE, "accelerationSensorSensitivity": ATTR_ACCELERATION_SENSOR_SENSITIVITY, "accelerationSensorTriggerAngle": ATTR_ACCELERATION_SENSOR_TRIGGER_ANGLE, } async def async_setup_entry( hass: HomeAssistantType, config_entry: ConfigEntry, async_add_entities ) -> None: """Set up the HomematicIP Cloud binary sensor from a config entry.""" hap = hass.data[HMIPC_DOMAIN][config_entry.unique_id] entities = [] for device in hap.home.devices: if isinstance(device, AsyncAccelerationSensor): entities.append(HomematicipAccelerationSensor(hap, device)) if isinstance(device, AsyncTiltVibrationSensor): entities.append(HomematicipTiltVibrationSensor(hap, device)) if isinstance(device, (AsyncContactInterface, AsyncFullFlushContactInterface)): entities.append(HomematicipContactInterface(hap, device)) if isinstance( device, (AsyncShutterContact, AsyncShutterContactMagnetic), ): entities.append(HomematicipShutterContact(hap, device)) if isinstance(device, AsyncRotaryHandleSensor): entities.append(HomematicipShutterContact(hap, device, True)) if isinstance( device, ( AsyncMotionDetectorIndoor, AsyncMotionDetectorOutdoor, AsyncMotionDetectorPushButton, ), ): entities.append(HomematicipMotionDetector(hap, device)) if isinstance(device, AsyncPluggableMainsFailureSurveillance): entities.append( HomematicipPluggableMainsFailureSurveillanceSensor(hap, device) ) if isinstance(device, AsyncPresenceDetectorIndoor): entities.append(HomematicipPresenceDetector(hap, device)) if isinstance(device, AsyncSmokeDetector): entities.append(HomematicipSmokeDetector(hap, device)) if isinstance(device, AsyncWaterSensor): entities.append(HomematicipWaterDetector(hap, device)) if isinstance(device, (AsyncWeatherSensorPlus, AsyncWeatherSensorPro)): entities.append(HomematicipRainSensor(hap, device)) if isinstance( device, (AsyncWeatherSensor, AsyncWeatherSensorPlus, AsyncWeatherSensorPro) ): entities.append(HomematicipStormSensor(hap, device)) entities.append(HomematicipSunshineSensor(hap, device)) if isinstance(device, AsyncDevice) and device.lowBat is not None: entities.append(HomematicipBatterySensor(hap, device)) for group in hap.home.groups: if isinstance(group, AsyncSecurityGroup): entities.append(HomematicipSecuritySensorGroup(hap, group)) elif isinstance(group, AsyncSecurityZoneGroup): entities.append(HomematicipSecurityZoneSensorGroup(hap, group)) if entities: async_add_entities(entities) class HomematicipBaseActionSensor(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP base action sensor.""" @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_MOVING @property def is_on(self) -> bool: """Return true if acceleration is detected.""" return self._device.accelerationSensorTriggered @property def device_state_attributes(self) -> Dict[str, Any]: """Return the state attributes of the acceleration sensor.""" state_attr = super().device_state_attributes for attr, attr_key in SAM_DEVICE_ATTRIBUTES.items(): attr_value = getattr(self._device, attr, None) if attr_value: state_attr[attr_key] = attr_value return state_attr class HomematicipAccelerationSensor(HomematicipBaseActionSensor): """Representation of the HomematicIP acceleration sensor.""" class HomematicipTiltVibrationSensor(HomematicipBaseActionSensor): """Representation of the HomematicIP tilt vibration sensor.""" class HomematicipContactInterface(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP contact interface.""" @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_OPENING @property def is_on(self) -> bool: """Return true if the contact interface is on/open.""" if self._device.windowState is None: return None return self._device.windowState != WindowState.CLOSED class HomematicipShutterContact(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP shutter contact.""" def __init__( self, hap: HomematicipHAP, device, has_additional_state: bool = False ) -> None: """Initialize the shutter contact.""" super().__init__(hap, device) self.has_additional_state = has_additional_state @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_DOOR @property def is_on(self) -> bool: """Return true if the shutter contact is on/open.""" if self._device.windowState is None: return None return self._device.windowState != WindowState.CLOSED @property def device_state_attributes(self) -> Dict[str, Any]: """Return the state attributes of the Shutter Contact.""" state_attr = super().device_state_attributes if self.has_additional_state: window_state = getattr(self._device, "windowState", None) if window_state and window_state != WindowState.CLOSED: state_attr[ATTR_WINDOW_STATE] = window_state return state_attr class HomematicipMotionDetector(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP motion detector.""" @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_MOTION @property def is_on(self) -> bool: """Return true if motion is detected.""" return self._device.motionDetected class HomematicipPresenceDetector(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP presence detector.""" @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_PRESENCE @property def is_on(self) -> bool: """Return true if presence is detected.""" return self._device.presenceDetected class HomematicipSmokeDetector(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP smoke detector.""" @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_SMOKE @property def is_on(self) -> bool: """Return true if smoke is detected.""" if self._device.smokeDetectorAlarmType: return ( self._device.smokeDetectorAlarmType == SmokeDetectorAlarmType.PRIMARY_ALARM ) return False class HomematicipWaterDetector(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP water detector.""" @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_MOISTURE @property def is_on(self) -> bool: """Return true, if moisture or waterlevel is detected.""" return self._device.moistureDetected or self._device.waterlevelDetected class HomematicipStormSensor(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP storm sensor.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize storm sensor.""" super().__init__(hap, device, "Storm") @property def icon(self) -> str: """Return the icon.""" return "mdi:weather-windy" if self.is_on else "mdi:pinwheel-outline" @property def is_on(self) -> bool: """Return true, if storm is detected.""" return self._device.storm class HomematicipRainSensor(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP rain sensor.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize rain sensor.""" super().__init__(hap, device, "Raining") @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_MOISTURE @property def is_on(self) -> bool: """Return true, if it is raining.""" return self._device.raining class HomematicipSunshineSensor(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP sunshine sensor.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize sunshine sensor.""" super().__init__(hap, device, "Sunshine") @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_LIGHT @property def is_on(self) -> bool: """Return true if sun is shining.""" return self._device.sunshine @property def device_state_attributes(self) -> Dict[str, Any]: """Return the state attributes of the illuminance sensor.""" state_attr = super().device_state_attributes today_sunshine_duration = getattr(self._device, "todaySunshineDuration", None) if today_sunshine_duration: state_attr[ATTR_TODAY_SUNSHINE_DURATION] = today_sunshine_duration return state_attr class HomematicipBatterySensor(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP low battery sensor.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize battery sensor.""" super().__init__(hap, device, "Battery") @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_BATTERY @property def is_on(self) -> bool: """Return true if battery is low.""" return self._device.lowBat class HomematicipPluggableMainsFailureSurveillanceSensor( HomematicipGenericEntity, BinarySensorEntity ): """Representation of the HomematicIP pluggable mains failure surveillance sensor.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize pluggable mains failure surveillance sensor.""" super().__init__(hap, device) @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_POWER @property def is_on(self) -> bool: """Return true if power mains fails.""" return not self._device.powerMainsFailure class HomematicipSecurityZoneSensorGroup(HomematicipGenericEntity, BinarySensorEntity): """Representation of the HomematicIP security zone sensor group.""" def __init__(self, hap: HomematicipHAP, device, post: str = "SecurityZone") -> None: """Initialize security zone group.""" device.modelType = f"HmIP-{post}" super().__init__(hap, device, post) @property def device_class(self) -> str: """Return the class of this sensor.""" return DEVICE_CLASS_SAFETY @property def available(self) -> bool: """Security-Group available.""" # A security-group must be available, and should not be affected by # the individual availability of group members. return True @property def device_state_attributes(self) -> Dict[str, Any]: """Return the state attributes of the security zone group.""" state_attr = super().device_state_attributes for attr, attr_key in GROUP_ATTRIBUTES.items(): attr_value = getattr(self._device, attr, None) if attr_value: state_attr[attr_key] = attr_value window_state = getattr(self._device, "windowState", None) if window_state and window_state != WindowState.CLOSED: state_attr[ATTR_WINDOW_STATE] = str(window_state) return state_attr @property def is_on(self) -> bool: """Return true if security issue detected.""" if ( self._device.motionDetected or self._device.presenceDetected or self._device.unreach or self._device.sabotage ): return True if ( self._device.windowState is not None and self._device.windowState != WindowState.CLOSED ): return True return False class HomematicipSecuritySensorGroup( HomematicipSecurityZoneSensorGroup, BinarySensorEntity ): """Representation of the HomematicIP security group.""" def __init__(self, hap: HomematicipHAP, device) -> None: """Initialize security group.""" super().__init__(hap, device, "Sensors") @property def device_state_attributes(self) -> Dict[str, Any]: """Return the state attributes of the security group.""" state_attr = super().device_state_attributes smoke_detector_at = getattr(self._device, "smokeDetectorAlarmType", None) if smoke_detector_at: if smoke_detector_at == SmokeDetectorAlarmType.PRIMARY_ALARM: state_attr[ATTR_SMOKE_DETECTOR_ALARM] = str(smoke_detector_at) if smoke_detector_at == SmokeDetectorAlarmType.INTRUSION_ALARM: state_attr[ATTR_INTRUSION_ALARM] = str(smoke_detector_at) return state_attr @property def is_on(self) -> bool: """Return true if safety issue detected.""" parent_is_on = super().is_on if parent_is_on: return True if ( self._device.powerMainsFailure or self._device.moistureDetected or self._device.waterlevelDetected or self._device.lowBat or self._device.dutyCycle ): return True if ( self._device.smokeDetectorAlarmType is not None and self._device.smokeDetectorAlarmType != SmokeDetectorAlarmType.IDLE_OFF ): return True return False
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/homematicip_cloud/binary_sensor.py
"""Support for OVO Energy.""" from datetime import datetime, timedelta import logging from typing import Any, Dict import aiohttp import async_timeout from ovoenergy import OVODailyUsage from ovoenergy.ovoenergy import OVOEnergy from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers.typing import ConfigType, HomeAssistantType from homeassistant.helpers.update_coordinator import ( CoordinatorEntity, DataUpdateCoordinator, ) from .const import DATA_CLIENT, DATA_COORDINATOR, DOMAIN _LOGGER = logging.getLogger(__name__) async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool: """Set up the OVO Energy components.""" return True async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: """Set up OVO Energy from a config entry.""" client = OVOEnergy() try: await client.authenticate(entry.data[CONF_USERNAME], entry.data[CONF_PASSWORD]) except aiohttp.ClientError as exception: _LOGGER.warning(exception) raise ConfigEntryNotReady from exception async def async_update_data() -> OVODailyUsage: """Fetch data from OVO Energy.""" now = datetime.utcnow() async with async_timeout.timeout(10): try: await client.authenticate( entry.data[CONF_USERNAME], entry.data[CONF_PASSWORD] ) return await client.get_daily_usage(now.strftime("%Y-%m")) except aiohttp.ClientError as exception: _LOGGER.warning(exception) return None coordinator = DataUpdateCoordinator( hass, _LOGGER, # Name of the data. For logging purposes. name="sensor", update_method=async_update_data, # Polling interval. Will only be polled if there are subscribers. update_interval=timedelta(seconds=300), ) hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = { DATA_CLIENT: client, DATA_COORDINATOR: coordinator, } # Fetch initial data so we have data when entities subscribe await coordinator.async_refresh() # Setup components hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, "sensor") ) return True async def async_unload_entry(hass: HomeAssistantType, entry: ConfigType) -> bool: """Unload OVO Energy config entry.""" # Unload sensors await hass.config_entries.async_forward_entry_unload(entry, "sensor") del hass.data[DOMAIN][entry.entry_id] return True class OVOEnergyEntity(CoordinatorEntity): """Defines a base OVO Energy entity.""" def __init__( self, coordinator: DataUpdateCoordinator, client: OVOEnergy, key: str, name: str, icon: str, ) -> None: """Initialize the OVO Energy entity.""" super().__init__(coordinator) self._client = client self._key = key self._name = name self._icon = icon self._available = True @property def unique_id(self) -> str: """Return the unique ID for this sensor.""" return self._key @property def name(self) -> str: """Return the name of the entity.""" return self._name @property def icon(self) -> str: """Return the mdi icon of the entity.""" return self._icon @property def available(self) -> bool: """Return True if entity is available.""" return self.coordinator.last_update_success and self._available class OVOEnergyDeviceEntity(OVOEnergyEntity): """Defines a OVO Energy device entity.""" @property def device_info(self) -> Dict[str, Any]: """Return device information about this OVO Energy instance.""" return { "identifiers": {(DOMAIN, self._client.account_id)}, "manufacturer": "OVO Energy", "name": self._client.account_id, "entry_type": "service", }
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/ovo_energy/__init__.py
"""Support for turning on and off Pi-hole system.""" import logging from hole.exceptions import HoleError import voluptuous as vol from homeassistant.components.switch import SwitchEntity from homeassistant.const import CONF_NAME from homeassistant.helpers import config_validation as cv, entity_platform from . import PiHoleEntity from .const import ( DATA_KEY_API, DATA_KEY_COORDINATOR, DOMAIN as PIHOLE_DOMAIN, SERVICE_DISABLE, SERVICE_DISABLE_ATTR_DURATION, ) _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass, entry, async_add_entities): """Set up the Pi-hole switch.""" name = entry.data[CONF_NAME] hole_data = hass.data[PIHOLE_DOMAIN][entry.entry_id] switches = [ PiHoleSwitch( hole_data[DATA_KEY_API], hole_data[DATA_KEY_COORDINATOR], name, entry.entry_id, ) ] async_add_entities(switches, True) # register service platform = entity_platform.current_platform.get() platform.async_register_entity_service( SERVICE_DISABLE, { vol.Required(SERVICE_DISABLE_ATTR_DURATION): vol.All( cv.time_period_str, cv.positive_timedelta ), }, "async_disable", ) class PiHoleSwitch(PiHoleEntity, SwitchEntity): """Representation of a Pi-hole switch.""" @property def name(self): """Return the name of the switch.""" return self._name @property def unique_id(self): """Return the unique id of the switch.""" return f"{self._server_unique_id}/Switch" @property def icon(self): """Icon to use in the frontend, if any.""" return "mdi:pi-hole" @property def is_on(self): """Return if the service is on.""" return self.api.data.get("status") == "enabled" async def async_turn_on(self, **kwargs): """Turn on the service.""" try: await self.api.enable() await self.async_update() except HoleError as err: _LOGGER.error("Unable to enable Pi-hole: %s", err) async def async_turn_off(self, **kwargs): """Turn off the service.""" await self.async_disable() async def async_disable(self, duration=None): """Disable the service for a given duration.""" duration_seconds = True # Disable infinitely by default if duration is not None: duration_seconds = duration.total_seconds() _LOGGER.debug( "Disabling Pi-hole '%s' (%s) for %d seconds", self.name, self.api.host, duration_seconds, ) try: await self.api.disable(duration_seconds) await self.async_update() except HoleError as err: _LOGGER.error("Unable to disable Pi-hole: %s", err)
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/pi_hole/switch.py
"""Support for Rova garbage calendar.""" from datetime import datetime, timedelta import logging from requests.exceptions import ConnectTimeout, HTTPError from rova.rova import Rova import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_MONITORED_CONDITIONS, CONF_NAME, DEVICE_CLASS_TIMESTAMP, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle # Config for rova requests. CONF_ZIP_CODE = "zip_code" CONF_HOUSE_NUMBER = "house_number" CONF_HOUSE_NUMBER_SUFFIX = "house_number_suffix" UPDATE_DELAY = timedelta(hours=12) SCAN_INTERVAL = timedelta(hours=12) # Supported sensor types: # Key: [json_key, name, icon] SENSOR_TYPES = { "bio": ["gft", "Biowaste", "mdi:recycle"], "paper": ["papier", "Paper", "mdi:recycle"], "plastic": ["pmd", "PET", "mdi:recycle"], "residual": ["restafval", "Residual", "mdi:recycle"], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_ZIP_CODE): cv.string, vol.Required(CONF_HOUSE_NUMBER): cv.string, vol.Optional(CONF_HOUSE_NUMBER_SUFFIX, default=""): cv.string, vol.Optional(CONF_NAME, default="Rova"): cv.string, vol.Optional(CONF_MONITORED_CONDITIONS, default=["bio"]): vol.All( cv.ensure_list, [vol.In(SENSOR_TYPES)] ), } ) _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Create the Rova data service and sensors.""" zip_code = config[CONF_ZIP_CODE] house_number = config[CONF_HOUSE_NUMBER] house_number_suffix = config[CONF_HOUSE_NUMBER_SUFFIX] platform_name = config[CONF_NAME] # Create new Rova object to retrieve data api = Rova(zip_code, house_number, house_number_suffix) try: if not api.is_rova_area(): _LOGGER.error("ROVA does not collect garbage in this area") return except (ConnectTimeout, HTTPError): _LOGGER.error("Could not retrieve details from ROVA API") return # Create rova data service which will retrieve and update the data. data_service = RovaData(api) # Create a new sensor for each garbage type. entities = [] for sensor_key in config[CONF_MONITORED_CONDITIONS]: sensor = RovaSensor(platform_name, sensor_key, data_service) entities.append(sensor) add_entities(entities, True) class RovaSensor(Entity): """Representation of a Rova sensor.""" def __init__(self, platform_name, sensor_key, data_service): """Initialize the sensor.""" self.sensor_key = sensor_key self.platform_name = platform_name self.data_service = data_service self._state = None self._json_key = SENSOR_TYPES[self.sensor_key][0] @property def name(self): """Return the name.""" return f"{self.platform_name}_{self.sensor_key}" @property def icon(self): """Return the sensor icon.""" return SENSOR_TYPES[self.sensor_key][2] @property def device_class(self): """Return the class of this sensor.""" return DEVICE_CLASS_TIMESTAMP @property def state(self): """Return the state of the sensor.""" return self._state def update(self): """Get the latest data from the sensor and update the state.""" self.data_service.update() pickup_date = self.data_service.data.get(self._json_key) if pickup_date is not None: self._state = pickup_date.isoformat() class RovaData: """Get and update the latest data from the Rova API.""" def __init__(self, api): """Initialize the data object.""" self.api = api self.data = {} @Throttle(UPDATE_DELAY) def update(self): """Update the data from the Rova API.""" try: items = self.api.get_calendar_items() except (ConnectTimeout, HTTPError): _LOGGER.error("Could not retrieve data, retry again later") return self.data = {} for item in items: date = datetime.strptime(item["Date"], "%Y-%m-%dT%H:%M:%S") code = item["GarbageTypeCode"].lower() if code not in self.data and date > datetime.now(): self.data[code] = date _LOGGER.debug("Updated Rova calendar: %s", self.data)
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/rova/sensor.py
"""Support for Recollect Waste curbside collection pickup.""" from datetime import timedelta import logging import recollect_waste import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_NAME import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) ATTR_PICKUP_TYPES = "pickup_types" ATTR_AREA_NAME = "area_name" CONF_PLACE_ID = "place_id" CONF_SERVICE_ID = "service_id" DEFAULT_NAME = "recollect_waste" ICON = "mdi:trash-can-outline" SCAN_INTERVAL = timedelta(days=1) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_PLACE_ID): cv.string, vol.Required(CONF_SERVICE_ID): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Recollect Waste platform.""" client = recollect_waste.RecollectWasteClient( config[CONF_PLACE_ID], config[CONF_SERVICE_ID] ) # Ensure the client can connect to the API successfully # with given place_id and service_id. try: client.get_next_pickup() except recollect_waste.RecollectWasteException as ex: _LOGGER.error("Recollect Waste platform error. %s", ex) return add_entities([RecollectWasteSensor(config.get(CONF_NAME), client)], True) class RecollectWasteSensor(Entity): """Recollect Waste Sensor.""" def __init__(self, name, client): """Initialize the sensor.""" self._attributes = {} self._name = name self._state = None self.client = client @property def name(self): """Return the name of the sensor.""" return self._name @property def unique_id(self) -> str: """Return a unique ID.""" return f"{self.client.place_id}{self.client.service_id}" @property def state(self): """Return the state of the sensor.""" return self._state @property def device_state_attributes(self): """Return the state attributes.""" return self._attributes @property def icon(self): """Icon to use in the frontend.""" return ICON def update(self): """Update device state.""" try: pickup_event = self.client.get_next_pickup() self._state = pickup_event.event_date self._attributes.update( { ATTR_PICKUP_TYPES: pickup_event.pickup_types, ATTR_AREA_NAME: pickup_event.area_name, } ) except recollect_waste.RecollectWasteException as ex: _LOGGER.error("Recollect Waste platform error. %s", ex)
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/recollect_waste/sensor.py
"""Constants for the Rollease Acmeda Automate integration.""" import logging LOGGER = logging.getLogger(__package__) DOMAIN = "acmeda" ACMEDA_HUB_UPDATE = "acmeda_hub_update_{}" ACMEDA_ENTITY_REMOVE = "acmeda_entity_remove_{}"
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/acmeda/const.py
"""Allows the creation of a sensor that filters state property.""" from collections import Counter, deque from copy import copy from datetime import timedelta from functools import partial import logging from numbers import Number import statistics from typing import Optional import voluptuous as vol from homeassistant.components import history from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_ICON, ATTR_UNIT_OF_MEASUREMENT, CONF_ENTITY_ID, CONF_NAME, STATE_UNAVAILABLE, STATE_UNKNOWN, ) from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.helpers.event import async_track_state_change_event from homeassistant.helpers.reload import async_setup_reload_service from homeassistant.util.decorator import Registry import homeassistant.util.dt as dt_util from . import DOMAIN, PLATFORMS _LOGGER = logging.getLogger(__name__) FILTER_NAME_RANGE = "range" FILTER_NAME_LOWPASS = "lowpass" FILTER_NAME_OUTLIER = "outlier" FILTER_NAME_THROTTLE = "throttle" FILTER_NAME_TIME_THROTTLE = "time_throttle" FILTER_NAME_TIME_SMA = "time_simple_moving_average" FILTERS = Registry() CONF_FILTERS = "filters" CONF_FILTER_NAME = "filter" CONF_FILTER_WINDOW_SIZE = "window_size" CONF_FILTER_PRECISION = "precision" CONF_FILTER_RADIUS = "radius" CONF_FILTER_TIME_CONSTANT = "time_constant" CONF_FILTER_LOWER_BOUND = "lower_bound" CONF_FILTER_UPPER_BOUND = "upper_bound" CONF_TIME_SMA_TYPE = "type" TIME_SMA_LAST = "last" WINDOW_SIZE_UNIT_NUMBER_EVENTS = 1 WINDOW_SIZE_UNIT_TIME = 2 DEFAULT_WINDOW_SIZE = 1 DEFAULT_PRECISION = 2 DEFAULT_FILTER_RADIUS = 2.0 DEFAULT_FILTER_TIME_CONSTANT = 10 NAME_TEMPLATE = "{} filter" ICON = "mdi:chart-line-variant" FILTER_SCHEMA = vol.Schema( {vol.Optional(CONF_FILTER_PRECISION, default=DEFAULT_PRECISION): vol.Coerce(int)} ) FILTER_OUTLIER_SCHEMA = FILTER_SCHEMA.extend( { vol.Required(CONF_FILTER_NAME): FILTER_NAME_OUTLIER, vol.Optional(CONF_FILTER_WINDOW_SIZE, default=DEFAULT_WINDOW_SIZE): vol.Coerce( int ), vol.Optional(CONF_FILTER_RADIUS, default=DEFAULT_FILTER_RADIUS): vol.Coerce( float ), } ) FILTER_LOWPASS_SCHEMA = FILTER_SCHEMA.extend( { vol.Required(CONF_FILTER_NAME): FILTER_NAME_LOWPASS, vol.Optional(CONF_FILTER_WINDOW_SIZE, default=DEFAULT_WINDOW_SIZE): vol.Coerce( int ), vol.Optional( CONF_FILTER_TIME_CONSTANT, default=DEFAULT_FILTER_TIME_CONSTANT ): vol.Coerce(int), } ) FILTER_RANGE_SCHEMA = FILTER_SCHEMA.extend( { vol.Required(CONF_FILTER_NAME): FILTER_NAME_RANGE, vol.Optional(CONF_FILTER_LOWER_BOUND): vol.Coerce(float), vol.Optional(CONF_FILTER_UPPER_BOUND): vol.Coerce(float), } ) FILTER_TIME_SMA_SCHEMA = FILTER_SCHEMA.extend( { vol.Required(CONF_FILTER_NAME): FILTER_NAME_TIME_SMA, vol.Optional(CONF_TIME_SMA_TYPE, default=TIME_SMA_LAST): vol.In( [TIME_SMA_LAST] ), vol.Required(CONF_FILTER_WINDOW_SIZE): vol.All( cv.time_period, cv.positive_timedelta ), } ) FILTER_THROTTLE_SCHEMA = FILTER_SCHEMA.extend( { vol.Required(CONF_FILTER_NAME): FILTER_NAME_THROTTLE, vol.Optional(CONF_FILTER_WINDOW_SIZE, default=DEFAULT_WINDOW_SIZE): vol.Coerce( int ), } ) FILTER_TIME_THROTTLE_SCHEMA = FILTER_SCHEMA.extend( { vol.Required(CONF_FILTER_NAME): FILTER_NAME_TIME_THROTTLE, vol.Required(CONF_FILTER_WINDOW_SIZE): vol.All( cv.time_period, cv.positive_timedelta ), } ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_ENTITY_ID): cv.entity_id, vol.Optional(CONF_NAME): cv.string, vol.Required(CONF_FILTERS): vol.All( cv.ensure_list, [ vol.Any( FILTER_OUTLIER_SCHEMA, FILTER_LOWPASS_SCHEMA, FILTER_TIME_SMA_SCHEMA, FILTER_THROTTLE_SCHEMA, FILTER_TIME_THROTTLE_SCHEMA, FILTER_RANGE_SCHEMA, ) ], ), } ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the template sensors.""" await async_setup_reload_service(hass, DOMAIN, PLATFORMS) name = config.get(CONF_NAME) entity_id = config.get(CONF_ENTITY_ID) filters = [ FILTERS[_filter.pop(CONF_FILTER_NAME)](entity=entity_id, **_filter) for _filter in config[CONF_FILTERS] ] async_add_entities([SensorFilter(name, entity_id, filters)]) class SensorFilter(Entity): """Representation of a Filter Sensor.""" def __init__(self, name, entity_id, filters): """Initialize the sensor.""" self._name = name self._entity = entity_id self._unit_of_measurement = None self._state = None self._filters = filters self._icon = None @callback def _update_filter_sensor_state_event(self, event): """Handle device state changes.""" self._update_filter_sensor_state(event.data.get("new_state")) @callback def _update_filter_sensor_state(self, new_state, update_ha=True): """Process device state changes.""" if new_state is None or new_state.state in [STATE_UNKNOWN, STATE_UNAVAILABLE]: return temp_state = new_state try: for filt in self._filters: filtered_state = filt.filter_state(copy(temp_state)) _LOGGER.debug( "%s(%s=%s) -> %s", filt.name, self._entity, temp_state.state, "skip" if filt.skip_processing else filtered_state.state, ) if filt.skip_processing: return temp_state = filtered_state except ValueError: _LOGGER.error("Could not convert state: %s to number", self._state) return self._state = temp_state.state if self._icon is None: self._icon = new_state.attributes.get(ATTR_ICON, ICON) if self._unit_of_measurement is None: self._unit_of_measurement = new_state.attributes.get( ATTR_UNIT_OF_MEASUREMENT ) if update_ha: self.async_write_ha_state() async def async_added_to_hass(self): """Register callbacks.""" if "recorder" in self.hass.config.components: history_list = [] largest_window_items = 0 largest_window_time = timedelta(0) # Determine the largest window_size by type for filt in self._filters: if ( filt.window_unit == WINDOW_SIZE_UNIT_NUMBER_EVENTS and largest_window_items < filt.window_size ): largest_window_items = filt.window_size elif ( filt.window_unit == WINDOW_SIZE_UNIT_TIME and largest_window_time < filt.window_size ): largest_window_time = filt.window_size # Retrieve the largest window_size of each type if largest_window_items > 0: filter_history = await self.hass.async_add_job( partial( history.get_last_state_changes, self.hass, largest_window_items, entity_id=self._entity, ) ) if self._entity in filter_history: history_list.extend(filter_history[self._entity]) if largest_window_time > timedelta(seconds=0): start = dt_util.utcnow() - largest_window_time filter_history = await self.hass.async_add_job( partial( history.state_changes_during_period, self.hass, start, entity_id=self._entity, ) ) if self._entity in filter_history: history_list.extend( [ state for state in filter_history[self._entity] if state not in history_list ] ) # Sort the window states history_list = sorted(history_list, key=lambda s: s.last_updated) _LOGGER.debug( "Loading from history: %s", [(s.state, s.last_updated) for s in history_list], ) # Replay history through the filter chain for state in history_list: self._update_filter_sensor_state(state, False) self.async_on_remove( async_track_state_change_event( self.hass, [self._entity], self._update_filter_sensor_state_event ) ) @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._state @property def icon(self): """Return the icon to use in the frontend, if any.""" return self._icon @property def unit_of_measurement(self): """Return the unit_of_measurement of the device.""" return self._unit_of_measurement @property def should_poll(self): """No polling needed.""" return False @property def device_state_attributes(self): """Return the state attributes of the sensor.""" state_attr = {ATTR_ENTITY_ID: self._entity} return state_attr class FilterState: """State abstraction for filter usage.""" def __init__(self, state): """Initialize with HA State object.""" self.timestamp = state.last_updated try: self.state = float(state.state) except ValueError: self.state = state.state def set_precision(self, precision): """Set precision of Number based states.""" if isinstance(self.state, Number): value = round(float(self.state), precision) self.state = int(value) if precision == 0 else value def __str__(self): """Return state as the string representation of FilterState.""" return str(self.state) def __repr__(self): """Return timestamp and state as the representation of FilterState.""" return f"{self.timestamp} : {self.state}" class Filter: """Filter skeleton.""" def __init__( self, name, window_size: int = 1, precision: Optional[int] = None, entity: Optional[str] = None, ): """Initialize common attributes. :param window_size: size of the sliding window that holds previous values :param precision: round filtered value to precision value :param entity: used for debugging only """ if isinstance(window_size, int): self.states = deque(maxlen=window_size) self.window_unit = WINDOW_SIZE_UNIT_NUMBER_EVENTS else: self.states = deque(maxlen=0) self.window_unit = WINDOW_SIZE_UNIT_TIME self.precision = precision self._name = name self._entity = entity self._skip_processing = False self._window_size = window_size self._store_raw = False self._only_numbers = True @property def window_size(self): """Return window size.""" return self._window_size @property def name(self): """Return filter name.""" return self._name @property def skip_processing(self): """Return whether the current filter_state should be skipped.""" return self._skip_processing def _filter_state(self, new_state): """Implement filter.""" raise NotImplementedError() def filter_state(self, new_state): """Implement a common interface for filters.""" fstate = FilterState(new_state) if self._only_numbers and not isinstance(fstate.state, Number): raise ValueError filtered = self._filter_state(fstate) filtered.set_precision(self.precision) if self._store_raw: self.states.append(copy(FilterState(new_state))) else: self.states.append(copy(filtered)) new_state.state = filtered.state return new_state @FILTERS.register(FILTER_NAME_RANGE) class RangeFilter(Filter): """Range filter. Determines if new state is in the range of upper_bound and lower_bound. If not inside, lower or upper bound is returned instead. """ def __init__( self, entity, precision: Optional[int] = DEFAULT_PRECISION, lower_bound: Optional[float] = None, upper_bound: Optional[float] = None, ): """Initialize Filter. :param upper_bound: band upper bound :param lower_bound: band lower bound """ super().__init__(FILTER_NAME_RANGE, precision=precision, entity=entity) self._lower_bound = lower_bound self._upper_bound = upper_bound self._stats_internal = Counter() def _filter_state(self, new_state): """Implement the range filter.""" if self._upper_bound is not None and new_state.state > self._upper_bound: self._stats_internal["erasures_up"] += 1 _LOGGER.debug( "Upper outlier nr. %s in %s: %s", self._stats_internal["erasures_up"], self._entity, new_state, ) new_state.state = self._upper_bound elif self._lower_bound is not None and new_state.state < self._lower_bound: self._stats_internal["erasures_low"] += 1 _LOGGER.debug( "Lower outlier nr. %s in %s: %s", self._stats_internal["erasures_low"], self._entity, new_state, ) new_state.state = self._lower_bound return new_state @FILTERS.register(FILTER_NAME_OUTLIER) class OutlierFilter(Filter): """BASIC outlier filter. Determines if new state is in a band around the median. """ def __init__(self, window_size, precision, entity, radius: float): """Initialize Filter. :param radius: band radius """ super().__init__(FILTER_NAME_OUTLIER, window_size, precision, entity) self._radius = radius self._stats_internal = Counter() self._store_raw = True def _filter_state(self, new_state): """Implement the outlier filter.""" median = statistics.median([s.state for s in self.states]) if self.states else 0 if ( len(self.states) == self.states.maxlen and abs(new_state.state - median) > self._radius ): self._stats_internal["erasures"] += 1 _LOGGER.debug( "Outlier nr. %s in %s: %s", self._stats_internal["erasures"], self._entity, new_state, ) new_state.state = median return new_state @FILTERS.register(FILTER_NAME_LOWPASS) class LowPassFilter(Filter): """BASIC Low Pass Filter.""" def __init__(self, window_size, precision, entity, time_constant: int): """Initialize Filter.""" super().__init__(FILTER_NAME_LOWPASS, window_size, precision, entity) self._time_constant = time_constant def _filter_state(self, new_state): """Implement the low pass filter.""" if not self.states: return new_state new_weight = 1.0 / self._time_constant prev_weight = 1.0 - new_weight new_state.state = ( prev_weight * self.states[-1].state + new_weight * new_state.state ) return new_state @FILTERS.register(FILTER_NAME_TIME_SMA) class TimeSMAFilter(Filter): """Simple Moving Average (SMA) Filter. The window_size is determined by time, and SMA is time weighted. """ def __init__( self, window_size, precision, entity, type ): # pylint: disable=redefined-builtin """Initialize Filter. :param type: type of algorithm used to connect discrete values """ super().__init__(FILTER_NAME_TIME_SMA, window_size, precision, entity) self._time_window = window_size self.last_leak = None self.queue = deque() def _leak(self, left_boundary): """Remove timeouted elements.""" while self.queue: if self.queue[0].timestamp + self._time_window <= left_boundary: self.last_leak = self.queue.popleft() else: return def _filter_state(self, new_state): """Implement the Simple Moving Average filter.""" self._leak(new_state.timestamp) self.queue.append(copy(new_state)) moving_sum = 0 start = new_state.timestamp - self._time_window prev_state = self.last_leak or self.queue[0] for state in self.queue: moving_sum += (state.timestamp - start).total_seconds() * prev_state.state start = state.timestamp prev_state = state new_state.state = moving_sum / self._time_window.total_seconds() return new_state @FILTERS.register(FILTER_NAME_THROTTLE) class ThrottleFilter(Filter): """Throttle Filter. One sample per window. """ def __init__(self, window_size, precision, entity): """Initialize Filter.""" super().__init__(FILTER_NAME_THROTTLE, window_size, precision, entity) self._only_numbers = False def _filter_state(self, new_state): """Implement the throttle filter.""" if not self.states or len(self.states) == self.states.maxlen: self.states.clear() self._skip_processing = False else: self._skip_processing = True return new_state @FILTERS.register(FILTER_NAME_TIME_THROTTLE) class TimeThrottleFilter(Filter): """Time Throttle Filter. One sample per time period. """ def __init__(self, window_size, precision, entity): """Initialize Filter.""" super().__init__(FILTER_NAME_TIME_THROTTLE, window_size, precision, entity) self._time_window = window_size self._last_emitted_at = None self._only_numbers = False def _filter_state(self, new_state): """Implement the filter.""" window_start = new_state.timestamp - self._time_window if not self._last_emitted_at or self._last_emitted_at <= window_start: self._last_emitted_at = new_state.timestamp self._skip_processing = False else: self._skip_processing = True return new_state
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/filter/sensor.py
"""Time-based One Time Password auth module.""" import asyncio from io import BytesIO import logging from typing import Any, Dict, Optional, Tuple import voluptuous as vol from homeassistant.auth.models import User from homeassistant.core import HomeAssistant from . import ( MULTI_FACTOR_AUTH_MODULE_SCHEMA, MULTI_FACTOR_AUTH_MODULES, MultiFactorAuthModule, SetupFlow, ) REQUIREMENTS = ["pyotp==2.3.0", "PyQRCode==1.2.1"] CONFIG_SCHEMA = MULTI_FACTOR_AUTH_MODULE_SCHEMA.extend({}, extra=vol.PREVENT_EXTRA) STORAGE_VERSION = 1 STORAGE_KEY = "auth_module.totp" STORAGE_USERS = "users" STORAGE_USER_ID = "user_id" STORAGE_OTA_SECRET = "ota_secret" INPUT_FIELD_CODE = "code" DUMMY_SECRET = "FPPTH34D4E3MI2HG" _LOGGER = logging.getLogger(__name__) def _generate_qr_code(data: str) -> str: """Generate a base64 PNG string represent QR Code image of data.""" import pyqrcode # pylint: disable=import-outside-toplevel qr_code = pyqrcode.create(data) with BytesIO() as buffer: qr_code.svg(file=buffer, scale=4) return str( buffer.getvalue() .decode("ascii") .replace("\n", "") .replace( '<?xml version="1.0" encoding="UTF-8"?>' '<svg xmlns="http://www.w3.org/2000/svg"', "<svg", ) ) def _generate_secret_and_qr_code(username: str) -> Tuple[str, str, str]: """Generate a secret, url, and QR code.""" import pyotp # pylint: disable=import-outside-toplevel ota_secret = pyotp.random_base32() url = pyotp.totp.TOTP(ota_secret).provisioning_uri( username, issuer_name="Home Assistant" ) image = _generate_qr_code(url) return ota_secret, url, image @MULTI_FACTOR_AUTH_MODULES.register("totp") class TotpAuthModule(MultiFactorAuthModule): """Auth module validate time-based one time password.""" DEFAULT_TITLE = "Time-based One Time Password" MAX_RETRY_TIME = 5 def __init__(self, hass: HomeAssistant, config: Dict[str, Any]) -> None: """Initialize the user data store.""" super().__init__(hass, config) self._users: Optional[Dict[str, str]] = None self._user_store = hass.helpers.storage.Store( STORAGE_VERSION, STORAGE_KEY, private=True ) self._init_lock = asyncio.Lock() @property def input_schema(self) -> vol.Schema: """Validate login flow input data.""" return vol.Schema({INPUT_FIELD_CODE: str}) async def _async_load(self) -> None: """Load stored data.""" async with self._init_lock: if self._users is not None: return data = await self._user_store.async_load() if data is None: data = {STORAGE_USERS: {}} self._users = data.get(STORAGE_USERS, {}) async def _async_save(self) -> None: """Save data.""" await self._user_store.async_save({STORAGE_USERS: self._users}) def _add_ota_secret(self, user_id: str, secret: Optional[str] = None) -> str: """Create a ota_secret for user.""" import pyotp # pylint: disable=import-outside-toplevel ota_secret: str = secret or pyotp.random_base32() self._users[user_id] = ota_secret # type: ignore return ota_secret async def async_setup_flow(self, user_id: str) -> SetupFlow: """Return a data entry flow handler for setup module. Mfa module should extend SetupFlow """ user = await self.hass.auth.async_get_user(user_id) assert user is not None return TotpSetupFlow(self, self.input_schema, user) async def async_setup_user(self, user_id: str, setup_data: Any) -> str: """Set up auth module for user.""" if self._users is None: await self._async_load() result = await self.hass.async_add_executor_job( self._add_ota_secret, user_id, setup_data.get("secret") ) await self._async_save() return result async def async_depose_user(self, user_id: str) -> None: """Depose auth module for user.""" if self._users is None: await self._async_load() if self._users.pop(user_id, None): # type: ignore await self._async_save() async def async_is_user_setup(self, user_id: str) -> bool: """Return whether user is setup.""" if self._users is None: await self._async_load() return user_id in self._users # type: ignore async def async_validate(self, user_id: str, user_input: Dict[str, Any]) -> bool: """Return True if validation passed.""" if self._users is None: await self._async_load() # user_input has been validate in caller # set INPUT_FIELD_CODE as vol.Required is not user friendly return await self.hass.async_add_executor_job( self._validate_2fa, user_id, user_input.get(INPUT_FIELD_CODE, "") ) def _validate_2fa(self, user_id: str, code: str) -> bool: """Validate two factor authentication code.""" import pyotp # pylint: disable=import-outside-toplevel ota_secret = self._users.get(user_id) # type: ignore if ota_secret is None: # even we cannot find user, we still do verify # to make timing the same as if user was found. pyotp.TOTP(DUMMY_SECRET).verify(code, valid_window=1) return False return bool(pyotp.TOTP(ota_secret).verify(code, valid_window=1)) class TotpSetupFlow(SetupFlow): """Handler for the setup flow.""" def __init__( self, auth_module: TotpAuthModule, setup_schema: vol.Schema, user: User ) -> None: """Initialize the setup flow.""" super().__init__(auth_module, setup_schema, user.id) # to fix typing complaint self._auth_module: TotpAuthModule = auth_module self._user = user self._ota_secret: Optional[str] = None self._url = None # type Optional[str] self._image = None # type Optional[str] async def async_step_init( self, user_input: Optional[Dict[str, str]] = None ) -> Dict[str, Any]: """Handle the first step of setup flow. Return self.async_show_form(step_id='init') if user_input is None. Return self.async_create_entry(data={'result': result}) if finish. """ import pyotp # pylint: disable=import-outside-toplevel errors: Dict[str, str] = {} if user_input: verified = await self.hass.async_add_executor_job( # type: ignore pyotp.TOTP(self._ota_secret).verify, user_input["code"] ) if verified: result = await self._auth_module.async_setup_user( self._user_id, {"secret": self._ota_secret} ) return self.async_create_entry( title=self._auth_module.name, data={"result": result} ) errors["base"] = "invalid_code" else: hass = self._auth_module.hass ( self._ota_secret, self._url, self._image, ) = await hass.async_add_executor_job( _generate_secret_and_qr_code, # type: ignore str(self._user.name), ) return self.async_show_form( step_id="init", data_schema=self._setup_schema, description_placeholders={ "code": self._ota_secret, "url": self._url, "qr_code": self._image, }, errors=errors, )
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/auth/mfa_modules/totp.py
"""Support for Alexa skill service end point.""" import logging import voluptuous as vol from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET, CONF_NAME from homeassistant.helpers import config_validation as cv, entityfilter from . import flash_briefings, intent, smart_home_http from .const import ( CONF_AUDIO, CONF_DESCRIPTION, CONF_DISPLAY_CATEGORIES, CONF_DISPLAY_URL, CONF_ENDPOINT, CONF_ENTITY_CONFIG, CONF_FILTER, CONF_LOCALE, CONF_PASSWORD, CONF_SUPPORTED_LOCALES, CONF_TEXT, CONF_TITLE, CONF_UID, DOMAIN, ) _LOGGER = logging.getLogger(__name__) CONF_FLASH_BRIEFINGS = "flash_briefings" CONF_SMART_HOME = "smart_home" DEFAULT_LOCALE = "en-US" ALEXA_ENTITY_SCHEMA = vol.Schema( { vol.Optional(CONF_DESCRIPTION): cv.string, vol.Optional(CONF_DISPLAY_CATEGORIES): cv.string, vol.Optional(CONF_NAME): cv.string, } ) SMART_HOME_SCHEMA = vol.Schema( { vol.Optional(CONF_ENDPOINT): cv.string, vol.Optional(CONF_CLIENT_ID): cv.string, vol.Optional(CONF_CLIENT_SECRET): cv.string, vol.Optional(CONF_LOCALE, default=DEFAULT_LOCALE): vol.In( CONF_SUPPORTED_LOCALES ), vol.Optional(CONF_FILTER, default={}): entityfilter.FILTER_SCHEMA, vol.Optional(CONF_ENTITY_CONFIG): {cv.entity_id: ALEXA_ENTITY_SCHEMA}, } ) CONFIG_SCHEMA = vol.Schema( { DOMAIN: { CONF_FLASH_BRIEFINGS: { vol.Required(CONF_PASSWORD): cv.string, cv.string: vol.All( cv.ensure_list, [ { vol.Optional(CONF_UID): cv.string, vol.Required(CONF_TITLE): cv.template, vol.Optional(CONF_AUDIO): cv.template, vol.Required(CONF_TEXT, default=""): cv.template, vol.Optional(CONF_DISPLAY_URL): cv.template, } ], ), }, # vol.Optional here would mean we couldn't distinguish between an empty # smart_home: and none at all. CONF_SMART_HOME: vol.Any(SMART_HOME_SCHEMA, None), } }, extra=vol.ALLOW_EXTRA, ) async def async_setup(hass, config): """Activate the Alexa component.""" if DOMAIN not in config: return True config = config[DOMAIN] flash_briefings_config = config.get(CONF_FLASH_BRIEFINGS) intent.async_setup(hass) if flash_briefings_config: flash_briefings.async_setup(hass, flash_briefings_config) try: smart_home_config = config[CONF_SMART_HOME] except KeyError: pass else: smart_home_config = smart_home_config or SMART_HOME_SCHEMA({}) await smart_home_http.async_setup(hass, smart_home_config) return True
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/alexa/__init__.py
"""Support for LCN lights.""" import pypck from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_TRANSITION, SUPPORT_BRIGHTNESS, SUPPORT_TRANSITION, LightEntity, ) from homeassistant.const import CONF_ADDRESS from . import LcnDevice from .const import ( CONF_CONNECTIONS, CONF_DIMMABLE, CONF_OUTPUT, CONF_TRANSITION, DATA_LCN, OUTPUT_PORTS, ) from .helpers import get_connection async def async_setup_platform( hass, hass_config, async_add_entities, discovery_info=None ): """Set up the LCN light platform.""" if discovery_info is None: return devices = [] for config in discovery_info: address, connection_id = config[CONF_ADDRESS] addr = pypck.lcn_addr.LcnAddr(*address) connections = hass.data[DATA_LCN][CONF_CONNECTIONS] connection = get_connection(connections, connection_id) address_connection = connection.get_address_conn(addr) if config[CONF_OUTPUT] in OUTPUT_PORTS: device = LcnOutputLight(config, address_connection) else: # in RELAY_PORTS device = LcnRelayLight(config, address_connection) devices.append(device) async_add_entities(devices) class LcnOutputLight(LcnDevice, LightEntity): """Representation of a LCN light for output ports.""" def __init__(self, config, address_connection): """Initialize the LCN light.""" super().__init__(config, address_connection) self.output = pypck.lcn_defs.OutputPort[config[CONF_OUTPUT]] self._transition = pypck.lcn_defs.time_to_ramp_value(config[CONF_TRANSITION]) self.dimmable = config[CONF_DIMMABLE] self._brightness = 255 self._is_on = None self._is_dimming_to_zero = False async def async_added_to_hass(self): """Run when entity about to be added to hass.""" await super().async_added_to_hass() await self.address_connection.activate_status_request_handler(self.output) @property def supported_features(self): """Flag supported features.""" features = SUPPORT_TRANSITION if self.dimmable: features |= SUPPORT_BRIGHTNESS return features @property def brightness(self): """Return the brightness of this light between 0..255.""" return self._brightness @property def is_on(self): """Return True if entity is on.""" return self._is_on async def async_turn_on(self, **kwargs): """Turn the entity on.""" self._is_on = True self._is_dimming_to_zero = False if ATTR_BRIGHTNESS in kwargs: percent = int(kwargs[ATTR_BRIGHTNESS] / 255.0 * 100) else: percent = 100 if ATTR_TRANSITION in kwargs: transition = pypck.lcn_defs.time_to_ramp_value( kwargs[ATTR_TRANSITION] * 1000 ) else: transition = self._transition self.address_connection.dim_output(self.output.value, percent, transition) self.async_write_ha_state() async def async_turn_off(self, **kwargs): """Turn the entity off.""" self._is_on = False if ATTR_TRANSITION in kwargs: transition = pypck.lcn_defs.time_to_ramp_value( kwargs[ATTR_TRANSITION] * 1000 ) else: transition = self._transition self._is_dimming_to_zero = bool(transition) self.address_connection.dim_output(self.output.value, 0, transition) self.async_write_ha_state() def input_received(self, input_obj): """Set light state when LCN input object (command) is received.""" if ( not isinstance(input_obj, pypck.inputs.ModStatusOutput) or input_obj.get_output_id() != self.output.value ): return self._brightness = int(input_obj.get_percent() / 100.0 * 255) if self.brightness == 0: self._is_dimming_to_zero = False if not self._is_dimming_to_zero: self._is_on = self.brightness > 0 self.async_write_ha_state() class LcnRelayLight(LcnDevice, LightEntity): """Representation of a LCN light for relay ports.""" def __init__(self, config, address_connection): """Initialize the LCN light.""" super().__init__(config, address_connection) self.output = pypck.lcn_defs.RelayPort[config[CONF_OUTPUT]] self._is_on = None async def async_added_to_hass(self): """Run when entity about to be added to hass.""" await super().async_added_to_hass() await self.address_connection.activate_status_request_handler(self.output) @property def is_on(self): """Return True if entity is on.""" return self._is_on async def async_turn_on(self, **kwargs): """Turn the entity on.""" self._is_on = True states = [pypck.lcn_defs.RelayStateModifier.NOCHANGE] * 8 states[self.output.value] = pypck.lcn_defs.RelayStateModifier.ON self.address_connection.control_relays(states) self.async_write_ha_state() async def async_turn_off(self, **kwargs): """Turn the entity off.""" self._is_on = False states = [pypck.lcn_defs.RelayStateModifier.NOCHANGE] * 8 states[self.output.value] = pypck.lcn_defs.RelayStateModifier.OFF self.address_connection.control_relays(states) self.async_write_ha_state() def input_received(self, input_obj): """Set light state when LCN input object (command) is received.""" if not isinstance(input_obj, pypck.inputs.ModStatusRelays): return self._is_on = input_obj.get_state(self.output.value) self.async_write_ha_state()
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/lcn/light.py
"""Support for AlarmDecoder devices.""" import asyncio from datetime import timedelta import logging from adext import AdExt from alarmdecoder.devices import SerialDevice, SocketDevice from alarmdecoder.util import NoDeviceError from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONF_HOST, CONF_PORT, CONF_PROTOCOL, EVENT_HOMEASSISTANT_STOP, ) from homeassistant.helpers.typing import HomeAssistantType from homeassistant.util import dt as dt_util from .const import ( CONF_DEVICE_BAUD, CONF_DEVICE_PATH, DATA_AD, DATA_REMOVE_STOP_LISTENER, DATA_REMOVE_UPDATE_LISTENER, DATA_RESTART, DOMAIN, PROTOCOL_SERIAL, PROTOCOL_SOCKET, SIGNAL_PANEL_MESSAGE, SIGNAL_REL_MESSAGE, SIGNAL_RFX_MESSAGE, SIGNAL_ZONE_FAULT, SIGNAL_ZONE_RESTORE, ) _LOGGER = logging.getLogger(__name__) PLATFORMS = ["alarm_control_panel", "sensor", "binary_sensor"] async def async_setup(hass, config): """Set up for the AlarmDecoder devices.""" return True async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: """Set up AlarmDecoder config flow.""" undo_listener = entry.add_update_listener(_update_listener) ad_connection = entry.data protocol = ad_connection[CONF_PROTOCOL] def stop_alarmdecoder(event): """Handle the shutdown of AlarmDecoder.""" if not hass.data.get(DOMAIN): return _LOGGER.debug("Shutting down alarmdecoder") hass.data[DOMAIN][entry.entry_id][DATA_RESTART] = False controller.close() async def open_connection(now=None): """Open a connection to AlarmDecoder.""" try: await hass.async_add_executor_job(controller.open, baud) except NoDeviceError: _LOGGER.debug("Failed to connect. Retrying in 5 seconds") hass.helpers.event.async_track_point_in_time( open_connection, dt_util.utcnow() + timedelta(seconds=5) ) return _LOGGER.debug("Established a connection with the alarmdecoder") hass.data[DOMAIN][entry.entry_id][DATA_RESTART] = True def handle_closed_connection(event): """Restart after unexpected loss of connection.""" if not hass.data[DOMAIN][entry.entry_id][DATA_RESTART]: return hass.data[DOMAIN][entry.entry_id][DATA_RESTART] = False _LOGGER.warning("AlarmDecoder unexpectedly lost connection") hass.add_job(open_connection) def handle_message(sender, message): """Handle message from AlarmDecoder.""" hass.helpers.dispatcher.dispatcher_send(SIGNAL_PANEL_MESSAGE, message) def handle_rfx_message(sender, message): """Handle RFX message from AlarmDecoder.""" hass.helpers.dispatcher.dispatcher_send(SIGNAL_RFX_MESSAGE, message) def zone_fault_callback(sender, zone): """Handle zone fault from AlarmDecoder.""" hass.helpers.dispatcher.dispatcher_send(SIGNAL_ZONE_FAULT, zone) def zone_restore_callback(sender, zone): """Handle zone restore from AlarmDecoder.""" hass.helpers.dispatcher.dispatcher_send(SIGNAL_ZONE_RESTORE, zone) def handle_rel_message(sender, message): """Handle relay or zone expander message from AlarmDecoder.""" hass.helpers.dispatcher.dispatcher_send(SIGNAL_REL_MESSAGE, message) baud = ad_connection.get(CONF_DEVICE_BAUD) if protocol == PROTOCOL_SOCKET: host = ad_connection[CONF_HOST] port = ad_connection[CONF_PORT] controller = AdExt(SocketDevice(interface=(host, port))) if protocol == PROTOCOL_SERIAL: path = ad_connection[CONF_DEVICE_PATH] controller = AdExt(SerialDevice(interface=path)) controller.on_message += handle_message controller.on_rfx_message += handle_rfx_message controller.on_zone_fault += zone_fault_callback controller.on_zone_restore += zone_restore_callback controller.on_close += handle_closed_connection controller.on_expander_message += handle_rel_message remove_stop_listener = hass.bus.async_listen_once( EVENT_HOMEASSISTANT_STOP, stop_alarmdecoder ) hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = { DATA_AD: controller, DATA_REMOVE_UPDATE_LISTENER: undo_listener, DATA_REMOVE_STOP_LISTENER: remove_stop_listener, DATA_RESTART: False, } await open_connection() for component in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, component) ) return True async def async_unload_entry(hass: HomeAssistantType, entry: ConfigEntry): """Unload a AlarmDecoder entry.""" hass.data[DOMAIN][entry.entry_id][DATA_RESTART] = False unload_ok = all( await asyncio.gather( *[ hass.config_entries.async_forward_entry_unload(entry, component) for component in PLATFORMS ] ) ) if not unload_ok: return False hass.data[DOMAIN][entry.entry_id][DATA_REMOVE_UPDATE_LISTENER]() hass.data[DOMAIN][entry.entry_id][DATA_REMOVE_STOP_LISTENER]() await hass.async_add_executor_job(hass.data[DOMAIN][entry.entry_id][DATA_AD].close) if hass.data[DOMAIN][entry.entry_id]: hass.data[DOMAIN].pop(entry.entry_id) if not hass.data[DOMAIN]: hass.data.pop(DOMAIN) return True async def _update_listener(hass: HomeAssistantType, entry: ConfigEntry): """Handle options update.""" _LOGGER.debug("AlarmDecoder options updated: %s", entry.as_dict()["options"]) await hass.config_entries.async_reload(entry.entry_id)
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/alarmdecoder/__init__.py
"""Support for Plaato Airlock.""" import logging from aiohttp import web import voluptuous as vol from homeassistant.components.sensor import DOMAIN as SENSOR from homeassistant.const import ( CONF_WEBHOOK_ID, HTTP_OK, TEMP_CELSIUS, TEMP_FAHRENHEIT, VOLUME_GALLONS, VOLUME_LITERS, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_send from .const import DOMAIN _LOGGER = logging.getLogger(__name__) DEPENDENCIES = ["webhook"] PLAATO_DEVICE_SENSORS = "sensors" PLAATO_DEVICE_ATTRS = "attrs" ATTR_DEVICE_ID = "device_id" ATTR_DEVICE_NAME = "device_name" ATTR_TEMP_UNIT = "temp_unit" ATTR_VOLUME_UNIT = "volume_unit" ATTR_BPM = "bpm" ATTR_TEMP = "temp" ATTR_SG = "sg" ATTR_OG = "og" ATTR_BUBBLES = "bubbles" ATTR_ABV = "abv" ATTR_CO2_VOLUME = "co2_volume" ATTR_BATCH_VOLUME = "batch_volume" SENSOR_UPDATE = f"{DOMAIN}_sensor_update" SENSOR_DATA_KEY = f"{DOMAIN}.{SENSOR}" WEBHOOK_SCHEMA = vol.Schema( { vol.Required(ATTR_DEVICE_NAME): cv.string, vol.Required(ATTR_DEVICE_ID): cv.positive_int, vol.Required(ATTR_TEMP_UNIT): vol.Any(TEMP_CELSIUS, TEMP_FAHRENHEIT), vol.Required(ATTR_VOLUME_UNIT): vol.Any(VOLUME_LITERS, VOLUME_GALLONS), vol.Required(ATTR_BPM): cv.positive_int, vol.Required(ATTR_TEMP): vol.Coerce(float), vol.Required(ATTR_SG): vol.Coerce(float), vol.Required(ATTR_OG): vol.Coerce(float), vol.Required(ATTR_ABV): vol.Coerce(float), vol.Required(ATTR_CO2_VOLUME): vol.Coerce(float), vol.Required(ATTR_BATCH_VOLUME): vol.Coerce(float), vol.Required(ATTR_BUBBLES): cv.positive_int, }, extra=vol.ALLOW_EXTRA, ) async def async_setup(hass, hass_config): """Set up the Plaato component.""" return True async def async_setup_entry(hass, entry): """Configure based on config entry.""" if DOMAIN not in hass.data: hass.data[DOMAIN] = {} webhook_id = entry.data[CONF_WEBHOOK_ID] hass.components.webhook.async_register(DOMAIN, "Plaato", webhook_id, handle_webhook) hass.async_create_task(hass.config_entries.async_forward_entry_setup(entry, SENSOR)) return True async def async_unload_entry(hass, entry): """Unload a config entry.""" hass.components.webhook.async_unregister(entry.data[CONF_WEBHOOK_ID]) hass.data[SENSOR_DATA_KEY]() await hass.config_entries.async_forward_entry_unload(entry, SENSOR) return True async def handle_webhook(hass, webhook_id, request): """Handle incoming webhook from Plaato.""" try: data = WEBHOOK_SCHEMA(await request.json()) except vol.MultipleInvalid as error: _LOGGER.warning("An error occurred when parsing webhook data <%s>", error) return device_id = _device_id(data) attrs = { ATTR_DEVICE_NAME: data.get(ATTR_DEVICE_NAME), ATTR_DEVICE_ID: data.get(ATTR_DEVICE_ID), ATTR_TEMP_UNIT: data.get(ATTR_TEMP_UNIT), ATTR_VOLUME_UNIT: data.get(ATTR_VOLUME_UNIT), } sensors = { ATTR_TEMP: data.get(ATTR_TEMP), ATTR_BPM: data.get(ATTR_BPM), ATTR_SG: data.get(ATTR_SG), ATTR_OG: data.get(ATTR_OG), ATTR_ABV: data.get(ATTR_ABV), ATTR_CO2_VOLUME: data.get(ATTR_CO2_VOLUME), ATTR_BATCH_VOLUME: data.get(ATTR_BATCH_VOLUME), ATTR_BUBBLES: data.get(ATTR_BUBBLES), } hass.data[DOMAIN][device_id] = { PLAATO_DEVICE_ATTRS: attrs, PLAATO_DEVICE_SENSORS: sensors, } async_dispatcher_send(hass, SENSOR_UPDATE, device_id) return web.Response(text=f"Saving status for {device_id}", status=HTTP_OK) def _device_id(data): """Return name of device sensor.""" return f"{data.get(ATTR_DEVICE_NAME)}_{data.get(ATTR_DEVICE_ID)}"
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/plaato/__init__.py
"""Support for the Pico TTS speech service.""" import logging import os import shutil import subprocess import tempfile import voluptuous as vol from homeassistant.components.tts import CONF_LANG, PLATFORM_SCHEMA, Provider _LOGGER = logging.getLogger(__name__) SUPPORT_LANGUAGES = ["en-US", "en-GB", "de-DE", "es-ES", "fr-FR", "it-IT"] DEFAULT_LANG = "en-US" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Optional(CONF_LANG, default=DEFAULT_LANG): vol.In(SUPPORT_LANGUAGES)} ) def get_engine(hass, config, discovery_info=None): """Set up Pico speech component.""" if shutil.which("pico2wave") is None: _LOGGER.error("'pico2wave' was not found") return False return PicoProvider(config[CONF_LANG]) class PicoProvider(Provider): """The Pico TTS API provider.""" def __init__(self, lang): """Initialize Pico TTS provider.""" self._lang = lang self.name = "PicoTTS" @property def default_language(self): """Return the default language.""" return self._lang @property def supported_languages(self): """Return list of supported languages.""" return SUPPORT_LANGUAGES def get_tts_audio(self, message, language, options=None): """Load TTS using pico2wave.""" with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmpf: fname = tmpf.name cmd = ["pico2wave", "--wave", fname, "-l", language, message] subprocess.call(cmd) data = None try: with open(fname, "rb") as voice: data = voice.read() except OSError: _LOGGER.error("Error trying to read %s", fname) return (None, None) finally: os.remove(fname) if data: return ("wav", data) return (None, None)
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/picotts/tts.py
"""Support for Dominos Pizza ordering.""" from datetime import timedelta import logging from pizzapi import Address, Customer, Order from pizzapi.address import StoreException import voluptuous as vol from homeassistant.components import http from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity_component import EntityComponent from homeassistant.util import Throttle _LOGGER = logging.getLogger(__name__) # The domain of your component. Should be equal to the name of your component. DOMAIN = "dominos" ENTITY_ID_FORMAT = DOMAIN + ".{}" ATTR_COUNTRY = "country_code" ATTR_FIRST_NAME = "first_name" ATTR_LAST_NAME = "last_name" ATTR_EMAIL = "email" ATTR_PHONE = "phone" ATTR_ADDRESS = "address" ATTR_ORDERS = "orders" ATTR_SHOW_MENU = "show_menu" ATTR_ORDER_ENTITY = "order_entity_id" ATTR_ORDER_NAME = "name" ATTR_ORDER_CODES = "codes" MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=10) MIN_TIME_BETWEEN_STORE_UPDATES = timedelta(minutes=3330) _ORDERS_SCHEMA = vol.Schema( { vol.Required(ATTR_ORDER_NAME): cv.string, vol.Required(ATTR_ORDER_CODES): vol.All(cv.ensure_list, [cv.string]), } ) CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Required(ATTR_COUNTRY): cv.string, vol.Required(ATTR_FIRST_NAME): cv.string, vol.Required(ATTR_LAST_NAME): cv.string, vol.Required(ATTR_EMAIL): cv.string, vol.Required(ATTR_PHONE): cv.string, vol.Required(ATTR_ADDRESS): cv.string, vol.Optional(ATTR_SHOW_MENU): cv.boolean, vol.Optional(ATTR_ORDERS, default=[]): vol.All( cv.ensure_list, [_ORDERS_SCHEMA] ), } ) }, extra=vol.ALLOW_EXTRA, ) def setup(hass, config): """Set up is called when Home Assistant is loading our component.""" dominos = Dominos(hass, config) component = EntityComponent(_LOGGER, DOMAIN, hass) hass.data[DOMAIN] = {} entities = [] conf = config[DOMAIN] hass.services.register(DOMAIN, "order", dominos.handle_order) if conf.get(ATTR_SHOW_MENU): hass.http.register_view(DominosProductListView(dominos)) for order_info in conf.get(ATTR_ORDERS): order = DominosOrder(order_info, dominos) entities.append(order) if entities: component.add_entities(entities) # Return boolean to indicate that initialization was successfully. return True class Dominos: """Main Dominos service.""" def __init__(self, hass, config): """Set up main service.""" conf = config[DOMAIN] self.hass = hass self.customer = Customer( conf.get(ATTR_FIRST_NAME), conf.get(ATTR_LAST_NAME), conf.get(ATTR_EMAIL), conf.get(ATTR_PHONE), conf.get(ATTR_ADDRESS), ) self.address = Address( *self.customer.address.split(","), country=conf.get(ATTR_COUNTRY) ) self.country = conf.get(ATTR_COUNTRY) try: self.closest_store = self.address.closest_store() except StoreException: self.closest_store = None def handle_order(self, call): """Handle ordering pizza.""" entity_ids = call.data.get(ATTR_ORDER_ENTITY) target_orders = [ order for order in self.hass.data[DOMAIN]["entities"] if order.entity_id in entity_ids ] for order in target_orders: order.place() @Throttle(MIN_TIME_BETWEEN_STORE_UPDATES) def update_closest_store(self): """Update the shared closest store (if open).""" try: self.closest_store = self.address.closest_store() return True except StoreException: self.closest_store = None return False def get_menu(self): """Return the products from the closest stores menu.""" self.update_closest_store() if self.closest_store is None: _LOGGER.warning("Cannot get menu. Store may be closed") return [] menu = self.closest_store.get_menu() product_entries = [] for product in menu.products: item = {} if isinstance(product.menu_data["Variants"], list): variants = ", ".join(product.menu_data["Variants"]) else: variants = product.menu_data["Variants"] item["name"] = product.name item["variants"] = variants product_entries.append(item) return product_entries class DominosProductListView(http.HomeAssistantView): """View to retrieve product list content.""" url = "/api/dominos" name = "api:dominos" def __init__(self, dominos): """Initialize suite view.""" self.dominos = dominos @callback def get(self, request): """Retrieve if API is running.""" return self.json(self.dominos.get_menu()) class DominosOrder(Entity): """Represents a Dominos order entity.""" def __init__(self, order_info, dominos): """Set up the entity.""" self._name = order_info["name"] self._product_codes = order_info["codes"] self._orderable = False self.dominos = dominos @property def name(self): """Return the orders name.""" return self._name @property def product_codes(self): """Return the orders product codes.""" return self._product_codes @property def orderable(self): """Return the true if orderable.""" return self._orderable @property def state(self): """Return the state either closed, orderable or unorderable.""" if self.dominos.closest_store is None: return "closed" return "orderable" if self._orderable else "unorderable" @Throttle(MIN_TIME_BETWEEN_UPDATES) def update(self): """Update the order state and refreshes the store.""" try: self.dominos.update_closest_store() except StoreException: self._orderable = False return try: order = self.order() order.pay_with() self._orderable = True except StoreException: self._orderable = False def order(self): """Create the order object.""" if self.dominos.closest_store is None: raise StoreException order = Order( self.dominos.closest_store, self.dominos.customer, self.dominos.address, self.dominos.country, ) for code in self._product_codes: order.add_item(code) return order def place(self): """Place the order.""" try: order = self.order() order.place() except StoreException: self._orderable = False _LOGGER.warning( "Attempted to order Dominos - Order invalid or store closed" )
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/dominos/__init__.py
"""Support for Vera switches.""" import logging from typing import Any, Callable, List, Optional import pyvera as veraApi from homeassistant.components.switch import ( DOMAIN as PLATFORM_DOMAIN, ENTITY_ID_FORMAT, SwitchEntity, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import Entity from homeassistant.util import convert from . import VeraDevice from .common import ControllerData, get_controller_data _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: Callable[[List[Entity], bool], None], ) -> None: """Set up the sensor config entry.""" controller_data = get_controller_data(hass, entry) async_add_entities( [ VeraSwitch(device, controller_data) for device in controller_data.devices.get(PLATFORM_DOMAIN) ] ) class VeraSwitch(VeraDevice[veraApi.VeraSwitch], SwitchEntity): """Representation of a Vera Switch.""" def __init__( self, vera_device: veraApi.VeraSwitch, controller_data: ControllerData ): """Initialize the Vera device.""" self._state = False VeraDevice.__init__(self, vera_device, controller_data) self.entity_id = ENTITY_ID_FORMAT.format(self.vera_id) def turn_on(self, **kwargs: Any) -> None: """Turn device on.""" self.vera_device.switch_on() self._state = True self.schedule_update_ha_state() def turn_off(self, **kwargs: Any) -> None: """Turn device off.""" self.vera_device.switch_off() self._state = False self.schedule_update_ha_state() @property def current_power_w(self) -> Optional[float]: """Return the current power usage in W.""" power = self.vera_device.power if power: return convert(power, float, 0.0) @property def is_on(self) -> bool: """Return true if device is on.""" return self._state def update(self) -> None: """Update device state.""" self._state = self.vera_device.is_switched_on()
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/components/vera/switch.py
"""JSON utility functions.""" from collections import deque import json import logging import os import tempfile from typing import Any, Callable, Dict, List, Optional, Type, Union from homeassistant.core import Event, State from homeassistant.exceptions import HomeAssistantError _LOGGER = logging.getLogger(__name__) class SerializationError(HomeAssistantError): """Error serializing the data to JSON.""" class WriteError(HomeAssistantError): """Error writing the data.""" def load_json( filename: str, default: Union[List, Dict, None] = None ) -> Union[List, Dict]: """Load JSON data from a file and return as dict or list. Defaults to returning empty dict if file is not found. """ try: with open(filename, encoding="utf-8") as fdesc: return json.loads(fdesc.read()) # type: ignore except FileNotFoundError: # This is not a fatal error _LOGGER.debug("JSON file not found: %s", filename) except ValueError as error: _LOGGER.exception("Could not parse JSON content: %s", filename) raise HomeAssistantError(error) from error except OSError as error: _LOGGER.exception("JSON file reading failed: %s", filename) raise HomeAssistantError(error) from error return {} if default is None else default def save_json( filename: str, data: Union[List, Dict], private: bool = False, *, encoder: Optional[Type[json.JSONEncoder]] = None, ) -> None: """Save JSON data to a file. Returns True on success. """ try: json_data = json.dumps(data, indent=4, cls=encoder) except TypeError as error: msg = f"Failed to serialize to JSON: {filename}. Bad data at {format_unserializable_data(find_paths_unserializable_data(data))}" _LOGGER.error(msg) raise SerializationError(msg) from error tmp_filename = "" tmp_path = os.path.split(filename)[0] try: # Modern versions of Python tempfile create this file with mode 0o600 with tempfile.NamedTemporaryFile( mode="w", encoding="utf-8", dir=tmp_path, delete=False ) as fdesc: fdesc.write(json_data) tmp_filename = fdesc.name if not private: os.chmod(tmp_filename, 0o644) os.replace(tmp_filename, filename) except OSError as error: _LOGGER.exception("Saving JSON file failed: %s", filename) raise WriteError(error) from error finally: if os.path.exists(tmp_filename): try: os.remove(tmp_filename) except OSError as err: # If we are cleaning up then something else went wrong, so # we should suppress likely follow-on errors in the cleanup _LOGGER.error("JSON replacement cleanup failed: %s", err) def format_unserializable_data(data: Dict[str, Any]) -> str: """Format output of find_paths in a friendly way. Format is comma separated: <path>=<value>(<type>) """ return ", ".join(f"{path}={value}({type(value)}" for path, value in data.items()) def find_paths_unserializable_data( bad_data: Any, *, dump: Callable[[Any], str] = json.dumps ) -> Dict[str, Any]: """Find the paths to unserializable data. This method is slow! Only use for error handling. """ to_process = deque([(bad_data, "$")]) invalid = {} while to_process: obj, obj_path = to_process.popleft() try: dump(obj) continue except (ValueError, TypeError): pass # We convert states and events to dict so we can find bad data inside it if isinstance(obj, State): obj_path += f"(state: {obj.entity_id})" obj = obj.as_dict() elif isinstance(obj, Event): obj_path += f"(event: {obj.event_type})" obj = obj.as_dict() if isinstance(obj, dict): for key, value in obj.items(): try: # Is key valid? dump({key: None}) except TypeError: invalid[f"{obj_path}<key: {key}>"] = key else: # Process value to_process.append((value, f"{obj_path}.{key}")) elif isinstance(obj, list): for idx, value in enumerate(obj): to_process.append((value, f"{obj_path}[{idx}]")) else: invalid[obj_path] = obj return invalid
"""Test the AlarmDecoder config flow.""" from alarmdecoder.util import NoDeviceError import pytest from homeassistant import config_entries, data_entry_flow from homeassistant.components.alarmdecoder import config_flow from homeassistant.components.alarmdecoder.const import ( CONF_ALT_NIGHT_MODE, CONF_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED, CONF_DEVICE_BAUD, CONF_DEVICE_PATH, CONF_RELAY_ADDR, CONF_RELAY_CHAN, CONF_ZONE_LOOP, CONF_ZONE_NAME, CONF_ZONE_NUMBER, CONF_ZONE_RFID, CONF_ZONE_TYPE, DEFAULT_ARM_OPTIONS, DEFAULT_ZONE_OPTIONS, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) from homeassistant.components.binary_sensor import DEVICE_CLASS_WINDOW from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import HomeAssistant from tests.async_mock import patch from tests.common import MockConfigEntry @pytest.mark.parametrize( "protocol,connection,title", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, "alarmdecoder123:10001", ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, "/dev/ttyUSB123", ), ], ) async def test_setups(hass: HomeAssistant, protocol, connection, title): """Test flow for setting up the available AlarmDecoder protocols.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch("homeassistant.components.alarmdecoder.config_flow.AdExt.open"), patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.close" ), patch( "homeassistant.components.alarmdecoder.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == title assert result["data"] == { **connection, CONF_PROTOCOL: protocol, } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 async def test_setup_connection_error(hass: HomeAssistant): """Test flow for setup with a connection error.""" port = 1001 host = "alarmdecoder" protocol = PROTOCOL_SOCKET connection_settings = {CONF_HOST: host, CONF_PORT: port} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" with patch( "homeassistant.components.alarmdecoder.config_flow.AdExt.open", side_effect=NoDeviceError, ), patch("homeassistant.components.alarmdecoder.config_flow.AdExt.close"): result = await hass.config_entries.flow.async_configure( result["flow_id"], connection_settings ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["errors"] == {"base": "service_unavailable"} async def test_options_arm_flow(hass: HomeAssistant): """Test arm options flow.""" user_input = { CONF_ALT_NIGHT_MODE: True, CONF_AUTO_BYPASS: True, CONF_CODE_ARM_REQUIRED: True, } entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Arming Settings"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "arm_settings" with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=user_input, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: user_input, OPTIONS_ZONES: DEFAULT_ZONE_OPTIONS, } async def test_options_zone_flow(hass: HomeAssistant): """Test options flow for adding/deleting zones.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input=zone_settings, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {zone_number: zone_settings}, } # Make sure zone can be removed... result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: {}, } async def test_options_zone_flow_validation(hass: HomeAssistant): """Test input validation for zone options flow.""" zone_number = "2" zone_settings = {CONF_ZONE_NAME: "Front Entry", CONF_ZONE_TYPE: DEVICE_CLASS_WINDOW} entry = MockConfigEntry(domain=DOMAIN) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={"edit_selection": "Zones"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" # Zone Number must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: "asd"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_select" assert result["errors"] == {CONF_ZONE_NUMBER: "int"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={CONF_ZONE_NUMBER: zone_number}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_CHAN: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {"base": "relay_inclusive"} # CONF_RELAY_ADDR, CONF_RELAY_CHAN must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_RELAY_ADDR: "abc", CONF_RELAY_CHAN: "abc"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == { CONF_RELAY_ADDR: "int", CONF_RELAY_CHAN: "int", } # CONF_ZONE_LOOP depends on CONF_ZONE_RFID result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_LOOP: "1"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_rfid"} # CONF_ZONE_LOOP must be int result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "ab"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "int"} # CONF_ZONE_LOOP must be between [1,4] result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={**zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "5"}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "zone_details" assert result["errors"] == {CONF_ZONE_LOOP: "loop_range"} # All valid settings with patch( "homeassistant.components.alarmdecoder.async_setup_entry", return_value=True ): result = await hass.config_entries.options.async_configure( result["flow_id"], user_input={ **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: "2", CONF_RELAY_ADDR: "12", CONF_RELAY_CHAN: "1", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert entry.options == { OPTIONS_ARM: DEFAULT_ARM_OPTIONS, OPTIONS_ZONES: { zone_number: { **zone_settings, CONF_ZONE_RFID: "rfid123", CONF_ZONE_LOOP: 2, CONF_RELAY_ADDR: 12, CONF_RELAY_CHAN: 1, } }, } @pytest.mark.parametrize( "protocol,connection", [ ( PROTOCOL_SOCKET, { CONF_HOST: "alarmdecoder123", CONF_PORT: 10001, }, ), ( PROTOCOL_SERIAL, { CONF_DEVICE_PATH: "/dev/ttyUSB123", CONF_DEVICE_BAUD: 115000, }, ), ], ) async def test_one_device_allowed(hass, protocol, connection): """Test that only one AlarmDecoder device is allowed.""" flow = config_flow.AlarmDecoderFlowHandler() flow.hass = hass MockConfigEntry( domain=DOMAIN, data=connection, ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PROTOCOL: protocol}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "protocol" result = await hass.config_entries.flow.async_configure( result["flow_id"], connection ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
tchellomello/home-assistant
tests/components/alarmdecoder/test_config_flow.py
homeassistant/util/json.py