input
stringlengths
53
297k
output
stringclasses
604 values
repo_name
stringclasses
376 values
test_path
stringclasses
583 values
code_path
stringlengths
7
116
"""Config flow for DialogFlow.""" from homeassistant.helpers import config_entry_flow from .const import DOMAIN config_entry_flow.register_webhook_flow( DOMAIN, "Dialogflow Webhook", { "dialogflow_url": "https://dialogflow.com/docs/fulfillment#webhook", "docs_url": "https://www.home-assistant.io/integrations/dialogflow/", }, )
"""Test Hue init with multiple bridges.""" from aiohue.groups import Groups from aiohue.lights import Lights from aiohue.scenes import Scenes from aiohue.sensors import Sensors import pytest from homeassistant import config_entries from homeassistant.components import hue from homeassistant.components.hue import sensor_base as hue_sensor_base from homeassistant.setup import async_setup_component from tests.async_mock import Mock, patch async def setup_component(hass): """Hue component.""" with patch.object(hue, "async_setup_entry", return_value=True): assert ( await async_setup_component( hass, hue.DOMAIN, {}, ) is True ) async def test_hue_activate_scene_both_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes both bridges successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) mock_hue_activate_scene1.assert_called_once() mock_hue_activate_scene2.assert_called_once() async def test_hue_activate_scene_one_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes only one bridge successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) mock_hue_activate_scene1.assert_called_once() mock_hue_activate_scene2.assert_called_once() async def test_hue_activate_scene_zero_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes no bridge successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) # both were retried assert mock_hue_activate_scene1.call_count == 2 assert mock_hue_activate_scene2.call_count == 2 async def setup_bridge(hass, mock_bridge, config_entry): """Load the Hue light platform with the provided bridge.""" mock_bridge.config_entry = config_entry hass.data[hue.DOMAIN][config_entry.entry_id] = mock_bridge await hass.config_entries.async_forward_entry_setup(config_entry, "light") # To flush out the service call to update the group await hass.async_block_till_done() @pytest.fixture def mock_config_entry1(hass): """Mock a config entry.""" return create_config_entry() @pytest.fixture def mock_config_entry2(hass): """Mock a config entry.""" return create_config_entry() def create_config_entry(): """Mock a config entry.""" return config_entries.ConfigEntry( 1, hue.DOMAIN, "Mock Title", {"host": "mock-host"}, "test", config_entries.CONN_CLASS_LOCAL_POLL, system_options={}, ) @pytest.fixture def mock_bridge1(hass): """Mock a Hue bridge.""" return create_mock_bridge(hass) @pytest.fixture def mock_bridge2(hass): """Mock a Hue bridge.""" return create_mock_bridge(hass) def create_mock_bridge(hass): """Create a mock Hue bridge.""" bridge = Mock( hass=hass, available=True, authorized=True, allow_unreachable=False, allow_groups=False, api=Mock(), reset_jobs=[], spec=hue.HueBridge, ) bridge.sensor_manager = hue_sensor_base.SensorManager(bridge) bridge.mock_requests = [] async def mock_request(method, path, **kwargs): kwargs["method"] = method kwargs["path"] = path bridge.mock_requests.append(kwargs) return {} async def async_request_call(task): await task() bridge.async_request_call = async_request_call bridge.api.config.apiversion = "9.9.9" bridge.api.lights = Lights({}, mock_request) bridge.api.groups = Groups({}, mock_request) bridge.api.sensors = Sensors({}, mock_request) bridge.api.scenes = Scenes({}, mock_request) return bridge
mezz64/home-assistant
tests/components/hue/test_init_multiple_bridges.py
homeassistant/components/dialogflow/config_flow.py
"""Support for the DirecTV receivers.""" import logging from typing import Callable, List, Optional from directv import DIRECTV from homeassistant.components.media_player import ( DEVICE_CLASS_RECEIVER, MediaPlayerEntity, ) from homeassistant.components.media_player.const import ( MEDIA_TYPE_CHANNEL, MEDIA_TYPE_MOVIE, MEDIA_TYPE_MUSIC, MEDIA_TYPE_TVSHOW, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PLAY, SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK, SUPPORT_STOP, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import STATE_OFF, STATE_PAUSED, STATE_PLAYING from homeassistant.helpers.typing import HomeAssistantType from homeassistant.util import dt as dt_util from . import DIRECTVEntity from .const import ( ATTR_MEDIA_CURRENTLY_RECORDING, ATTR_MEDIA_RATING, ATTR_MEDIA_RECORDED, ATTR_MEDIA_START_TIME, DOMAIN, ) _LOGGER = logging.getLogger(__name__) KNOWN_MEDIA_TYPES = [MEDIA_TYPE_MOVIE, MEDIA_TYPE_MUSIC, MEDIA_TYPE_TVSHOW] SUPPORT_DTV = ( SUPPORT_PAUSE | SUPPORT_TURN_ON | SUPPORT_TURN_OFF | SUPPORT_PLAY_MEDIA | SUPPORT_STOP | SUPPORT_NEXT_TRACK | SUPPORT_PREVIOUS_TRACK | SUPPORT_PLAY ) SUPPORT_DTV_CLIENT = ( SUPPORT_PAUSE | SUPPORT_PLAY_MEDIA | SUPPORT_STOP | SUPPORT_NEXT_TRACK | SUPPORT_PREVIOUS_TRACK | SUPPORT_PLAY ) async def async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities: Callable[[List, bool], None], ) -> bool: """Set up the DirecTV config entry.""" dtv = hass.data[DOMAIN][entry.entry_id] entities = [] for location in dtv.device.locations: entities.append( DIRECTVMediaPlayer( dtv=dtv, name=str.title(location.name), address=location.address, ) ) async_add_entities(entities, True) class DIRECTVMediaPlayer(DIRECTVEntity, MediaPlayerEntity): """Representation of a DirecTV receiver on the network.""" def __init__(self, *, dtv: DIRECTV, name: str, address: str = "0") -> None: """Initialize DirecTV media player.""" super().__init__( dtv=dtv, name=name, address=address, ) self._assumed_state = None self._available = False self._is_recorded = None self._is_standby = True self._last_position = None self._last_update = None self._paused = None self._program = None self._state = None async def async_update(self): """Retrieve latest state.""" self._state = await self.dtv.state(self._address) self._available = self._state.available self._is_standby = self._state.standby self._program = self._state.program if self._is_standby: self._assumed_state = False self._is_recorded = None self._last_position = None self._last_update = None self._paused = None elif self._program is not None: self._paused = self._last_position == self._program.position self._is_recorded = self._program.recorded self._last_position = self._program.position self._last_update = self._state.at self._assumed_state = self._is_recorded @property def device_state_attributes(self): """Return device specific state attributes.""" if self._is_standby: return {} return { ATTR_MEDIA_CURRENTLY_RECORDING: self.media_currently_recording, ATTR_MEDIA_RATING: self.media_rating, ATTR_MEDIA_RECORDED: self.media_recorded, ATTR_MEDIA_START_TIME: self.media_start_time, } @property def name(self): """Return the name of the device.""" return self._name @property def device_class(self) -> Optional[str]: """Return the class of this device.""" return DEVICE_CLASS_RECEIVER @property def unique_id(self): """Return a unique ID to use for this media player.""" if self._address == "0": return self.dtv.device.info.receiver_id return self._address # MediaPlayerEntity properties and methods @property def state(self): """Return the state of the device.""" if self._is_standby: return STATE_OFF # For recorded media we can determine if it is paused or not. # For live media we're unable to determine and will always return # playing instead. if self._paused: return STATE_PAUSED return STATE_PLAYING @property def available(self): """Return if able to retrieve information from DVR or not.""" return self._available @property def assumed_state(self): """Return if we assume the state or not.""" return self._assumed_state @property def media_content_id(self): """Return the content ID of current playing media.""" if self._is_standby or self._program is None: return None return self._program.program_id @property def media_content_type(self): """Return the content type of current playing media.""" if self._is_standby or self._program is None: return None if self._program.program_type in KNOWN_MEDIA_TYPES: return self._program.program_type return MEDIA_TYPE_MOVIE @property def media_duration(self): """Return the duration of current playing media in seconds.""" if self._is_standby or self._program is None: return None return self._program.duration @property def media_position(self): """Position of current playing media in seconds.""" if self._is_standby: return None return self._last_position @property def media_position_updated_at(self): """When was the position of the current playing media valid.""" if self._is_standby: return None return self._last_update @property def media_title(self): """Return the title of current playing media.""" if self._is_standby or self._program is None: return None if self.media_content_type == MEDIA_TYPE_MUSIC: return self._program.music_title return self._program.title @property def media_artist(self): """Artist of current playing media, music track only.""" if self._is_standby or self._program is None: return None return self._program.music_artist @property def media_album_name(self): """Album name of current playing media, music track only.""" if self._is_standby or self._program is None: return None return self._program.music_album @property def media_series_title(self): """Return the title of current episode of TV show.""" if self._is_standby or self._program is None: return None return self._program.episode_title @property def media_channel(self): """Return the channel current playing media.""" if self._is_standby or self._program is None: return None return f"{self._program.channel_name} ({self._program.channel})" @property def source(self): """Name of the current input source.""" if self._is_standby or self._program is None: return None return self._program.channel @property def supported_features(self): """Flag media player features that are supported.""" return SUPPORT_DTV_CLIENT if self._is_client else SUPPORT_DTV @property def media_currently_recording(self): """If the media is currently being recorded or not.""" if self._is_standby or self._program is None: return None return self._program.recording @property def media_rating(self): """TV Rating of the current playing media.""" if self._is_standby or self._program is None: return None return self._program.rating @property def media_recorded(self): """If the media was recorded or live.""" if self._is_standby: return None return self._is_recorded @property def media_start_time(self): """Start time the program aired.""" if self._is_standby or self._program is None: return None return dt_util.as_local(self._program.start_time) async def async_turn_on(self): """Turn on the receiver.""" if self._is_client: raise NotImplementedError() _LOGGER.debug("Turn on %s", self._name) await self.dtv.remote("poweron", self._address) async def async_turn_off(self): """Turn off the receiver.""" if self._is_client: raise NotImplementedError() _LOGGER.debug("Turn off %s", self._name) await self.dtv.remote("poweroff", self._address) async def async_media_play(self): """Send play command.""" _LOGGER.debug("Play on %s", self._name) await self.dtv.remote("play", self._address) async def async_media_pause(self): """Send pause command.""" _LOGGER.debug("Pause on %s", self._name) await self.dtv.remote("pause", self._address) async def async_media_stop(self): """Send stop command.""" _LOGGER.debug("Stop on %s", self._name) await self.dtv.remote("stop", self._address) async def async_media_previous_track(self): """Send rewind command.""" _LOGGER.debug("Rewind on %s", self._name) await self.dtv.remote("rew", self._address) async def async_media_next_track(self): """Send fast forward command.""" _LOGGER.debug("Fast forward on %s", self._name) await self.dtv.remote("ffwd", self._address) async def async_play_media(self, media_type, media_id, **kwargs): """Select input source.""" if media_type != MEDIA_TYPE_CHANNEL: _LOGGER.error( "Invalid media type %s. Only %s is supported", media_type, MEDIA_TYPE_CHANNEL, ) return _LOGGER.debug("Changing channel on %s to %s", self._name, media_id) await self.dtv.tune(media_id, self._address)
"""Test Hue init with multiple bridges.""" from aiohue.groups import Groups from aiohue.lights import Lights from aiohue.scenes import Scenes from aiohue.sensors import Sensors import pytest from homeassistant import config_entries from homeassistant.components import hue from homeassistant.components.hue import sensor_base as hue_sensor_base from homeassistant.setup import async_setup_component from tests.async_mock import Mock, patch async def setup_component(hass): """Hue component.""" with patch.object(hue, "async_setup_entry", return_value=True): assert ( await async_setup_component( hass, hue.DOMAIN, {}, ) is True ) async def test_hue_activate_scene_both_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes both bridges successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) mock_hue_activate_scene1.assert_called_once() mock_hue_activate_scene2.assert_called_once() async def test_hue_activate_scene_one_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes only one bridge successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) mock_hue_activate_scene1.assert_called_once() mock_hue_activate_scene2.assert_called_once() async def test_hue_activate_scene_zero_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes no bridge successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) # both were retried assert mock_hue_activate_scene1.call_count == 2 assert mock_hue_activate_scene2.call_count == 2 async def setup_bridge(hass, mock_bridge, config_entry): """Load the Hue light platform with the provided bridge.""" mock_bridge.config_entry = config_entry hass.data[hue.DOMAIN][config_entry.entry_id] = mock_bridge await hass.config_entries.async_forward_entry_setup(config_entry, "light") # To flush out the service call to update the group await hass.async_block_till_done() @pytest.fixture def mock_config_entry1(hass): """Mock a config entry.""" return create_config_entry() @pytest.fixture def mock_config_entry2(hass): """Mock a config entry.""" return create_config_entry() def create_config_entry(): """Mock a config entry.""" return config_entries.ConfigEntry( 1, hue.DOMAIN, "Mock Title", {"host": "mock-host"}, "test", config_entries.CONN_CLASS_LOCAL_POLL, system_options={}, ) @pytest.fixture def mock_bridge1(hass): """Mock a Hue bridge.""" return create_mock_bridge(hass) @pytest.fixture def mock_bridge2(hass): """Mock a Hue bridge.""" return create_mock_bridge(hass) def create_mock_bridge(hass): """Create a mock Hue bridge.""" bridge = Mock( hass=hass, available=True, authorized=True, allow_unreachable=False, allow_groups=False, api=Mock(), reset_jobs=[], spec=hue.HueBridge, ) bridge.sensor_manager = hue_sensor_base.SensorManager(bridge) bridge.mock_requests = [] async def mock_request(method, path, **kwargs): kwargs["method"] = method kwargs["path"] = path bridge.mock_requests.append(kwargs) return {} async def async_request_call(task): await task() bridge.async_request_call = async_request_call bridge.api.config.apiversion = "9.9.9" bridge.api.lights = Lights({}, mock_request) bridge.api.groups = Groups({}, mock_request) bridge.api.sensors = Sensors({}, mock_request) bridge.api.scenes = Scenes({}, mock_request) return bridge
mezz64/home-assistant
tests/components/hue/test_init_multiple_bridges.py
homeassistant/components/directv/media_player.py
"""Component for interacting with the Yale Smart Alarm System API.""" import logging import voluptuous as vol from yalesmartalarmclient.client import ( YALE_STATE_ARM_FULL, YALE_STATE_ARM_PARTIAL, YALE_STATE_DISARM, AuthenticationError, YaleSmartAlarmClient, ) from homeassistant.components.alarm_control_panel import ( PLATFORM_SCHEMA, AlarmControlPanelEntity, ) from homeassistant.components.alarm_control_panel.const import ( SUPPORT_ALARM_ARM_AWAY, SUPPORT_ALARM_ARM_HOME, ) from homeassistant.const import ( CONF_NAME, CONF_PASSWORD, CONF_USERNAME, STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, STATE_ALARM_DISARMED, ) import homeassistant.helpers.config_validation as cv CONF_AREA_ID = "area_id" DEFAULT_NAME = "Yale Smart Alarm" DEFAULT_AREA_ID = "1" _LOGGER = logging.getLogger(__name__) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_AREA_ID, default=DEFAULT_AREA_ID): cv.string, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the alarm platform.""" name = config[CONF_NAME] username = config[CONF_USERNAME] password = config[CONF_PASSWORD] area_id = config[CONF_AREA_ID] try: client = YaleSmartAlarmClient(username, password, area_id) except AuthenticationError: _LOGGER.error("Authentication failed. Check credentials") return add_entities([YaleAlarmDevice(name, client)], True) class YaleAlarmDevice(AlarmControlPanelEntity): """Represent a Yale Smart Alarm.""" def __init__(self, name, client): """Initialize the Yale Alarm Device.""" self._name = name self._client = client self._state = None self._state_map = { YALE_STATE_DISARM: STATE_ALARM_DISARMED, YALE_STATE_ARM_PARTIAL: STATE_ALARM_ARMED_HOME, YALE_STATE_ARM_FULL: STATE_ALARM_ARMED_AWAY, } @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 supported_features(self) -> int: """Return the list of supported features.""" return SUPPORT_ALARM_ARM_HOME | SUPPORT_ALARM_ARM_AWAY def update(self): """Return the state of the device.""" armed_status = self._client.get_armed_status() self._state = self._state_map.get(armed_status) def alarm_disarm(self, code=None): """Send disarm command.""" self._client.disarm() def alarm_arm_home(self, code=None): """Send arm home command.""" self._client.arm_partial() def alarm_arm_away(self, code=None): """Send arm away command.""" self._client.arm_full()
"""Test Hue init with multiple bridges.""" from aiohue.groups import Groups from aiohue.lights import Lights from aiohue.scenes import Scenes from aiohue.sensors import Sensors import pytest from homeassistant import config_entries from homeassistant.components import hue from homeassistant.components.hue import sensor_base as hue_sensor_base from homeassistant.setup import async_setup_component from tests.async_mock import Mock, patch async def setup_component(hass): """Hue component.""" with patch.object(hue, "async_setup_entry", return_value=True): assert ( await async_setup_component( hass, hue.DOMAIN, {}, ) is True ) async def test_hue_activate_scene_both_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes both bridges successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) mock_hue_activate_scene1.assert_called_once() mock_hue_activate_scene2.assert_called_once() async def test_hue_activate_scene_one_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes only one bridge successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) mock_hue_activate_scene1.assert_called_once() mock_hue_activate_scene2.assert_called_once() async def test_hue_activate_scene_zero_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes no bridge successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) # both were retried assert mock_hue_activate_scene1.call_count == 2 assert mock_hue_activate_scene2.call_count == 2 async def setup_bridge(hass, mock_bridge, config_entry): """Load the Hue light platform with the provided bridge.""" mock_bridge.config_entry = config_entry hass.data[hue.DOMAIN][config_entry.entry_id] = mock_bridge await hass.config_entries.async_forward_entry_setup(config_entry, "light") # To flush out the service call to update the group await hass.async_block_till_done() @pytest.fixture def mock_config_entry1(hass): """Mock a config entry.""" return create_config_entry() @pytest.fixture def mock_config_entry2(hass): """Mock a config entry.""" return create_config_entry() def create_config_entry(): """Mock a config entry.""" return config_entries.ConfigEntry( 1, hue.DOMAIN, "Mock Title", {"host": "mock-host"}, "test", config_entries.CONN_CLASS_LOCAL_POLL, system_options={}, ) @pytest.fixture def mock_bridge1(hass): """Mock a Hue bridge.""" return create_mock_bridge(hass) @pytest.fixture def mock_bridge2(hass): """Mock a Hue bridge.""" return create_mock_bridge(hass) def create_mock_bridge(hass): """Create a mock Hue bridge.""" bridge = Mock( hass=hass, available=True, authorized=True, allow_unreachable=False, allow_groups=False, api=Mock(), reset_jobs=[], spec=hue.HueBridge, ) bridge.sensor_manager = hue_sensor_base.SensorManager(bridge) bridge.mock_requests = [] async def mock_request(method, path, **kwargs): kwargs["method"] = method kwargs["path"] = path bridge.mock_requests.append(kwargs) return {} async def async_request_call(task): await task() bridge.async_request_call = async_request_call bridge.api.config.apiversion = "9.9.9" bridge.api.lights = Lights({}, mock_request) bridge.api.groups = Groups({}, mock_request) bridge.api.sensors = Sensors({}, mock_request) bridge.api.scenes = Scenes({}, mock_request) return bridge
mezz64/home-assistant
tests/components/hue/test_init_multiple_bridges.py
homeassistant/components/yale_smart_alarm/alarm_control_panel.py
"""Support for LCN climate control.""" import pypck from homeassistant.components.climate import ClimateEntity, const from homeassistant.const import ATTR_TEMPERATURE, CONF_ADDRESS, CONF_UNIT_OF_MEASUREMENT from . import LcnDevice from .const import ( CONF_CONNECTIONS, CONF_LOCKABLE, CONF_MAX_TEMP, CONF_MIN_TEMP, CONF_SETPOINT, CONF_SOURCE, DATA_LCN, ) from .helpers import get_connection async def async_setup_platform( hass, hass_config, async_add_entities, discovery_info=None ): """Set up the LCN climate 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) devices.append(LcnClimate(config, address_connection)) async_add_entities(devices) class LcnClimate(LcnDevice, ClimateEntity): """Representation of a LCN climate device.""" def __init__(self, config, address_connection): """Initialize of a LCN climate device.""" super().__init__(config, address_connection) self.variable = pypck.lcn_defs.Var[config[CONF_SOURCE]] self.setpoint = pypck.lcn_defs.Var[config[CONF_SETPOINT]] self.unit = pypck.lcn_defs.VarUnit.parse(config[CONF_UNIT_OF_MEASUREMENT]) self.regulator_id = pypck.lcn_defs.Var.to_set_point_id(self.setpoint) self.is_lockable = config[CONF_LOCKABLE] self._max_temp = config[CONF_MAX_TEMP] self._min_temp = config[CONF_MIN_TEMP] self._current_temperature = None self._target_temperature = None 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.variable) await self.address_connection.activate_status_request_handler(self.setpoint) @property def supported_features(self): """Return the list of supported features.""" return const.SUPPORT_TARGET_TEMPERATURE @property def temperature_unit(self): """Return the unit of measurement.""" return self.unit.value @property def current_temperature(self): """Return the current temperature.""" return self._current_temperature @property def target_temperature(self): """Return the temperature we try to reach.""" return self._target_temperature @property def hvac_mode(self): """Return hvac operation ie. heat, cool mode. Need to be one of HVAC_MODE_*. """ if self._is_on: return const.HVAC_MODE_HEAT return const.HVAC_MODE_OFF @property def hvac_modes(self): """Return the list of available hvac operation modes. Need to be a subset of HVAC_MODES. """ modes = [const.HVAC_MODE_HEAT] if self.is_lockable: modes.append(const.HVAC_MODE_OFF) return modes @property def max_temp(self): """Return the maximum temperature.""" return self._max_temp @property def min_temp(self): """Return the minimum temperature.""" return self._min_temp async def async_set_hvac_mode(self, hvac_mode): """Set new target hvac mode.""" if hvac_mode == const.HVAC_MODE_HEAT: self._is_on = True self.address_connection.lock_regulator(self.regulator_id, False) elif hvac_mode == const.HVAC_MODE_OFF: self._is_on = False self.address_connection.lock_regulator(self.regulator_id, True) self._target_temperature = None self.async_write_ha_state() async def async_set_temperature(self, **kwargs): """Set new target temperature.""" temperature = kwargs.get(ATTR_TEMPERATURE) if temperature is None: return self._target_temperature = temperature self.address_connection.var_abs( self.setpoint, self._target_temperature, self.unit ) self.async_write_ha_state() def input_received(self, input_obj): """Set temperature value when LCN input object is received.""" if not isinstance(input_obj, pypck.inputs.ModStatusVar): return if input_obj.get_var() == self.variable: self._current_temperature = input_obj.get_value().to_var_unit(self.unit) elif input_obj.get_var() == self.setpoint: self._is_on = not input_obj.get_value().is_locked_regulator() if self._is_on: self._target_temperature = input_obj.get_value().to_var_unit(self.unit) self.async_write_ha_state()
"""Test Hue init with multiple bridges.""" from aiohue.groups import Groups from aiohue.lights import Lights from aiohue.scenes import Scenes from aiohue.sensors import Sensors import pytest from homeassistant import config_entries from homeassistant.components import hue from homeassistant.components.hue import sensor_base as hue_sensor_base from homeassistant.setup import async_setup_component from tests.async_mock import Mock, patch async def setup_component(hass): """Hue component.""" with patch.object(hue, "async_setup_entry", return_value=True): assert ( await async_setup_component( hass, hue.DOMAIN, {}, ) is True ) async def test_hue_activate_scene_both_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes both bridges successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) mock_hue_activate_scene1.assert_called_once() mock_hue_activate_scene2.assert_called_once() async def test_hue_activate_scene_one_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes only one bridge successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) mock_hue_activate_scene1.assert_called_once() mock_hue_activate_scene2.assert_called_once() async def test_hue_activate_scene_zero_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes no bridge successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) # both were retried assert mock_hue_activate_scene1.call_count == 2 assert mock_hue_activate_scene2.call_count == 2 async def setup_bridge(hass, mock_bridge, config_entry): """Load the Hue light platform with the provided bridge.""" mock_bridge.config_entry = config_entry hass.data[hue.DOMAIN][config_entry.entry_id] = mock_bridge await hass.config_entries.async_forward_entry_setup(config_entry, "light") # To flush out the service call to update the group await hass.async_block_till_done() @pytest.fixture def mock_config_entry1(hass): """Mock a config entry.""" return create_config_entry() @pytest.fixture def mock_config_entry2(hass): """Mock a config entry.""" return create_config_entry() def create_config_entry(): """Mock a config entry.""" return config_entries.ConfigEntry( 1, hue.DOMAIN, "Mock Title", {"host": "mock-host"}, "test", config_entries.CONN_CLASS_LOCAL_POLL, system_options={}, ) @pytest.fixture def mock_bridge1(hass): """Mock a Hue bridge.""" return create_mock_bridge(hass) @pytest.fixture def mock_bridge2(hass): """Mock a Hue bridge.""" return create_mock_bridge(hass) def create_mock_bridge(hass): """Create a mock Hue bridge.""" bridge = Mock( hass=hass, available=True, authorized=True, allow_unreachable=False, allow_groups=False, api=Mock(), reset_jobs=[], spec=hue.HueBridge, ) bridge.sensor_manager = hue_sensor_base.SensorManager(bridge) bridge.mock_requests = [] async def mock_request(method, path, **kwargs): kwargs["method"] = method kwargs["path"] = path bridge.mock_requests.append(kwargs) return {} async def async_request_call(task): await task() bridge.async_request_call = async_request_call bridge.api.config.apiversion = "9.9.9" bridge.api.lights = Lights({}, mock_request) bridge.api.groups = Groups({}, mock_request) bridge.api.sensors = Sensors({}, mock_request) bridge.api.scenes = Scenes({}, mock_request) return bridge
mezz64/home-assistant
tests/components/hue/test_init_multiple_bridges.py
homeassistant/components/lcn/climate.py
"""Support for Apple TV media player.""" import logging import pyatv.const as atv_const from homeassistant.components.media_player import MediaPlayerEntity from homeassistant.components.media_player.const import ( MEDIA_TYPE_MUSIC, MEDIA_TYPE_TVSHOW, MEDIA_TYPE_VIDEO, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PLAY, SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK, SUPPORT_SEEK, SUPPORT_STOP, SUPPORT_TURN_OFF, SUPPORT_TURN_ON, ) from homeassistant.const import ( CONF_HOST, CONF_NAME, EVENT_HOMEASSISTANT_STOP, STATE_IDLE, STATE_OFF, STATE_PAUSED, STATE_PLAYING, STATE_STANDBY, ) from homeassistant.core import callback import homeassistant.util.dt as dt_util from . import ATTR_ATV, ATTR_POWER, DATA_APPLE_TV, DATA_ENTITIES _LOGGER = logging.getLogger(__name__) SUPPORT_APPLE_TV = ( SUPPORT_TURN_ON | SUPPORT_TURN_OFF | SUPPORT_PLAY_MEDIA | SUPPORT_PAUSE | SUPPORT_PLAY | SUPPORT_SEEK | SUPPORT_STOP | SUPPORT_NEXT_TRACK | SUPPORT_PREVIOUS_TRACK ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the Apple TV platform.""" if not discovery_info: return # Manage entity cache for service handler if DATA_ENTITIES not in hass.data: hass.data[DATA_ENTITIES] = [] name = discovery_info[CONF_NAME] host = discovery_info[CONF_HOST] atv = hass.data[DATA_APPLE_TV][host][ATTR_ATV] power = hass.data[DATA_APPLE_TV][host][ATTR_POWER] entity = AppleTvDevice(atv, name, power) @callback def on_hass_stop(event): """Stop push updates when hass stops.""" atv.push_updater.stop() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, on_hass_stop) if entity not in hass.data[DATA_ENTITIES]: hass.data[DATA_ENTITIES].append(entity) async_add_entities([entity]) class AppleTvDevice(MediaPlayerEntity): """Representation of an Apple TV device.""" def __init__(self, atv, name, power): """Initialize the Apple TV device.""" self.atv = atv self._name = name self._playing = None self._power = power self._power.listeners.append(self) self.atv.push_updater.listener = self async def async_added_to_hass(self): """Handle when an entity is about to be added to Home Assistant.""" self._power.init() @property def name(self): """Return the name of the device.""" return self._name @property def unique_id(self): """Return a unique ID.""" return self.atv.metadata.device_id @property def should_poll(self): """No polling needed.""" return False @property def state(self): """Return the state of the device.""" if not self._power.turned_on: return STATE_OFF if self._playing: state = self._playing.play_state if state in ( atv_const.PLAY_STATE_IDLE, atv_const.PLAY_STATE_NO_MEDIA, atv_const.PLAY_STATE_LOADING, ): return STATE_IDLE if state == atv_const.PLAY_STATE_PLAYING: return STATE_PLAYING if state in ( atv_const.PLAY_STATE_PAUSED, atv_const.PLAY_STATE_FAST_FORWARD, atv_const.PLAY_STATE_FAST_BACKWARD, atv_const.PLAY_STATE_STOPPED, ): # Catch fast forward/backward here so "play" is default action return STATE_PAUSED return STATE_STANDBY # Bad or unknown state? @callback def playstatus_update(self, updater, playing): """Print what is currently playing when it changes.""" self._playing = playing self.async_write_ha_state() @callback def playstatus_error(self, updater, exception): """Inform about an error and restart push updates.""" _LOGGER.warning("A %s error occurred: %s", exception.__class__, exception) # This will wait 10 seconds before restarting push updates. If the # connection continues to fail, it will flood the log (every 10 # seconds) until it succeeds. A better approach should probably be # implemented here later. updater.start(initial_delay=10) self._playing = None self.async_write_ha_state() @property def media_content_type(self): """Content type of current playing media.""" if self._playing: media_type = self._playing.media_type if media_type == atv_const.MEDIA_TYPE_VIDEO: return MEDIA_TYPE_VIDEO if media_type == atv_const.MEDIA_TYPE_MUSIC: return MEDIA_TYPE_MUSIC if media_type == atv_const.MEDIA_TYPE_TV: return MEDIA_TYPE_TVSHOW @property def media_duration(self): """Duration of current playing media in seconds.""" if self._playing: return self._playing.total_time @property def media_position(self): """Position of current playing media in seconds.""" if self._playing: return self._playing.position @property def media_position_updated_at(self): """Last valid time of media position.""" state = self.state if state in (STATE_PLAYING, STATE_PAUSED): return dt_util.utcnow() async def async_play_media(self, media_type, media_id, **kwargs): """Send the play_media command to the media player.""" await self.atv.airplay.play_url(media_id) @property def media_image_hash(self): """Hash value for media image.""" state = self.state if self._playing and state not in [STATE_OFF, STATE_IDLE]: return self._playing.hash async def async_get_media_image(self): """Fetch media image of current playing image.""" state = self.state if self._playing and state not in [STATE_OFF, STATE_IDLE]: return (await self.atv.metadata.artwork()), "image/png" return None, None @property def media_title(self): """Title of current playing media.""" if self._playing: if self.state == STATE_IDLE: return "Nothing playing" title = self._playing.title return title if title else "No title" return f"Establishing a connection to {self._name}..." @property def supported_features(self): """Flag media player features that are supported.""" return SUPPORT_APPLE_TV async def async_turn_on(self): """Turn the media player on.""" self._power.set_power_on(True) async def async_turn_off(self): """Turn the media player off.""" self._playing = None self._power.set_power_on(False) async def async_media_play_pause(self): """Pause media on media player.""" if not self._playing: return state = self.state if state == STATE_PAUSED: await self.atv.remote_control.play() elif state == STATE_PLAYING: await self.atv.remote_control.pause() async def async_media_play(self): """Play media.""" if self._playing: await self.atv.remote_control.play() async def async_media_stop(self): """Stop the media player.""" if self._playing: await self.atv.remote_control.stop() async def async_media_pause(self): """Pause the media player.""" if self._playing: await self.atv.remote_control.pause() async def async_media_next_track(self): """Send next track command.""" if self._playing: await self.atv.remote_control.next() async def async_media_previous_track(self): """Send previous track command.""" if self._playing: await self.atv.remote_control.previous() async def async_media_seek(self, position): """Send seek command.""" if self._playing: await self.atv.remote_control.set_position(position)
"""Test Hue init with multiple bridges.""" from aiohue.groups import Groups from aiohue.lights import Lights from aiohue.scenes import Scenes from aiohue.sensors import Sensors import pytest from homeassistant import config_entries from homeassistant.components import hue from homeassistant.components.hue import sensor_base as hue_sensor_base from homeassistant.setup import async_setup_component from tests.async_mock import Mock, patch async def setup_component(hass): """Hue component.""" with patch.object(hue, "async_setup_entry", return_value=True): assert ( await async_setup_component( hass, hue.DOMAIN, {}, ) is True ) async def test_hue_activate_scene_both_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes both bridges successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) mock_hue_activate_scene1.assert_called_once() mock_hue_activate_scene2.assert_called_once() async def test_hue_activate_scene_one_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes only one bridge successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) mock_hue_activate_scene1.assert_called_once() mock_hue_activate_scene2.assert_called_once() async def test_hue_activate_scene_zero_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes no bridge successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) # both were retried assert mock_hue_activate_scene1.call_count == 2 assert mock_hue_activate_scene2.call_count == 2 async def setup_bridge(hass, mock_bridge, config_entry): """Load the Hue light platform with the provided bridge.""" mock_bridge.config_entry = config_entry hass.data[hue.DOMAIN][config_entry.entry_id] = mock_bridge await hass.config_entries.async_forward_entry_setup(config_entry, "light") # To flush out the service call to update the group await hass.async_block_till_done() @pytest.fixture def mock_config_entry1(hass): """Mock a config entry.""" return create_config_entry() @pytest.fixture def mock_config_entry2(hass): """Mock a config entry.""" return create_config_entry() def create_config_entry(): """Mock a config entry.""" return config_entries.ConfigEntry( 1, hue.DOMAIN, "Mock Title", {"host": "mock-host"}, "test", config_entries.CONN_CLASS_LOCAL_POLL, system_options={}, ) @pytest.fixture def mock_bridge1(hass): """Mock a Hue bridge.""" return create_mock_bridge(hass) @pytest.fixture def mock_bridge2(hass): """Mock a Hue bridge.""" return create_mock_bridge(hass) def create_mock_bridge(hass): """Create a mock Hue bridge.""" bridge = Mock( hass=hass, available=True, authorized=True, allow_unreachable=False, allow_groups=False, api=Mock(), reset_jobs=[], spec=hue.HueBridge, ) bridge.sensor_manager = hue_sensor_base.SensorManager(bridge) bridge.mock_requests = [] async def mock_request(method, path, **kwargs): kwargs["method"] = method kwargs["path"] = path bridge.mock_requests.append(kwargs) return {} async def async_request_call(task): await task() bridge.async_request_call = async_request_call bridge.api.config.apiversion = "9.9.9" bridge.api.lights = Lights({}, mock_request) bridge.api.groups = Groups({}, mock_request) bridge.api.sensors = Sensors({}, mock_request) bridge.api.scenes = Scenes({}, mock_request) return bridge
mezz64/home-assistant
tests/components/hue/test_init_multiple_bridges.py
homeassistant/components/apple_tv/media_player.py
"""Support for Sonarr sensors.""" from datetime import timedelta import logging from typing import Any, Callable, Dict, List, Optional from sonarr import Sonarr, SonarrConnectionError, SonarrError from homeassistant.config_entries import ConfigEntry from homeassistant.const import DATA_GIGABYTES from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity import Entity from homeassistant.helpers.typing import HomeAssistantType import homeassistant.util.dt as dt_util from . import SonarrEntity from .const import CONF_UPCOMING_DAYS, CONF_WANTED_MAX_ITEMS, DATA_SONARR, DOMAIN _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities: Callable[[List[Entity], bool], None], ) -> None: """Set up Sonarr sensors based on a config entry.""" options = entry.options sonarr = hass.data[DOMAIN][entry.entry_id][DATA_SONARR] entities = [ SonarrCommandsSensor(sonarr, entry.entry_id), SonarrDiskspaceSensor(sonarr, entry.entry_id), SonarrQueueSensor(sonarr, entry.entry_id), SonarrSeriesSensor(sonarr, entry.entry_id), SonarrUpcomingSensor(sonarr, entry.entry_id, days=options[CONF_UPCOMING_DAYS]), SonarrWantedSensor( sonarr, entry.entry_id, max_items=options[CONF_WANTED_MAX_ITEMS] ), ] async_add_entities(entities, True) def sonarr_exception_handler(func): """Decorate Sonarr calls to handle Sonarr exceptions. A decorator that wraps the passed in function, catches Sonarr errors, and handles the availability of the entity. """ async def handler(self, *args, **kwargs): try: await func(self, *args, **kwargs) self.last_update_success = True except SonarrConnectionError as error: if self.available: _LOGGER.error("Error communicating with API: %s", error) self.last_update_success = False except SonarrError as error: if self.available: _LOGGER.error("Invalid response from API: %s", error) self.last_update_success = False return handler class SonarrSensor(SonarrEntity): """Implementation of the Sonarr sensor.""" def __init__( self, *, sonarr: Sonarr, entry_id: str, enabled_default: bool = True, icon: str, key: str, name: str, unit_of_measurement: Optional[str] = None, ) -> None: """Initialize Sonarr sensor.""" self._unit_of_measurement = unit_of_measurement self._key = key self._unique_id = f"{entry_id}_{key}" self.last_update_success = False super().__init__( sonarr=sonarr, entry_id=entry_id, device_id=entry_id, name=name, icon=icon, enabled_default=enabled_default, ) @property def unique_id(self) -> str: """Return the unique ID for this sensor.""" return self._unique_id @property def available(self) -> bool: """Return sensor availability.""" return self.last_update_success @property def unit_of_measurement(self) -> str: """Return the unit this state is expressed in.""" return self._unit_of_measurement class SonarrCommandsSensor(SonarrSensor): """Defines a Sonarr Commands sensor.""" def __init__(self, sonarr: Sonarr, entry_id: str) -> None: """Initialize Sonarr Commands sensor.""" self._commands = [] super().__init__( sonarr=sonarr, entry_id=entry_id, icon="mdi:code-braces", key="commands", name=f"{sonarr.app.info.app_name} Commands", unit_of_measurement="Commands", enabled_default=False, ) @sonarr_exception_handler async def async_update(self) -> None: """Update entity.""" self._commands = await self.sonarr.commands() @property def device_state_attributes(self) -> Optional[Dict[str, Any]]: """Return the state attributes of the entity.""" attrs = {} for command in self._commands: attrs[command.name] = command.state return attrs @property def state(self) -> int: """Return the state of the sensor.""" return len(self._commands) class SonarrDiskspaceSensor(SonarrSensor): """Defines a Sonarr Disk Space sensor.""" def __init__(self, sonarr: Sonarr, entry_id: str) -> None: """Initialize Sonarr Disk Space sensor.""" self._disks = [] self._total_free = 0 super().__init__( sonarr=sonarr, entry_id=entry_id, icon="mdi:harddisk", key="diskspace", name=f"{sonarr.app.info.app_name} Disk Space", unit_of_measurement=DATA_GIGABYTES, enabled_default=False, ) @sonarr_exception_handler async def async_update(self) -> None: """Update entity.""" app = await self.sonarr.update() self._disks = app.disks self._total_free = sum([disk.free for disk in self._disks]) @property def device_state_attributes(self) -> Optional[Dict[str, Any]]: """Return the state attributes of the entity.""" attrs = {} for disk in self._disks: free = disk.free / 1024 ** 3 total = disk.total / 1024 ** 3 usage = free / total * 100 attrs[ disk.path ] = f"{free:.2f}/{total:.2f}{self._unit_of_measurement} ({usage:.2f}%)" return attrs @property def state(self) -> str: """Return the state of the sensor.""" free = self._total_free / 1024 ** 3 return f"{free:.2f}" class SonarrQueueSensor(SonarrSensor): """Defines a Sonarr Queue sensor.""" def __init__(self, sonarr: Sonarr, entry_id: str) -> None: """Initialize Sonarr Queue sensor.""" self._queue = [] super().__init__( sonarr=sonarr, entry_id=entry_id, icon="mdi:download", key="queue", name=f"{sonarr.app.info.app_name} Queue", unit_of_measurement="Episodes", enabled_default=False, ) @sonarr_exception_handler async def async_update(self) -> None: """Update entity.""" self._queue = await self.sonarr.queue() @property def device_state_attributes(self) -> Optional[Dict[str, Any]]: """Return the state attributes of the entity.""" attrs = {} for item in self._queue: remaining = 1 if item.size == 0 else item.size_remaining / item.size remaining_pct = 100 * (1 - remaining) name = f"{item.episode.series.title} {item.episode.identifier}" attrs[name] = f"{remaining_pct:.2f}%" return attrs @property def state(self) -> int: """Return the state of the sensor.""" return len(self._queue) class SonarrSeriesSensor(SonarrSensor): """Defines a Sonarr Series sensor.""" def __init__(self, sonarr: Sonarr, entry_id: str) -> None: """Initialize Sonarr Series sensor.""" self._items = [] super().__init__( sonarr=sonarr, entry_id=entry_id, icon="mdi:television", key="series", name=f"{sonarr.app.info.app_name} Shows", unit_of_measurement="Series", enabled_default=False, ) @sonarr_exception_handler async def async_update(self) -> None: """Update entity.""" self._items = await self.sonarr.series() @property def device_state_attributes(self) -> Optional[Dict[str, Any]]: """Return the state attributes of the entity.""" attrs = {} for item in self._items: attrs[item.series.title] = f"{item.downloaded}/{item.episodes} Episodes" return attrs @property def state(self) -> int: """Return the state of the sensor.""" return len(self._items) class SonarrUpcomingSensor(SonarrSensor): """Defines a Sonarr Upcoming sensor.""" def __init__(self, sonarr: Sonarr, entry_id: str, days: int = 1) -> None: """Initialize Sonarr Upcoming sensor.""" self._days = days self._upcoming = [] super().__init__( sonarr=sonarr, entry_id=entry_id, icon="mdi:television", key="upcoming", name=f"{sonarr.app.info.app_name} Upcoming", unit_of_measurement="Episodes", ) async def async_added_to_hass(self): """Listen for signals.""" await super().async_added_to_hass() self.async_on_remove( async_dispatcher_connect( self.hass, f"sonarr.{self._entry_id}.entry_options_update", self.async_update_entry_options, ) ) @sonarr_exception_handler async def async_update(self) -> None: """Update entity.""" local = dt_util.start_of_local_day().replace(microsecond=0) start = dt_util.as_utc(local) end = start + timedelta(days=self._days) self._upcoming = await self.sonarr.calendar( start=start.isoformat(), end=end.isoformat() ) async def async_update_entry_options(self, options: dict) -> None: """Update sensor settings when config entry options are update.""" self._days = options[CONF_UPCOMING_DAYS] @property def device_state_attributes(self) -> Optional[Dict[str, Any]]: """Return the state attributes of the entity.""" attrs = {} for episode in self._upcoming: attrs[episode.series.title] = episode.identifier return attrs @property def state(self) -> int: """Return the state of the sensor.""" return len(self._upcoming) class SonarrWantedSensor(SonarrSensor): """Defines a Sonarr Wanted sensor.""" def __init__(self, sonarr: Sonarr, entry_id: str, max_items: int = 10) -> None: """Initialize Sonarr Wanted sensor.""" self._max_items = max_items self._results = None self._total: Optional[int] = None super().__init__( sonarr=sonarr, entry_id=entry_id, icon="mdi:television", key="wanted", name=f"{sonarr.app.info.app_name} Wanted", unit_of_measurement="Episodes", enabled_default=False, ) async def async_added_to_hass(self): """Listen for signals.""" await super().async_added_to_hass() self.async_on_remove( async_dispatcher_connect( self.hass, f"sonarr.{self._entry_id}.entry_options_update", self.async_update_entry_options, ) ) @sonarr_exception_handler async def async_update(self) -> None: """Update entity.""" self._results = await self.sonarr.wanted(page_size=self._max_items) self._total = self._results.total async def async_update_entry_options(self, options: dict) -> None: """Update sensor settings when config entry options are update.""" self._max_items = options[CONF_WANTED_MAX_ITEMS] @property def device_state_attributes(self) -> Optional[Dict[str, Any]]: """Return the state attributes of the entity.""" attrs = {} if self._results is not None: for episode in self._results.episodes: name = f"{episode.series.title} {episode.identifier}" attrs[name] = episode.airdate return attrs @property def state(self) -> Optional[int]: """Return the state of the sensor.""" return self._total
"""Test Hue init with multiple bridges.""" from aiohue.groups import Groups from aiohue.lights import Lights from aiohue.scenes import Scenes from aiohue.sensors import Sensors import pytest from homeassistant import config_entries from homeassistant.components import hue from homeassistant.components.hue import sensor_base as hue_sensor_base from homeassistant.setup import async_setup_component from tests.async_mock import Mock, patch async def setup_component(hass): """Hue component.""" with patch.object(hue, "async_setup_entry", return_value=True): assert ( await async_setup_component( hass, hue.DOMAIN, {}, ) is True ) async def test_hue_activate_scene_both_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes both bridges successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) mock_hue_activate_scene1.assert_called_once() mock_hue_activate_scene2.assert_called_once() async def test_hue_activate_scene_one_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes only one bridge successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) mock_hue_activate_scene1.assert_called_once() mock_hue_activate_scene2.assert_called_once() async def test_hue_activate_scene_zero_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes no bridge successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) # both were retried assert mock_hue_activate_scene1.call_count == 2 assert mock_hue_activate_scene2.call_count == 2 async def setup_bridge(hass, mock_bridge, config_entry): """Load the Hue light platform with the provided bridge.""" mock_bridge.config_entry = config_entry hass.data[hue.DOMAIN][config_entry.entry_id] = mock_bridge await hass.config_entries.async_forward_entry_setup(config_entry, "light") # To flush out the service call to update the group await hass.async_block_till_done() @pytest.fixture def mock_config_entry1(hass): """Mock a config entry.""" return create_config_entry() @pytest.fixture def mock_config_entry2(hass): """Mock a config entry.""" return create_config_entry() def create_config_entry(): """Mock a config entry.""" return config_entries.ConfigEntry( 1, hue.DOMAIN, "Mock Title", {"host": "mock-host"}, "test", config_entries.CONN_CLASS_LOCAL_POLL, system_options={}, ) @pytest.fixture def mock_bridge1(hass): """Mock a Hue bridge.""" return create_mock_bridge(hass) @pytest.fixture def mock_bridge2(hass): """Mock a Hue bridge.""" return create_mock_bridge(hass) def create_mock_bridge(hass): """Create a mock Hue bridge.""" bridge = Mock( hass=hass, available=True, authorized=True, allow_unreachable=False, allow_groups=False, api=Mock(), reset_jobs=[], spec=hue.HueBridge, ) bridge.sensor_manager = hue_sensor_base.SensorManager(bridge) bridge.mock_requests = [] async def mock_request(method, path, **kwargs): kwargs["method"] = method kwargs["path"] = path bridge.mock_requests.append(kwargs) return {} async def async_request_call(task): await task() bridge.async_request_call = async_request_call bridge.api.config.apiversion = "9.9.9" bridge.api.lights = Lights({}, mock_request) bridge.api.groups = Groups({}, mock_request) bridge.api.sensors = Sensors({}, mock_request) bridge.api.scenes = Scenes({}, mock_request) return bridge
mezz64/home-assistant
tests/components/hue/test_init_multiple_bridges.py
homeassistant/components/sonarr/sensor.py
"""Config flow to configure Coolmaster.""" from pycoolmasternet_async import CoolMasterNet import voluptuous as vol from homeassistant import config_entries, core from homeassistant.const import CONF_HOST, CONF_PORT # pylint: disable=unused-import from .const import AVAILABLE_MODES, CONF_SUPPORTED_MODES, DEFAULT_PORT, DOMAIN MODES_SCHEMA = {vol.Required(mode, default=True): bool for mode in AVAILABLE_MODES} DATA_SCHEMA = vol.Schema({vol.Required(CONF_HOST): str, **MODES_SCHEMA}) async def _validate_connection(hass: core.HomeAssistant, host): cool = CoolMasterNet(host, DEFAULT_PORT) units = await cool.status() return bool(units) class CoolmasterConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Handle a Coolmaster config flow.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL @core.callback def _async_get_entry(self, data): supported_modes = [ key for (key, value) in data.items() if key in AVAILABLE_MODES and value ] return self.async_create_entry( title=data[CONF_HOST], data={ CONF_HOST: data[CONF_HOST], CONF_PORT: DEFAULT_PORT, CONF_SUPPORTED_MODES: supported_modes, }, ) async def async_step_user(self, user_input=None): """Handle a flow initialized by the user.""" if user_input is None: return self.async_show_form(step_id="user", data_schema=DATA_SCHEMA) errors = {} host = user_input[CONF_HOST] try: result = await _validate_connection(self.hass, host) if not result: errors["base"] = "no_units" except (OSError, ConnectionRefusedError, TimeoutError): errors["base"] = "cannot_connect" if errors: return self.async_show_form( step_id="user", data_schema=DATA_SCHEMA, errors=errors ) return self._async_get_entry(user_input)
"""Test Hue init with multiple bridges.""" from aiohue.groups import Groups from aiohue.lights import Lights from aiohue.scenes import Scenes from aiohue.sensors import Sensors import pytest from homeassistant import config_entries from homeassistant.components import hue from homeassistant.components.hue import sensor_base as hue_sensor_base from homeassistant.setup import async_setup_component from tests.async_mock import Mock, patch async def setup_component(hass): """Hue component.""" with patch.object(hue, "async_setup_entry", return_value=True): assert ( await async_setup_component( hass, hue.DOMAIN, {}, ) is True ) async def test_hue_activate_scene_both_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes both bridges successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) mock_hue_activate_scene1.assert_called_once() mock_hue_activate_scene2.assert_called_once() async def test_hue_activate_scene_one_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes only one bridge successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) mock_hue_activate_scene1.assert_called_once() mock_hue_activate_scene2.assert_called_once() async def test_hue_activate_scene_zero_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes no bridge successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) # both were retried assert mock_hue_activate_scene1.call_count == 2 assert mock_hue_activate_scene2.call_count == 2 async def setup_bridge(hass, mock_bridge, config_entry): """Load the Hue light platform with the provided bridge.""" mock_bridge.config_entry = config_entry hass.data[hue.DOMAIN][config_entry.entry_id] = mock_bridge await hass.config_entries.async_forward_entry_setup(config_entry, "light") # To flush out the service call to update the group await hass.async_block_till_done() @pytest.fixture def mock_config_entry1(hass): """Mock a config entry.""" return create_config_entry() @pytest.fixture def mock_config_entry2(hass): """Mock a config entry.""" return create_config_entry() def create_config_entry(): """Mock a config entry.""" return config_entries.ConfigEntry( 1, hue.DOMAIN, "Mock Title", {"host": "mock-host"}, "test", config_entries.CONN_CLASS_LOCAL_POLL, system_options={}, ) @pytest.fixture def mock_bridge1(hass): """Mock a Hue bridge.""" return create_mock_bridge(hass) @pytest.fixture def mock_bridge2(hass): """Mock a Hue bridge.""" return create_mock_bridge(hass) def create_mock_bridge(hass): """Create a mock Hue bridge.""" bridge = Mock( hass=hass, available=True, authorized=True, allow_unreachable=False, allow_groups=False, api=Mock(), reset_jobs=[], spec=hue.HueBridge, ) bridge.sensor_manager = hue_sensor_base.SensorManager(bridge) bridge.mock_requests = [] async def mock_request(method, path, **kwargs): kwargs["method"] = method kwargs["path"] = path bridge.mock_requests.append(kwargs) return {} async def async_request_call(task): await task() bridge.async_request_call = async_request_call bridge.api.config.apiversion = "9.9.9" bridge.api.lights = Lights({}, mock_request) bridge.api.groups = Groups({}, mock_request) bridge.api.sensors = Sensors({}, mock_request) bridge.api.scenes = Scenes({}, mock_request) return bridge
mezz64/home-assistant
tests/components/hue/test_init_multiple_bridges.py
homeassistant/components/coolmaster/config_flow.py
"""Reproduce an Remote state.""" import asyncio import logging from typing import Any, Dict, Iterable, Optional from homeassistant.const import ( ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON, STATE_OFF, STATE_ON, ) from homeassistant.core import Context, State from homeassistant.helpers.typing import HomeAssistantType from . import DOMAIN _LOGGER = logging.getLogger(__name__) VALID_STATES = {STATE_ON, STATE_OFF} async def _async_reproduce_state( hass: HomeAssistantType, state: State, *, context: Optional[Context] = None, reproduce_options: Optional[Dict[str, Any]] = None, ) -> None: """Reproduce a single state.""" cur_state = hass.states.get(state.entity_id) if cur_state is None: _LOGGER.warning("Unable to find entity %s", state.entity_id) return if state.state not in VALID_STATES: _LOGGER.warning( "Invalid state specified for %s: %s", state.entity_id, state.state ) return # Return if we are already at the right state. if cur_state.state == state.state: return service_data = {ATTR_ENTITY_ID: state.entity_id} if state.state == STATE_ON: service = SERVICE_TURN_ON elif state.state == STATE_OFF: service = SERVICE_TURN_OFF await hass.services.async_call( DOMAIN, service, service_data, context=context, blocking=True ) async def async_reproduce_states( hass: HomeAssistantType, states: Iterable[State], *, context: Optional[Context] = None, reproduce_options: Optional[Dict[str, Any]] = None, ) -> None: """Reproduce Remote states.""" await asyncio.gather( *( _async_reproduce_state( hass, state, context=context, reproduce_options=reproduce_options ) for state in states ) )
"""Test Hue init with multiple bridges.""" from aiohue.groups import Groups from aiohue.lights import Lights from aiohue.scenes import Scenes from aiohue.sensors import Sensors import pytest from homeassistant import config_entries from homeassistant.components import hue from homeassistant.components.hue import sensor_base as hue_sensor_base from homeassistant.setup import async_setup_component from tests.async_mock import Mock, patch async def setup_component(hass): """Hue component.""" with patch.object(hue, "async_setup_entry", return_value=True): assert ( await async_setup_component( hass, hue.DOMAIN, {}, ) is True ) async def test_hue_activate_scene_both_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes both bridges successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) mock_hue_activate_scene1.assert_called_once() mock_hue_activate_scene2.assert_called_once() async def test_hue_activate_scene_one_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes only one bridge successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) mock_hue_activate_scene1.assert_called_once() mock_hue_activate_scene2.assert_called_once() async def test_hue_activate_scene_zero_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes no bridge successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) # both were retried assert mock_hue_activate_scene1.call_count == 2 assert mock_hue_activate_scene2.call_count == 2 async def setup_bridge(hass, mock_bridge, config_entry): """Load the Hue light platform with the provided bridge.""" mock_bridge.config_entry = config_entry hass.data[hue.DOMAIN][config_entry.entry_id] = mock_bridge await hass.config_entries.async_forward_entry_setup(config_entry, "light") # To flush out the service call to update the group await hass.async_block_till_done() @pytest.fixture def mock_config_entry1(hass): """Mock a config entry.""" return create_config_entry() @pytest.fixture def mock_config_entry2(hass): """Mock a config entry.""" return create_config_entry() def create_config_entry(): """Mock a config entry.""" return config_entries.ConfigEntry( 1, hue.DOMAIN, "Mock Title", {"host": "mock-host"}, "test", config_entries.CONN_CLASS_LOCAL_POLL, system_options={}, ) @pytest.fixture def mock_bridge1(hass): """Mock a Hue bridge.""" return create_mock_bridge(hass) @pytest.fixture def mock_bridge2(hass): """Mock a Hue bridge.""" return create_mock_bridge(hass) def create_mock_bridge(hass): """Create a mock Hue bridge.""" bridge = Mock( hass=hass, available=True, authorized=True, allow_unreachable=False, allow_groups=False, api=Mock(), reset_jobs=[], spec=hue.HueBridge, ) bridge.sensor_manager = hue_sensor_base.SensorManager(bridge) bridge.mock_requests = [] async def mock_request(method, path, **kwargs): kwargs["method"] = method kwargs["path"] = path bridge.mock_requests.append(kwargs) return {} async def async_request_call(task): await task() bridge.async_request_call = async_request_call bridge.api.config.apiversion = "9.9.9" bridge.api.lights = Lights({}, mock_request) bridge.api.groups = Groups({}, mock_request) bridge.api.sensors = Sensors({}, mock_request) bridge.api.scenes = Scenes({}, mock_request) return bridge
mezz64/home-assistant
tests/components/hue/test_init_multiple_bridges.py
homeassistant/components/remote/reproduce_state.py
"""Support for powering relays in a DoorBird video doorbell.""" import datetime from homeassistant.components.switch import SwitchEntity import homeassistant.util.dt as dt_util from .const import DOMAIN, DOOR_STATION, DOOR_STATION_INFO from .entity import DoorBirdEntity IR_RELAY = "__ir_light__" async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the DoorBird switch platform.""" entities = [] config_entry_id = config_entry.entry_id doorstation = hass.data[DOMAIN][config_entry_id][DOOR_STATION] doorstation_info = hass.data[DOMAIN][config_entry_id][DOOR_STATION_INFO] relays = doorstation_info["RELAYS"] relays.append(IR_RELAY) for relay in relays: switch = DoorBirdSwitch(doorstation, doorstation_info, relay) entities.append(switch) async_add_entities(entities) class DoorBirdSwitch(DoorBirdEntity, SwitchEntity): """A relay in a DoorBird device.""" def __init__(self, doorstation, doorstation_info, relay): """Initialize a relay in a DoorBird device.""" super().__init__(doorstation, doorstation_info) self._doorstation = doorstation self._relay = relay self._state = False self._assume_off = datetime.datetime.min if relay == IR_RELAY: self._time = datetime.timedelta(minutes=5) else: self._time = datetime.timedelta(seconds=5) self._unique_id = f"{self._mac_addr}_{self._relay}" @property def unique_id(self): """Switch unique id.""" return self._unique_id @property def name(self): """Return the name of the switch.""" if self._relay == IR_RELAY: return f"{self._doorstation.name} IR" return f"{self._doorstation.name} Relay {self._relay}" @property def icon(self): """Return the icon to display.""" return "mdi:lightbulb" if self._relay == IR_RELAY else "mdi:dip-switch" @property def is_on(self): """Get the assumed state of the relay.""" return self._state def turn_on(self, **kwargs): """Power the relay.""" if self._relay == IR_RELAY: self._state = self._doorstation.device.turn_light_on() else: self._state = self._doorstation.device.energize_relay(self._relay) now = dt_util.utcnow() self._assume_off = now + self._time def turn_off(self, **kwargs): """Turn off the relays is not needed. They are time-based.""" raise NotImplementedError("DoorBird relays cannot be manually turned off.") async def async_update(self): """Wait for the correct amount of assumed time to pass.""" if self._state and self._assume_off <= dt_util.utcnow(): self._state = False self._assume_off = datetime.datetime.min
"""Test Hue init with multiple bridges.""" from aiohue.groups import Groups from aiohue.lights import Lights from aiohue.scenes import Scenes from aiohue.sensors import Sensors import pytest from homeassistant import config_entries from homeassistant.components import hue from homeassistant.components.hue import sensor_base as hue_sensor_base from homeassistant.setup import async_setup_component from tests.async_mock import Mock, patch async def setup_component(hass): """Hue component.""" with patch.object(hue, "async_setup_entry", return_value=True): assert ( await async_setup_component( hass, hue.DOMAIN, {}, ) is True ) async def test_hue_activate_scene_both_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes both bridges successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) mock_hue_activate_scene1.assert_called_once() mock_hue_activate_scene2.assert_called_once() async def test_hue_activate_scene_one_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes only one bridge successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) mock_hue_activate_scene1.assert_called_once() mock_hue_activate_scene2.assert_called_once() async def test_hue_activate_scene_zero_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes no bridge successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) # both were retried assert mock_hue_activate_scene1.call_count == 2 assert mock_hue_activate_scene2.call_count == 2 async def setup_bridge(hass, mock_bridge, config_entry): """Load the Hue light platform with the provided bridge.""" mock_bridge.config_entry = config_entry hass.data[hue.DOMAIN][config_entry.entry_id] = mock_bridge await hass.config_entries.async_forward_entry_setup(config_entry, "light") # To flush out the service call to update the group await hass.async_block_till_done() @pytest.fixture def mock_config_entry1(hass): """Mock a config entry.""" return create_config_entry() @pytest.fixture def mock_config_entry2(hass): """Mock a config entry.""" return create_config_entry() def create_config_entry(): """Mock a config entry.""" return config_entries.ConfigEntry( 1, hue.DOMAIN, "Mock Title", {"host": "mock-host"}, "test", config_entries.CONN_CLASS_LOCAL_POLL, system_options={}, ) @pytest.fixture def mock_bridge1(hass): """Mock a Hue bridge.""" return create_mock_bridge(hass) @pytest.fixture def mock_bridge2(hass): """Mock a Hue bridge.""" return create_mock_bridge(hass) def create_mock_bridge(hass): """Create a mock Hue bridge.""" bridge = Mock( hass=hass, available=True, authorized=True, allow_unreachable=False, allow_groups=False, api=Mock(), reset_jobs=[], spec=hue.HueBridge, ) bridge.sensor_manager = hue_sensor_base.SensorManager(bridge) bridge.mock_requests = [] async def mock_request(method, path, **kwargs): kwargs["method"] = method kwargs["path"] = path bridge.mock_requests.append(kwargs) return {} async def async_request_call(task): await task() bridge.async_request_call = async_request_call bridge.api.config.apiversion = "9.9.9" bridge.api.lights = Lights({}, mock_request) bridge.api.groups = Groups({}, mock_request) bridge.api.sensors = Sensors({}, mock_request) bridge.api.scenes = Scenes({}, mock_request) return bridge
mezz64/home-assistant
tests/components/hue/test_init_multiple_bridges.py
homeassistant/components/doorbird/switch.py
"""Support for an Intergas heater via an InComfort/InTouch Lan2RF gateway.""" from typing import Any, Dict, Optional from homeassistant.components.binary_sensor import ( DOMAIN as BINARY_SENSOR_DOMAIN, BinarySensorEntity, ) from . import DOMAIN, IncomfortChild async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up an InComfort/InTouch binary_sensor device.""" if discovery_info is None: return client = hass.data[DOMAIN]["client"] heaters = hass.data[DOMAIN]["heaters"] async_add_entities([IncomfortFailed(client, h) for h in heaters]) class IncomfortFailed(IncomfortChild, BinarySensorEntity): """Representation of an InComfort Failed sensor.""" def __init__(self, client, heater) -> None: """Initialize the binary sensor.""" super().__init__() self._unique_id = f"{heater.serial_no}_failed" self.entity_id = f"{BINARY_SENSOR_DOMAIN}.{DOMAIN}_failed" self._name = "Boiler Fault" self._client = client self._heater = heater @property def is_on(self) -> bool: """Return the status of the sensor.""" return self._heater.status["is_failed"] @property def device_state_attributes(self) -> Optional[Dict[str, Any]]: """Return the device state attributes.""" return {"fault_code": self._heater.status["fault_code"]}
"""Test Hue init with multiple bridges.""" from aiohue.groups import Groups from aiohue.lights import Lights from aiohue.scenes import Scenes from aiohue.sensors import Sensors import pytest from homeassistant import config_entries from homeassistant.components import hue from homeassistant.components.hue import sensor_base as hue_sensor_base from homeassistant.setup import async_setup_component from tests.async_mock import Mock, patch async def setup_component(hass): """Hue component.""" with patch.object(hue, "async_setup_entry", return_value=True): assert ( await async_setup_component( hass, hue.DOMAIN, {}, ) is True ) async def test_hue_activate_scene_both_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes both bridges successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) mock_hue_activate_scene1.assert_called_once() mock_hue_activate_scene2.assert_called_once() async def test_hue_activate_scene_one_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes only one bridge successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) mock_hue_activate_scene1.assert_called_once() mock_hue_activate_scene2.assert_called_once() async def test_hue_activate_scene_zero_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes no bridge successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) # both were retried assert mock_hue_activate_scene1.call_count == 2 assert mock_hue_activate_scene2.call_count == 2 async def setup_bridge(hass, mock_bridge, config_entry): """Load the Hue light platform with the provided bridge.""" mock_bridge.config_entry = config_entry hass.data[hue.DOMAIN][config_entry.entry_id] = mock_bridge await hass.config_entries.async_forward_entry_setup(config_entry, "light") # To flush out the service call to update the group await hass.async_block_till_done() @pytest.fixture def mock_config_entry1(hass): """Mock a config entry.""" return create_config_entry() @pytest.fixture def mock_config_entry2(hass): """Mock a config entry.""" return create_config_entry() def create_config_entry(): """Mock a config entry.""" return config_entries.ConfigEntry( 1, hue.DOMAIN, "Mock Title", {"host": "mock-host"}, "test", config_entries.CONN_CLASS_LOCAL_POLL, system_options={}, ) @pytest.fixture def mock_bridge1(hass): """Mock a Hue bridge.""" return create_mock_bridge(hass) @pytest.fixture def mock_bridge2(hass): """Mock a Hue bridge.""" return create_mock_bridge(hass) def create_mock_bridge(hass): """Create a mock Hue bridge.""" bridge = Mock( hass=hass, available=True, authorized=True, allow_unreachable=False, allow_groups=False, api=Mock(), reset_jobs=[], spec=hue.HueBridge, ) bridge.sensor_manager = hue_sensor_base.SensorManager(bridge) bridge.mock_requests = [] async def mock_request(method, path, **kwargs): kwargs["method"] = method kwargs["path"] = path bridge.mock_requests.append(kwargs) return {} async def async_request_call(task): await task() bridge.async_request_call = async_request_call bridge.api.config.apiversion = "9.9.9" bridge.api.lights = Lights({}, mock_request) bridge.api.groups = Groups({}, mock_request) bridge.api.sensors = Sensors({}, mock_request) bridge.api.scenes = Scenes({}, mock_request) return bridge
mezz64/home-assistant
tests/components/hue/test_init_multiple_bridges.py
homeassistant/components/incomfort/binary_sensor.py
"""Manufacturer specific channels module for Zigbee Home Automation.""" from homeassistant.core import callback from .. import registries from ..const import ( ATTR_ATTRIBUTE_ID, ATTR_ATTRIBUTE_NAME, ATTR_VALUE, REPORT_CONFIG_ASAP, REPORT_CONFIG_MAX_INT, REPORT_CONFIG_MIN_INT, SIGNAL_ATTR_UPDATED, UNKNOWN, ) from .base import ZigbeeChannel @registries.ZIGBEE_CHANNEL_REGISTRY.register(registries.SMARTTHINGS_HUMIDITY_CLUSTER) class SmartThingsHumidity(ZigbeeChannel): """Smart Things Humidity channel.""" REPORT_CONFIG = [ { "attr": "measured_value", "config": (REPORT_CONFIG_MIN_INT, REPORT_CONFIG_MAX_INT, 50), } ] @registries.CHANNEL_ONLY_CLUSTERS.register(0xFD00) @registries.ZIGBEE_CHANNEL_REGISTRY.register(0xFD00) class OsramButton(ZigbeeChannel): """Osram button channel.""" REPORT_CONFIG = [] @registries.CHANNEL_ONLY_CLUSTERS.register(registries.PHILLIPS_REMOTE_CLUSTER) @registries.ZIGBEE_CHANNEL_REGISTRY.register(registries.PHILLIPS_REMOTE_CLUSTER) class PhillipsRemote(ZigbeeChannel): """Phillips remote channel.""" REPORT_CONFIG = [] @registries.CHANNEL_ONLY_CLUSTERS.register(0xFCC0) @registries.ZIGBEE_CHANNEL_REGISTRY.register(0xFCC0) class OppleRemote(ZigbeeChannel): """Opple button channel.""" REPORT_CONFIG = [] @registries.ZIGBEE_CHANNEL_REGISTRY.register( registries.SMARTTHINGS_ACCELERATION_CLUSTER ) class SmartThingsAcceleration(ZigbeeChannel): """Smart Things Acceleration channel.""" REPORT_CONFIG = [ {"attr": "acceleration", "config": REPORT_CONFIG_ASAP}, {"attr": "x_axis", "config": REPORT_CONFIG_ASAP}, {"attr": "y_axis", "config": REPORT_CONFIG_ASAP}, {"attr": "z_axis", "config": REPORT_CONFIG_ASAP}, ] @callback def attribute_updated(self, attrid, value): """Handle attribute updates on this cluster.""" if attrid == self.value_attribute: self.async_send_signal( f"{self.unique_id}_{SIGNAL_ATTR_UPDATED}", attrid, self._cluster.attributes.get(attrid, [UNKNOWN])[0], value, ) return self.zha_send_event( SIGNAL_ATTR_UPDATED, { ATTR_ATTRIBUTE_ID: attrid, ATTR_ATTRIBUTE_NAME: self._cluster.attributes.get(attrid, [UNKNOWN])[0], ATTR_VALUE: value, }, )
"""Test Hue init with multiple bridges.""" from aiohue.groups import Groups from aiohue.lights import Lights from aiohue.scenes import Scenes from aiohue.sensors import Sensors import pytest from homeassistant import config_entries from homeassistant.components import hue from homeassistant.components.hue import sensor_base as hue_sensor_base from homeassistant.setup import async_setup_component from tests.async_mock import Mock, patch async def setup_component(hass): """Hue component.""" with patch.object(hue, "async_setup_entry", return_value=True): assert ( await async_setup_component( hass, hue.DOMAIN, {}, ) is True ) async def test_hue_activate_scene_both_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes both bridges successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) mock_hue_activate_scene1.assert_called_once() mock_hue_activate_scene2.assert_called_once() async def test_hue_activate_scene_one_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes only one bridge successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=None ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) mock_hue_activate_scene1.assert_called_once() mock_hue_activate_scene2.assert_called_once() async def test_hue_activate_scene_zero_responds( hass, mock_bridge1, mock_bridge2, mock_config_entry1, mock_config_entry2 ): """Test that makes no bridge successfully activate a scene.""" await setup_component(hass) await setup_bridge(hass, mock_bridge1, mock_config_entry1) await setup_bridge(hass, mock_bridge2, mock_config_entry2) with patch.object( mock_bridge1, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene1, patch.object( mock_bridge2, "hue_activate_scene", return_value=False ) as mock_hue_activate_scene2: await hass.services.async_call( "hue", "hue_activate_scene", {"group_name": "group_2", "scene_name": "my_scene"}, blocking=True, ) # both were retried assert mock_hue_activate_scene1.call_count == 2 assert mock_hue_activate_scene2.call_count == 2 async def setup_bridge(hass, mock_bridge, config_entry): """Load the Hue light platform with the provided bridge.""" mock_bridge.config_entry = config_entry hass.data[hue.DOMAIN][config_entry.entry_id] = mock_bridge await hass.config_entries.async_forward_entry_setup(config_entry, "light") # To flush out the service call to update the group await hass.async_block_till_done() @pytest.fixture def mock_config_entry1(hass): """Mock a config entry.""" return create_config_entry() @pytest.fixture def mock_config_entry2(hass): """Mock a config entry.""" return create_config_entry() def create_config_entry(): """Mock a config entry.""" return config_entries.ConfigEntry( 1, hue.DOMAIN, "Mock Title", {"host": "mock-host"}, "test", config_entries.CONN_CLASS_LOCAL_POLL, system_options={}, ) @pytest.fixture def mock_bridge1(hass): """Mock a Hue bridge.""" return create_mock_bridge(hass) @pytest.fixture def mock_bridge2(hass): """Mock a Hue bridge.""" return create_mock_bridge(hass) def create_mock_bridge(hass): """Create a mock Hue bridge.""" bridge = Mock( hass=hass, available=True, authorized=True, allow_unreachable=False, allow_groups=False, api=Mock(), reset_jobs=[], spec=hue.HueBridge, ) bridge.sensor_manager = hue_sensor_base.SensorManager(bridge) bridge.mock_requests = [] async def mock_request(method, path, **kwargs): kwargs["method"] = method kwargs["path"] = path bridge.mock_requests.append(kwargs) return {} async def async_request_call(task): await task() bridge.async_request_call = async_request_call bridge.api.config.apiversion = "9.9.9" bridge.api.lights = Lights({}, mock_request) bridge.api.groups = Groups({}, mock_request) bridge.api.sensors = Sensors({}, mock_request) bridge.api.scenes = Scenes({}, mock_request) return bridge
mezz64/home-assistant
tests/components/hue/test_init_multiple_bridges.py
homeassistant/components/zha/core/channels/manufacturerspecific.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
"""Test the owntracks_http platform.""" import asyncio import pytest from homeassistant.setup import async_setup_component from homeassistant.components import owntracks from tests.common import mock_component, MockConfigEntry MINIMAL_LOCATION_MESSAGE = { "_type": "location", "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "tst": 1, } LOCATION_MESSAGE = { "_type": "location", "acc": 60, "alt": 27, "batt": 92, "cog": 248, "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "t": "u", "tst": 1, "vac": 4, "vel": 0, } @pytest.fixture(autouse=True) def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading.""" pass @pytest.fixture def mock_client(hass, aiohttp_client): """Start the Hass HTTP component.""" mock_component(hass, "group") mock_component(hass, "zone") mock_component(hass, "device_tracker") MockConfigEntry( domain="owntracks", data={"webhook_id": "owntracks_test", "secret": "abcd"} ).add_to_hass(hass) hass.loop.run_until_complete(async_setup_component(hass, "owntracks", {})) return hass.loop.run_until_complete(aiohttp_client(hass.http.app)) @asyncio.coroutine def test_handle_valid_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_valid_minimal_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=MINIMAL_LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_value_error(mock_client): """Test we don't disclose that this is a valid webhook.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json="", headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.text() assert json == "" @asyncio.coroutine def test_returns_error_missing_username(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-d": "Pixel"}, ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "No topic or user found" in caplog.text @asyncio.coroutine def test_returns_error_incorrect_json(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"} ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "invalid JSON" in caplog.text @asyncio.coroutine def test_returns_error_missing_device(mock_client): """Test that an error is returned when device name is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] def test_context_delivers_pending_msg(): """Test that context is able to hold pending messages while being init.""" context = owntracks.OwnTracksContext(None, None, None, None, None, None, None, None) context.async_see(hello="world") context.async_see(world="hello") received = [] context.set_async_see(lambda **data: received.append(data)) assert len(received) == 2 assert received[0] == {"hello": "world"} assert received[1] == {"world": "hello"} received.clear() context.set_async_see(lambda **data: received.append(data)) assert len(received) == 0
fbradyirl/home-assistant
tests/components/owntracks/test_init.py
homeassistant/components/hikvisioncam/switch.py
"""Support for Neato Connected Vacuums.""" from datetime import timedelta import logging import requests import voluptuous as vol from homeassistant.components.vacuum import ( ATTR_BATTERY_ICON, ATTR_BATTERY_LEVEL, ATTR_STATUS, DOMAIN, STATE_CLEANING, STATE_DOCKED, STATE_ERROR, STATE_IDLE, STATE_PAUSED, STATE_RETURNING, SUPPORT_BATTERY, SUPPORT_CLEAN_SPOT, SUPPORT_LOCATE, SUPPORT_MAP, SUPPORT_PAUSE, SUPPORT_RETURN_HOME, SUPPORT_START, SUPPORT_STATE, SUPPORT_STOP, StateVacuumDevice, ) from homeassistant.const import ATTR_ENTITY_ID import homeassistant.helpers.config_validation as cv from homeassistant.helpers.service import extract_entity_ids from . import ( ACTION, ALERTS, ERRORS, MODE, NEATO_LOGIN, NEATO_MAP_DATA, NEATO_PERSISTENT_MAPS, NEATO_ROBOTS, ) _LOGGER = logging.getLogger(__name__) SCAN_INTERVAL = timedelta(minutes=5) SUPPORT_NEATO = ( SUPPORT_BATTERY | SUPPORT_PAUSE | SUPPORT_RETURN_HOME | SUPPORT_STOP | SUPPORT_START | SUPPORT_CLEAN_SPOT | SUPPORT_STATE | SUPPORT_MAP | SUPPORT_LOCATE ) ATTR_CLEAN_START = "clean_start" ATTR_CLEAN_STOP = "clean_stop" ATTR_CLEAN_AREA = "clean_area" ATTR_CLEAN_BATTERY_START = "battery_level_at_clean_start" ATTR_CLEAN_BATTERY_END = "battery_level_at_clean_end" ATTR_CLEAN_SUSP_COUNT = "clean_suspension_count" ATTR_CLEAN_SUSP_TIME = "clean_suspension_time" ATTR_MODE = "mode" ATTR_NAVIGATION = "navigation" ATTR_CATEGORY = "category" ATTR_ZONE = "zone" SERVICE_NEATO_CUSTOM_CLEANING = "neato_custom_cleaning" SERVICE_NEATO_CUSTOM_CLEANING_SCHEMA = vol.Schema( { vol.Required(ATTR_ENTITY_ID): cv.entity_ids, vol.Optional(ATTR_MODE, default=2): cv.positive_int, vol.Optional(ATTR_NAVIGATION, default=1): cv.positive_int, vol.Optional(ATTR_CATEGORY, default=4): cv.positive_int, vol.Optional(ATTR_ZONE): cv.string, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Neato vacuum.""" dev = [] for robot in hass.data[NEATO_ROBOTS]: dev.append(NeatoConnectedVacuum(hass, robot)) if not dev: return _LOGGER.debug("Adding vacuums %s", dev) add_entities(dev, True) def neato_custom_cleaning_service(call): """Zone cleaning service that allows user to change options.""" for robot in service_to_entities(call): if call.service == SERVICE_NEATO_CUSTOM_CLEANING: mode = call.data.get(ATTR_MODE) navigation = call.data.get(ATTR_NAVIGATION) category = call.data.get(ATTR_CATEGORY) zone = call.data.get(ATTR_ZONE) robot.neato_custom_cleaning(mode, navigation, category, zone) def service_to_entities(call): """Return the known devices that a service call mentions.""" entity_ids = extract_entity_ids(hass, call) entities = [entity for entity in dev if entity.entity_id in entity_ids] return entities hass.services.register( DOMAIN, SERVICE_NEATO_CUSTOM_CLEANING, neato_custom_cleaning_service, schema=SERVICE_NEATO_CUSTOM_CLEANING_SCHEMA, ) class NeatoConnectedVacuum(StateVacuumDevice): """Representation of a Neato Connected Vacuum.""" def __init__(self, hass, robot): """Initialize the Neato Connected Vacuum.""" self.robot = robot self.neato = hass.data[NEATO_LOGIN] self._name = "{}".format(self.robot.name) self._status_state = None self._clean_state = None self._state = None self._mapdata = hass.data[NEATO_MAP_DATA] self.clean_time_start = None self.clean_time_stop = None self.clean_area = None self.clean_battery_start = None self.clean_battery_end = None self.clean_suspension_charge_count = None self.clean_suspension_time = None self._available = False self._battery_level = None self._robot_serial = self.robot.serial self._robot_maps = hass.data[NEATO_PERSISTENT_MAPS] self._robot_boundaries = {} self._robot_has_map = self.robot.has_persistent_maps def update(self): """Update the states of Neato Vacuums.""" _LOGGER.debug("Running Neato Vacuums update") self.neato.update_robots() try: self._state = self.robot.state self._available = True except ( requests.exceptions.ConnectionError, requests.exceptions.HTTPError, ) as ex: _LOGGER.warning("Neato connection error: %s", ex) self._state = None self._available = False return _LOGGER.debug("self._state=%s", self._state) if "alert" in self._state: robot_alert = ALERTS.get(self._state["alert"]) else: robot_alert = None if self._state["state"] == 1: if self._state["details"]["isCharging"]: self._clean_state = STATE_DOCKED self._status_state = "Charging" elif ( self._state["details"]["isDocked"] and not self._state["details"]["isCharging"] ): self._clean_state = STATE_DOCKED self._status_state = "Docked" else: self._clean_state = STATE_IDLE self._status_state = "Stopped" if robot_alert is not None: self._status_state = robot_alert elif self._state["state"] == 2: if robot_alert is None: self._clean_state = STATE_CLEANING self._status_state = ( MODE.get(self._state["cleaning"]["mode"]) + " " + ACTION.get(self._state["action"]) ) else: self._status_state = robot_alert elif self._state["state"] == 3: self._clean_state = STATE_PAUSED self._status_state = "Paused" elif self._state["state"] == 4: self._clean_state = STATE_ERROR self._status_state = ERRORS.get(self._state["error"]) self._battery_level = self._state["details"]["charge"] if not self._mapdata.get(self._robot_serial, {}).get("maps", []): return self.clean_time_start = ( self._mapdata[self._robot_serial]["maps"][0]["start_at"].strip("Z") ).replace("T", " ") self.clean_time_stop = ( self._mapdata[self._robot_serial]["maps"][0]["end_at"].strip("Z") ).replace("T", " ") self.clean_area = self._mapdata[self._robot_serial]["maps"][0]["cleaned_area"] self.clean_suspension_charge_count = self._mapdata[self._robot_serial]["maps"][ 0 ]["suspended_cleaning_charging_count"] self.clean_suspension_time = self._mapdata[self._robot_serial]["maps"][0][ "time_in_suspended_cleaning" ] self.clean_battery_start = self._mapdata[self._robot_serial]["maps"][0][ "run_charge_at_start" ] self.clean_battery_end = self._mapdata[self._robot_serial]["maps"][0][ "run_charge_at_end" ] if self._robot_has_map: if self._state["availableServices"]["maps"] != "basic-1": if self._robot_maps[self._robot_serial]: allmaps = self._robot_maps[self._robot_serial] for maps in allmaps: self._robot_boundaries = self.robot.get_map_boundaries( maps["id"] ).json() @property def name(self): """Return the name of the device.""" return self._name @property def supported_features(self): """Flag vacuum cleaner robot features that are supported.""" return SUPPORT_NEATO @property def battery_level(self): """Return the battery level of the vacuum cleaner.""" return self._battery_level @property def available(self): """Return if the robot is available.""" return self._available @property def state(self): """Return the status of the vacuum cleaner.""" return self._clean_state @property def unique_id(self): """Return a unique ID.""" return self._robot_serial @property def device_state_attributes(self): """Return the state attributes of the vacuum cleaner.""" data = {} if self._status_state is not None: data[ATTR_STATUS] = self._status_state if self.battery_level is not None: data[ATTR_BATTERY_LEVEL] = self.battery_level data[ATTR_BATTERY_ICON] = self.battery_icon if self.clean_time_start is not None: data[ATTR_CLEAN_START] = self.clean_time_start if self.clean_time_stop is not None: data[ATTR_CLEAN_STOP] = self.clean_time_stop if self.clean_area is not None: data[ATTR_CLEAN_AREA] = self.clean_area if self.clean_suspension_charge_count is not None: data[ATTR_CLEAN_SUSP_COUNT] = self.clean_suspension_charge_count if self.clean_suspension_time is not None: data[ATTR_CLEAN_SUSP_TIME] = self.clean_suspension_time if self.clean_battery_start is not None: data[ATTR_CLEAN_BATTERY_START] = self.clean_battery_start if self.clean_battery_end is not None: data[ATTR_CLEAN_BATTERY_END] = self.clean_battery_end return data def start(self): """Start cleaning or resume cleaning.""" if self._state["state"] == 1: self.robot.start_cleaning() elif self._state["state"] == 3: self.robot.resume_cleaning() def pause(self): """Pause the vacuum.""" self.robot.pause_cleaning() def return_to_base(self, **kwargs): """Set the vacuum cleaner to return to the dock.""" if self._clean_state == STATE_CLEANING: self.robot.pause_cleaning() self._clean_state = STATE_RETURNING self.robot.send_to_base() def stop(self, **kwargs): """Stop the vacuum cleaner.""" self.robot.stop_cleaning() def locate(self, **kwargs): """Locate the robot by making it emit a sound.""" self.robot.locate() def clean_spot(self, **kwargs): """Run a spot cleaning starting from the base.""" self.robot.start_spot_cleaning() def neato_custom_cleaning(self, mode, navigation, category, zone=None, **kwargs): """Zone cleaning service call.""" boundary_id = None if zone is not None: for boundary in self._robot_boundaries["data"]["boundaries"]: if zone in boundary["name"]: boundary_id = boundary["id"] if boundary_id is None: _LOGGER.error( "Zone '%s' was not found for the robot '%s'", zone, self._name ) return self._clean_state = STATE_CLEANING self.robot.start_cleaning(mode, navigation, category, boundary_id)
"""Test the owntracks_http platform.""" import asyncio import pytest from homeassistant.setup import async_setup_component from homeassistant.components import owntracks from tests.common import mock_component, MockConfigEntry MINIMAL_LOCATION_MESSAGE = { "_type": "location", "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "tst": 1, } LOCATION_MESSAGE = { "_type": "location", "acc": 60, "alt": 27, "batt": 92, "cog": 248, "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "t": "u", "tst": 1, "vac": 4, "vel": 0, } @pytest.fixture(autouse=True) def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading.""" pass @pytest.fixture def mock_client(hass, aiohttp_client): """Start the Hass HTTP component.""" mock_component(hass, "group") mock_component(hass, "zone") mock_component(hass, "device_tracker") MockConfigEntry( domain="owntracks", data={"webhook_id": "owntracks_test", "secret": "abcd"} ).add_to_hass(hass) hass.loop.run_until_complete(async_setup_component(hass, "owntracks", {})) return hass.loop.run_until_complete(aiohttp_client(hass.http.app)) @asyncio.coroutine def test_handle_valid_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_valid_minimal_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=MINIMAL_LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_value_error(mock_client): """Test we don't disclose that this is a valid webhook.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json="", headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.text() assert json == "" @asyncio.coroutine def test_returns_error_missing_username(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-d": "Pixel"}, ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "No topic or user found" in caplog.text @asyncio.coroutine def test_returns_error_incorrect_json(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"} ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "invalid JSON" in caplog.text @asyncio.coroutine def test_returns_error_missing_device(mock_client): """Test that an error is returned when device name is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] def test_context_delivers_pending_msg(): """Test that context is able to hold pending messages while being init.""" context = owntracks.OwnTracksContext(None, None, None, None, None, None, None, None) context.async_see(hello="world") context.async_see(world="hello") received = [] context.set_async_see(lambda **data: received.append(data)) assert len(received) == 2 assert received[0] == {"hello": "world"} assert received[1] == {"world": "hello"} received.clear() context.set_async_see(lambda **data: received.append(data)) assert len(received) == 0
fbradyirl/home-assistant
tests/components/owntracks/test_init.py
homeassistant/components/neato/vacuum.py
"""Support for NuHeat thermostats.""" from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.climate import ClimateDevice from homeassistant.components.climate.const import ( HVAC_MODE_AUTO, HVAC_MODE_HEAT, HVAC_MODE_OFF, SUPPORT_PRESET_MODE, SUPPORT_TARGET_TEMPERATURE, PRESET_NONE, ) from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT, ) import homeassistant.helpers.config_validation as cv from homeassistant.util import Throttle from . import DOMAIN as NUHEAT_DOMAIN _LOGGER = logging.getLogger(__name__) MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=5) # Hold modes MODE_AUTO = HVAC_MODE_AUTO # Run device schedule MODE_HOLD_TEMPERATURE = "temperature" MODE_TEMPORARY_HOLD = "temporary_temperature" OPERATION_LIST = [HVAC_MODE_HEAT, HVAC_MODE_OFF] SCHEDULE_HOLD = 3 SCHEDULE_RUN = 1 SCHEDULE_TEMPORARY_HOLD = 2 SERVICE_RESUME_PROGRAM = "resume_program" RESUME_PROGRAM_SCHEMA = vol.Schema({vol.Optional(ATTR_ENTITY_ID): cv.entity_ids}) SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the NuHeat thermostat(s).""" if discovery_info is None: return temperature_unit = hass.config.units.temperature_unit api, serial_numbers = hass.data[NUHEAT_DOMAIN] thermostats = [ NuHeatThermostat(api, serial_number, temperature_unit) for serial_number in serial_numbers ] add_entities(thermostats, True) def resume_program_set_service(service): """Resume the program on the target thermostats.""" entity_id = service.data.get(ATTR_ENTITY_ID) if entity_id: target_thermostats = [ device for device in thermostats if device.entity_id in entity_id ] else: target_thermostats = thermostats for thermostat in target_thermostats: thermostat.resume_program() thermostat.schedule_update_ha_state(True) hass.services.register( NUHEAT_DOMAIN, SERVICE_RESUME_PROGRAM, resume_program_set_service, schema=RESUME_PROGRAM_SCHEMA, ) class NuHeatThermostat(ClimateDevice): """Representation of a NuHeat Thermostat.""" def __init__(self, api, serial_number, temperature_unit): """Initialize the thermostat.""" self._thermostat = api.get_thermostat(serial_number) self._temperature_unit = temperature_unit self._force_update = False @property def name(self): """Return the name of the thermostat.""" return self._thermostat.room @property def supported_features(self): """Return the list of supported features.""" return SUPPORT_FLAGS @property def temperature_unit(self): """Return the unit of measurement.""" if self._temperature_unit == "C": return TEMP_CELSIUS return TEMP_FAHRENHEIT @property def current_temperature(self): """Return the current temperature.""" if self._temperature_unit == "C": return self._thermostat.celsius return self._thermostat.fahrenheit @property def hvac_mode(self): """Return current operation. ie. heat, idle.""" if self._thermostat.heating: return HVAC_MODE_HEAT return HVAC_MODE_OFF @property def min_temp(self): """Return the minimum supported temperature for the thermostat.""" if self._temperature_unit == "C": return self._thermostat.min_celsius return self._thermostat.min_fahrenheit @property def max_temp(self): """Return the maximum supported temperature for the thermostat.""" if self._temperature_unit == "C": return self._thermostat.max_celsius return self._thermostat.max_fahrenheit @property def target_temperature(self): """Return the currently programmed temperature.""" if self._temperature_unit == "C": return self._thermostat.target_celsius return self._thermostat.target_fahrenheit @property def preset_mode(self): """Return current preset mode.""" schedule_mode = self._thermostat.schedule_mode if schedule_mode == SCHEDULE_RUN: return MODE_AUTO if schedule_mode == SCHEDULE_HOLD: return MODE_HOLD_TEMPERATURE if schedule_mode == SCHEDULE_TEMPORARY_HOLD: return MODE_TEMPORARY_HOLD return MODE_AUTO @property def preset_modes(self): """Return available preset modes.""" return [PRESET_NONE, MODE_HOLD_TEMPERATURE, MODE_TEMPORARY_HOLD] @property def hvac_modes(self): """Return list of possible operation modes.""" return OPERATION_LIST def resume_program(self): """Resume the thermostat's programmed schedule.""" self._thermostat.resume_schedule() self._force_update = True def set_preset_mode(self, preset_mode): """Update the hold mode of the thermostat.""" if preset_mode == PRESET_NONE: schedule_mode = SCHEDULE_RUN elif preset_mode == MODE_HOLD_TEMPERATURE: schedule_mode = SCHEDULE_HOLD elif preset_mode == MODE_TEMPORARY_HOLD: schedule_mode = SCHEDULE_TEMPORARY_HOLD self._thermostat.schedule_mode = schedule_mode self._force_update = True def set_temperature(self, **kwargs): """Set a new target temperature.""" temperature = kwargs.get(ATTR_TEMPERATURE) if self._temperature_unit == "C": self._thermostat.target_celsius = temperature else: self._thermostat.target_fahrenheit = temperature _LOGGER.debug( "Setting NuHeat thermostat temperature to %s %s", temperature, self.temperature_unit, ) self._force_update = True def update(self): """Get the latest state from the thermostat.""" if self._force_update: self._throttled_update(no_throttle=True) self._force_update = False else: self._throttled_update() @Throttle(MIN_TIME_BETWEEN_UPDATES) def _throttled_update(self, **kwargs): """Get the latest state from the thermostat with a throttle.""" self._thermostat.get_data()
"""Test the owntracks_http platform.""" import asyncio import pytest from homeassistant.setup import async_setup_component from homeassistant.components import owntracks from tests.common import mock_component, MockConfigEntry MINIMAL_LOCATION_MESSAGE = { "_type": "location", "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "tst": 1, } LOCATION_MESSAGE = { "_type": "location", "acc": 60, "alt": 27, "batt": 92, "cog": 248, "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "t": "u", "tst": 1, "vac": 4, "vel": 0, } @pytest.fixture(autouse=True) def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading.""" pass @pytest.fixture def mock_client(hass, aiohttp_client): """Start the Hass HTTP component.""" mock_component(hass, "group") mock_component(hass, "zone") mock_component(hass, "device_tracker") MockConfigEntry( domain="owntracks", data={"webhook_id": "owntracks_test", "secret": "abcd"} ).add_to_hass(hass) hass.loop.run_until_complete(async_setup_component(hass, "owntracks", {})) return hass.loop.run_until_complete(aiohttp_client(hass.http.app)) @asyncio.coroutine def test_handle_valid_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_valid_minimal_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=MINIMAL_LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_value_error(mock_client): """Test we don't disclose that this is a valid webhook.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json="", headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.text() assert json == "" @asyncio.coroutine def test_returns_error_missing_username(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-d": "Pixel"}, ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "No topic or user found" in caplog.text @asyncio.coroutine def test_returns_error_incorrect_json(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"} ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "invalid JSON" in caplog.text @asyncio.coroutine def test_returns_error_missing_device(mock_client): """Test that an error is returned when device name is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] def test_context_delivers_pending_msg(): """Test that context is able to hold pending messages while being init.""" context = owntracks.OwnTracksContext(None, None, None, None, None, None, None, None) context.async_see(hello="world") context.async_see(world="hello") received = [] context.set_async_see(lambda **data: received.append(data)) assert len(received) == 2 assert received[0] == {"hello": "world"} assert received[1] == {"world": "hello"} received.clear() context.set_async_see(lambda **data: received.append(data)) assert len(received) == 0
fbradyirl/home-assistant
tests/components/owntracks/test_init.py
homeassistant/components/nuheat/climate.py
"""Support for Homekit covers.""" import logging from homeassistant.components.cover import ( ATTR_POSITION, ATTR_TILT_POSITION, SUPPORT_CLOSE, SUPPORT_CLOSE_TILT, SUPPORT_OPEN, SUPPORT_OPEN_TILT, SUPPORT_SET_POSITION, SUPPORT_STOP, SUPPORT_SET_TILT_POSITION, CoverDevice, ) from homeassistant.const import STATE_CLOSED, STATE_CLOSING, STATE_OPEN, STATE_OPENING from . import KNOWN_DEVICES, HomeKitEntity STATE_STOPPED = "stopped" _LOGGER = logging.getLogger(__name__) CURRENT_GARAGE_STATE_MAP = { 0: STATE_OPEN, 1: STATE_CLOSED, 2: STATE_OPENING, 3: STATE_CLOSING, 4: STATE_STOPPED, } TARGET_GARAGE_STATE_MAP = {STATE_OPEN: 0, STATE_CLOSED: 1, STATE_STOPPED: 2} CURRENT_WINDOW_STATE_MAP = {0: STATE_OPENING, 1: STATE_CLOSING, 2: STATE_STOPPED} async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Legacy set up platform.""" pass async def async_setup_entry(hass, config_entry, async_add_entities): """Set up Homekit covers.""" hkid = config_entry.data["AccessoryPairingID"] conn = hass.data[KNOWN_DEVICES][hkid] def async_add_service(aid, service): info = {"aid": aid, "iid": service["iid"]} if service["stype"] == "garage-door-opener": async_add_entities([HomeKitGarageDoorCover(conn, info)], True) return True if service["stype"] in ("window-covering", "window"): async_add_entities([HomeKitWindowCover(conn, info)], True) return True return False conn.add_listener(async_add_service) class HomeKitGarageDoorCover(HomeKitEntity, CoverDevice): """Representation of a HomeKit Garage Door.""" def __init__(self, accessory, discovery_info): """Initialise the Cover.""" super().__init__(accessory, discovery_info) self._state = None self._obstruction_detected = None self.lock_state = None @property def device_class(self): """Define this cover as a garage door.""" return "garage" def get_characteristic_types(self): """Define the homekit characteristics the entity cares about.""" # pylint: disable=import-error from homekit.model.characteristics import CharacteristicsTypes return [ CharacteristicsTypes.DOOR_STATE_CURRENT, CharacteristicsTypes.DOOR_STATE_TARGET, CharacteristicsTypes.OBSTRUCTION_DETECTED, ] def _update_door_state_current(self, value): self._state = CURRENT_GARAGE_STATE_MAP[value] def _update_obstruction_detected(self, value): self._obstruction_detected = value @property def supported_features(self): """Flag supported features.""" return SUPPORT_OPEN | SUPPORT_CLOSE @property def is_closed(self): """Return true if cover is closed, else False.""" return self._state == STATE_CLOSED @property def is_closing(self): """Return if the cover is closing or not.""" return self._state == STATE_CLOSING @property def is_opening(self): """Return if the cover is opening or not.""" return self._state == STATE_OPENING async def async_open_cover(self, **kwargs): """Send open command.""" await self.set_door_state(STATE_OPEN) async def async_close_cover(self, **kwargs): """Send close command.""" await self.set_door_state(STATE_CLOSED) async def set_door_state(self, state): """Send state command.""" characteristics = [ { "aid": self._aid, "iid": self._chars["door-state.target"], "value": TARGET_GARAGE_STATE_MAP[state], } ] await self._accessory.put_characteristics(characteristics) @property def device_state_attributes(self): """Return the optional state attributes.""" if self._obstruction_detected is None: return None return {"obstruction-detected": self._obstruction_detected} class HomeKitWindowCover(HomeKitEntity, CoverDevice): """Representation of a HomeKit Window or Window Covering.""" def __init__(self, accessory, discovery_info): """Initialise the Cover.""" super().__init__(accessory, discovery_info) self._state = None self._position = None self._tilt_position = None self._obstruction_detected = None self.lock_state = None self._features = SUPPORT_OPEN | SUPPORT_CLOSE | SUPPORT_SET_POSITION def get_characteristic_types(self): """Define the homekit characteristics the entity cares about.""" # pylint: disable=import-error from homekit.model.characteristics import CharacteristicsTypes return [ CharacteristicsTypes.POSITION_STATE, CharacteristicsTypes.POSITION_CURRENT, CharacteristicsTypes.POSITION_TARGET, CharacteristicsTypes.POSITION_HOLD, CharacteristicsTypes.VERTICAL_TILT_CURRENT, CharacteristicsTypes.VERTICAL_TILT_TARGET, CharacteristicsTypes.HORIZONTAL_TILT_CURRENT, CharacteristicsTypes.HORIZONTAL_TILT_TARGET, CharacteristicsTypes.OBSTRUCTION_DETECTED, ] def _setup_position_hold(self, char): self._features |= SUPPORT_STOP def _setup_vertical_tilt_current(self, char): self._features |= ( SUPPORT_OPEN_TILT | SUPPORT_CLOSE_TILT | SUPPORT_SET_TILT_POSITION ) def _setup_horizontal_tilt_current(self, char): self._features |= ( SUPPORT_OPEN_TILT | SUPPORT_CLOSE_TILT | SUPPORT_SET_TILT_POSITION ) def _update_position_state(self, value): self._state = CURRENT_WINDOW_STATE_MAP[value] def _update_position_current(self, value): self._position = value def _update_vertical_tilt_current(self, value): self._tilt_position = value def _update_horizontal_tilt_current(self, value): self._tilt_position = value def _update_obstruction_detected(self, value): self._obstruction_detected = value @property def supported_features(self): """Flag supported features.""" return self._features @property def current_cover_position(self): """Return the current position of cover.""" return self._position @property def is_closed(self): """Return true if cover is closed, else False.""" return self._position == 0 @property def is_closing(self): """Return if the cover is closing or not.""" return self._state == STATE_CLOSING @property def is_opening(self): """Return if the cover is opening or not.""" return self._state == STATE_OPENING async def async_stop_cover(self, **kwargs): """Send hold command.""" characteristics = [ {"aid": self._aid, "iid": self._chars["position.hold"], "value": 1} ] await self._accessory.put_characteristics(characteristics) async def async_open_cover(self, **kwargs): """Send open command.""" await self.async_set_cover_position(position=100) async def async_close_cover(self, **kwargs): """Send close command.""" await self.async_set_cover_position(position=0) async def async_set_cover_position(self, **kwargs): """Send position command.""" position = kwargs[ATTR_POSITION] characteristics = [ {"aid": self._aid, "iid": self._chars["position.target"], "value": position} ] await self._accessory.put_characteristics(characteristics) @property def current_cover_tilt_position(self): """Return current position of cover tilt.""" return self._tilt_position async def async_set_cover_tilt_position(self, **kwargs): """Move the cover tilt to a specific position.""" tilt_position = kwargs[ATTR_TILT_POSITION] if "vertical-tilt.target" in self._chars: characteristics = [ { "aid": self._aid, "iid": self._chars["vertical-tilt.target"], "value": tilt_position, } ] await self._accessory.put_characteristics(characteristics) elif "horizontal-tilt.target" in self._chars: characteristics = [ { "aid": self._aid, "iid": self._chars["horizontal-tilt.target"], "value": tilt_position, } ] await self._accessory.put_characteristics(characteristics) @property def device_state_attributes(self): """Return the optional state attributes.""" state_attributes = {} if self._obstruction_detected is not None: state_attributes["obstruction-detected"] = self._obstruction_detected return state_attributes
"""Test the owntracks_http platform.""" import asyncio import pytest from homeassistant.setup import async_setup_component from homeassistant.components import owntracks from tests.common import mock_component, MockConfigEntry MINIMAL_LOCATION_MESSAGE = { "_type": "location", "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "tst": 1, } LOCATION_MESSAGE = { "_type": "location", "acc": 60, "alt": 27, "batt": 92, "cog": 248, "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "t": "u", "tst": 1, "vac": 4, "vel": 0, } @pytest.fixture(autouse=True) def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading.""" pass @pytest.fixture def mock_client(hass, aiohttp_client): """Start the Hass HTTP component.""" mock_component(hass, "group") mock_component(hass, "zone") mock_component(hass, "device_tracker") MockConfigEntry( domain="owntracks", data={"webhook_id": "owntracks_test", "secret": "abcd"} ).add_to_hass(hass) hass.loop.run_until_complete(async_setup_component(hass, "owntracks", {})) return hass.loop.run_until_complete(aiohttp_client(hass.http.app)) @asyncio.coroutine def test_handle_valid_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_valid_minimal_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=MINIMAL_LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_value_error(mock_client): """Test we don't disclose that this is a valid webhook.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json="", headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.text() assert json == "" @asyncio.coroutine def test_returns_error_missing_username(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-d": "Pixel"}, ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "No topic or user found" in caplog.text @asyncio.coroutine def test_returns_error_incorrect_json(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"} ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "invalid JSON" in caplog.text @asyncio.coroutine def test_returns_error_missing_device(mock_client): """Test that an error is returned when device name is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] def test_context_delivers_pending_msg(): """Test that context is able to hold pending messages while being init.""" context = owntracks.OwnTracksContext(None, None, None, None, None, None, None, None) context.async_see(hello="world") context.async_see(world="hello") received = [] context.set_async_see(lambda **data: received.append(data)) assert len(received) == 2 assert received[0] == {"hello": "world"} assert received[1] == {"world": "hello"} received.clear() context.set_async_see(lambda **data: received.append(data)) assert len(received) == 0
fbradyirl/home-assistant
tests/components/owntracks/test_init.py
homeassistant/components/homekit_controller/cover.py
"""Support for Telegram bot using polling.""" import logging from homeassistant.const import EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP from homeassistant.core import callback from . import CONF_ALLOWED_CHAT_IDS, BaseTelegramBotEntity, initialize_bot _LOGGER = logging.getLogger(__name__) async def async_setup_platform(hass, config): """Set up the Telegram polling platform.""" bot = initialize_bot(config) pol = TelegramPoll(bot, hass, config[CONF_ALLOWED_CHAT_IDS]) @callback def _start_bot(_event): """Start the bot.""" pol.start_polling() @callback def _stop_bot(_event): """Stop the bot.""" pol.stop_polling() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, _start_bot) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _stop_bot) return True def process_error(bot, update, error): """Telegram bot error handler.""" from telegram.error import TelegramError, TimedOut, NetworkError, RetryAfter try: raise error except (TimedOut, NetworkError, RetryAfter): # Long polling timeout or connection problem. Nothing serious. pass except TelegramError: _LOGGER.error('Update "%s" caused error "%s"', update, error) def message_handler(handler): """Create messages handler.""" from telegram import Update from telegram.ext import Handler class MessageHandler(Handler): """Telegram bot message handler.""" def __init__(self): """Initialize the messages handler instance.""" super().__init__(handler) def check_update(self, update): # pylint: disable=no-self-use """Check is update valid.""" return isinstance(update, Update) def handle_update(self, update, dispatcher): """Handle update.""" optional_args = self.collect_optional_args(dispatcher, update) return self.callback(dispatcher.bot, update, **optional_args) return MessageHandler() class TelegramPoll(BaseTelegramBotEntity): """Asyncio telegram incoming message handler.""" def __init__(self, bot, hass, allowed_chat_ids): """Initialize the polling instance.""" from telegram.ext import Updater BaseTelegramBotEntity.__init__(self, hass, allowed_chat_ids) self.updater = Updater(bot=bot, workers=4) self.dispatcher = self.updater.dispatcher self.dispatcher.add_handler(message_handler(self.process_update)) self.dispatcher.add_error_handler(process_error) def start_polling(self): """Start the polling task.""" self.updater.start_polling() def stop_polling(self): """Stop the polling task.""" self.updater.stop() def process_update(self, bot, update): """Process incoming message.""" self.process_message(update.to_dict())
"""Test the owntracks_http platform.""" import asyncio import pytest from homeassistant.setup import async_setup_component from homeassistant.components import owntracks from tests.common import mock_component, MockConfigEntry MINIMAL_LOCATION_MESSAGE = { "_type": "location", "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "tst": 1, } LOCATION_MESSAGE = { "_type": "location", "acc": 60, "alt": 27, "batt": 92, "cog": 248, "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "t": "u", "tst": 1, "vac": 4, "vel": 0, } @pytest.fixture(autouse=True) def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading.""" pass @pytest.fixture def mock_client(hass, aiohttp_client): """Start the Hass HTTP component.""" mock_component(hass, "group") mock_component(hass, "zone") mock_component(hass, "device_tracker") MockConfigEntry( domain="owntracks", data={"webhook_id": "owntracks_test", "secret": "abcd"} ).add_to_hass(hass) hass.loop.run_until_complete(async_setup_component(hass, "owntracks", {})) return hass.loop.run_until_complete(aiohttp_client(hass.http.app)) @asyncio.coroutine def test_handle_valid_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_valid_minimal_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=MINIMAL_LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_value_error(mock_client): """Test we don't disclose that this is a valid webhook.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json="", headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.text() assert json == "" @asyncio.coroutine def test_returns_error_missing_username(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-d": "Pixel"}, ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "No topic or user found" in caplog.text @asyncio.coroutine def test_returns_error_incorrect_json(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"} ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "invalid JSON" in caplog.text @asyncio.coroutine def test_returns_error_missing_device(mock_client): """Test that an error is returned when device name is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] def test_context_delivers_pending_msg(): """Test that context is able to hold pending messages while being init.""" context = owntracks.OwnTracksContext(None, None, None, None, None, None, None, None) context.async_see(hello="world") context.async_see(world="hello") received = [] context.set_async_see(lambda **data: received.append(data)) assert len(received) == 2 assert received[0] == {"hello": "world"} assert received[1] == {"world": "hello"} received.clear() context.set_async_see(lambda **data: received.append(data)) assert len(received) == 0
fbradyirl/home-assistant
tests/components/owntracks/test_init.py
homeassistant/components/telegram_bot/polling.py
"""Constants for Google Hangouts Component.""" import logging import voluptuous as vol from homeassistant.components.notify import ATTR_DATA, ATTR_MESSAGE, ATTR_TARGET import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(".") DOMAIN = "hangouts" CONF_2FA = "2fa" CONF_AUTH_CODE = "authorization_code" CONF_REFRESH_TOKEN = "refresh_token" CONF_BOT = "bot" CONF_CONVERSATIONS = "conversations" CONF_DEFAULT_CONVERSATIONS = "default_conversations" CONF_ERROR_SUPPRESSED_CONVERSATIONS = "error_suppressed_conversations" CONF_INTENTS = "intents" CONF_INTENT_TYPE = "intent_type" CONF_SENTENCES = "sentences" CONF_MATCHERS = "matchers" INTENT_HELP = "HangoutsHelp" EVENT_HANGOUTS_CONNECTED = "hangouts_connected" EVENT_HANGOUTS_DISCONNECTED = "hangouts_disconnected" EVENT_HANGOUTS_USERS_CHANGED = "hangouts_users_changed" EVENT_HANGOUTS_CONVERSATIONS_CHANGED = "hangouts_conversations_changed" EVENT_HANGOUTS_CONVERSATIONS_RESOLVED = "hangouts_conversations_resolved" EVENT_HANGOUTS_MESSAGE_RECEIVED = "hangouts_message_received" CONF_CONVERSATION_ID = "id" CONF_CONVERSATION_NAME = "name" SERVICE_SEND_MESSAGE = "send_message" SERVICE_UPDATE = "update" SERVICE_RECONNECT = "reconnect" TARGETS_SCHEMA = vol.All( vol.Schema( { vol.Exclusive(CONF_CONVERSATION_ID, "id or name"): cv.string, vol.Exclusive(CONF_CONVERSATION_NAME, "id or name"): cv.string, } ), cv.has_at_least_one_key(CONF_CONVERSATION_ID, CONF_CONVERSATION_NAME), ) MESSAGE_SEGMENT_SCHEMA = vol.Schema( { vol.Required("text"): cv.string, vol.Optional("is_bold"): cv.boolean, vol.Optional("is_italic"): cv.boolean, vol.Optional("is_strikethrough"): cv.boolean, vol.Optional("is_underline"): cv.boolean, vol.Optional("parse_str"): cv.boolean, vol.Optional("link_target"): cv.string, } ) MESSAGE_DATA_SCHEMA = vol.Schema( {vol.Optional("image_file"): cv.string, vol.Optional("image_url"): cv.string} ) MESSAGE_SCHEMA = vol.Schema( { vol.Required(ATTR_TARGET): [TARGETS_SCHEMA], vol.Required(ATTR_MESSAGE): [MESSAGE_SEGMENT_SCHEMA], vol.Optional(ATTR_DATA): MESSAGE_DATA_SCHEMA, } ) INTENT_SCHEMA = vol.All( # Basic Schema vol.Schema( { vol.Required(CONF_SENTENCES): vol.All(cv.ensure_list, [cv.string]), vol.Optional(CONF_CONVERSATIONS): [TARGETS_SCHEMA], } ) )
"""Test the owntracks_http platform.""" import asyncio import pytest from homeassistant.setup import async_setup_component from homeassistant.components import owntracks from tests.common import mock_component, MockConfigEntry MINIMAL_LOCATION_MESSAGE = { "_type": "location", "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "tst": 1, } LOCATION_MESSAGE = { "_type": "location", "acc": 60, "alt": 27, "batt": 92, "cog": 248, "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "t": "u", "tst": 1, "vac": 4, "vel": 0, } @pytest.fixture(autouse=True) def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading.""" pass @pytest.fixture def mock_client(hass, aiohttp_client): """Start the Hass HTTP component.""" mock_component(hass, "group") mock_component(hass, "zone") mock_component(hass, "device_tracker") MockConfigEntry( domain="owntracks", data={"webhook_id": "owntracks_test", "secret": "abcd"} ).add_to_hass(hass) hass.loop.run_until_complete(async_setup_component(hass, "owntracks", {})) return hass.loop.run_until_complete(aiohttp_client(hass.http.app)) @asyncio.coroutine def test_handle_valid_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_valid_minimal_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=MINIMAL_LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_value_error(mock_client): """Test we don't disclose that this is a valid webhook.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json="", headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.text() assert json == "" @asyncio.coroutine def test_returns_error_missing_username(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-d": "Pixel"}, ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "No topic or user found" in caplog.text @asyncio.coroutine def test_returns_error_incorrect_json(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"} ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "invalid JSON" in caplog.text @asyncio.coroutine def test_returns_error_missing_device(mock_client): """Test that an error is returned when device name is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] def test_context_delivers_pending_msg(): """Test that context is able to hold pending messages while being init.""" context = owntracks.OwnTracksContext(None, None, None, None, None, None, None, None) context.async_see(hello="world") context.async_see(world="hello") received = [] context.set_async_see(lambda **data: received.append(data)) assert len(received) == 2 assert received[0] == {"hello": "world"} assert received[1] == {"world": "hello"} received.clear() context.set_async_see(lambda **data: received.append(data)) assert len(received) == 0
fbradyirl/home-assistant
tests/components/owntracks/test_init.py
homeassistant/components/hangouts/const.py
"""SMA Solar Webconnect interface.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_SCAN_INTERVAL, CONF_SSL, CONF_VERIFY_SSL, EVENT_HOMEASSISTANT_STOP, CONF_PATH, ) from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity from homeassistant.helpers.event import async_track_time_interval _LOGGER = logging.getLogger(__name__) CONF_CUSTOM = "custom" CONF_FACTOR = "factor" CONF_GROUP = "group" CONF_KEY = "key" CONF_SENSORS = "sensors" CONF_UNIT = "unit" GROUPS = ["user", "installer"] def _check_sensor_schema(conf): """Check sensors and attributes are valid.""" try: import pysma valid = [s.name for s in pysma.Sensors()] except (ImportError, AttributeError): return conf for name in conf[CONF_CUSTOM]: valid.append(name) for sname, attrs in conf[CONF_SENSORS].items(): if sname not in valid: raise vol.Invalid("{} does not exist".format(sname)) for attr in attrs: if attr in valid: continue raise vol.Invalid("{} does not exist [{}]".format(attr, sname)) return conf CUSTOM_SCHEMA = vol.Any( { vol.Required(CONF_KEY): vol.All(cv.string, vol.Length(min=13, max=15)), vol.Required(CONF_UNIT): cv.string, vol.Optional(CONF_FACTOR, default=1): vol.Coerce(float), vol.Optional(CONF_PATH): vol.All(cv.ensure_list, [str]), } ) PLATFORM_SCHEMA = vol.All( PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_SSL, default=False): cv.boolean, vol.Optional(CONF_VERIFY_SSL, default=True): cv.boolean, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_GROUP, default=GROUPS[0]): vol.In(GROUPS), vol.Optional(CONF_SENSORS, default={}): cv.schema_with_slug_keys( cv.ensure_list ), vol.Optional(CONF_CUSTOM, default={}): cv.schema_with_slug_keys( CUSTOM_SCHEMA ), }, extra=vol.PREVENT_EXTRA, ), _check_sensor_schema, ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up SMA WebConnect sensor.""" import pysma # Check config again during load - dependency available config = _check_sensor_schema(config) # Init all default sensors sensor_def = pysma.Sensors() # Sensor from the custom config sensor_def.add( [ pysma.Sensor(o[CONF_KEY], n, o[CONF_UNIT], o[CONF_FACTOR], o.get(CONF_PATH)) for n, o in config[CONF_CUSTOM].items() ] ) # Use all sensors by default config_sensors = config[CONF_SENSORS] if not config_sensors: config_sensors = {s.name: [] for s in sensor_def} # Prepare all HASS sensor entities hass_sensors = [] used_sensors = [] for name, attr in config_sensors.items(): sub_sensors = [sensor_def[s] for s in attr] hass_sensors.append(SMAsensor(sensor_def[name], sub_sensors)) used_sensors.append(name) used_sensors.extend(attr) async_add_entities(hass_sensors) used_sensors = [sensor_def[s] for s in set(used_sensors)] # Init the SMA interface session = async_get_clientsession(hass, verify_ssl=config[CONF_VERIFY_SSL]) grp = config[CONF_GROUP] url = "http{}://{}".format("s" if config[CONF_SSL] else "", config[CONF_HOST]) sma = pysma.SMA(session, url, config[CONF_PASSWORD], group=grp) # Ensure we logout on shutdown async def async_close_session(event): """Close the session.""" await sma.close_session() hass.bus.async_listen(EVENT_HOMEASSISTANT_STOP, async_close_session) backoff = 0 backoff_step = 0 async def async_sma(event): """Update all the SMA sensors.""" nonlocal backoff, backoff_step if backoff > 1: backoff -= 1 return values = await sma.read(used_sensors) if not values: try: backoff = [1, 1, 1, 6, 30][backoff_step] backoff_step += 1 except IndexError: backoff = 60 return backoff_step = 0 tasks = [] for sensor in hass_sensors: task = sensor.async_update_values() if task: tasks.append(task) if tasks: await asyncio.wait(tasks) interval = config.get(CONF_SCAN_INTERVAL) or timedelta(seconds=5) async_track_time_interval(hass, async_sma, interval) class SMAsensor(Entity): """Representation of a SMA sensor.""" def __init__(self, pysma_sensor, sub_sensors): """Initialize the sensor.""" self._sensor = pysma_sensor self._sub_sensors = sub_sensors self._attr = {s.name: "" for s in sub_sensors} self._state = self._sensor.value @property def name(self): """Return the name of the sensor.""" return self._sensor.name @property def state(self): """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return self._sensor.unit @property def device_state_attributes(self): """Return the state attributes of the sensor.""" return self._attr @property def poll(self): """SMA sensors are updated & don't poll.""" return False def async_update_values(self): """Update this sensor.""" update = False for sens in self._sub_sensors: newval = "{} {}".format(sens.value, sens.unit) if self._attr[sens.name] != newval: update = True self._attr[sens.name] = newval if self._sensor.value != self._state: update = True self._state = self._sensor.value return self.async_update_ha_state() if update else None @property def unique_id(self): """Return a unique identifier for this sensor.""" return "sma-{}-{}".format(self._sensor.key, self._sensor.name)
"""Test the owntracks_http platform.""" import asyncio import pytest from homeassistant.setup import async_setup_component from homeassistant.components import owntracks from tests.common import mock_component, MockConfigEntry MINIMAL_LOCATION_MESSAGE = { "_type": "location", "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "tst": 1, } LOCATION_MESSAGE = { "_type": "location", "acc": 60, "alt": 27, "batt": 92, "cog": 248, "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "t": "u", "tst": 1, "vac": 4, "vel": 0, } @pytest.fixture(autouse=True) def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading.""" pass @pytest.fixture def mock_client(hass, aiohttp_client): """Start the Hass HTTP component.""" mock_component(hass, "group") mock_component(hass, "zone") mock_component(hass, "device_tracker") MockConfigEntry( domain="owntracks", data={"webhook_id": "owntracks_test", "secret": "abcd"} ).add_to_hass(hass) hass.loop.run_until_complete(async_setup_component(hass, "owntracks", {})) return hass.loop.run_until_complete(aiohttp_client(hass.http.app)) @asyncio.coroutine def test_handle_valid_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_valid_minimal_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=MINIMAL_LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_value_error(mock_client): """Test we don't disclose that this is a valid webhook.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json="", headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.text() assert json == "" @asyncio.coroutine def test_returns_error_missing_username(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-d": "Pixel"}, ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "No topic or user found" in caplog.text @asyncio.coroutine def test_returns_error_incorrect_json(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"} ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "invalid JSON" in caplog.text @asyncio.coroutine def test_returns_error_missing_device(mock_client): """Test that an error is returned when device name is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] def test_context_delivers_pending_msg(): """Test that context is able to hold pending messages while being init.""" context = owntracks.OwnTracksContext(None, None, None, None, None, None, None, None) context.async_see(hello="world") context.async_see(world="hello") received = [] context.set_async_see(lambda **data: received.append(data)) assert len(received) == 2 assert received[0] == {"hello": "world"} assert received[1] == {"world": "hello"} received.clear() context.set_async_see(lambda **data: received.append(data)) assert len(received) == 0
fbradyirl/home-assistant
tests/components/owntracks/test_init.py
homeassistant/components/sma/sensor.py
"""Common utilities for VeSync Component.""" import logging from homeassistant.helpers.entity import ToggleEntity from .const import VS_SWITCHES _LOGGER = logging.getLogger(__name__) async def async_process_devices(hass, manager): """Assign devices to proper component.""" devices = {} devices[VS_SWITCHES] = [] await hass.async_add_executor_job(manager.update) if manager.outlets: devices[VS_SWITCHES].extend(manager.outlets) _LOGGER.info("%d VeSync outlets found", len(manager.outlets)) if manager.switches: for switch in manager.switches: if not switch.is_dimmable(): devices[VS_SWITCHES].append(switch) _LOGGER.info("%d VeSync standard switches found", len(manager.switches)) return devices class VeSyncDevice(ToggleEntity): """Base class for VeSync Device Representations.""" def __init__(self, device): """Initialize the VeSync device.""" self.device = device @property def unique_id(self): """Return the ID of this device.""" if isinstance(self.device.sub_device_no, int): return "{}{}".format(self.device.cid, str(self.device.sub_device_no)) return self.device.cid @property def name(self): """Return the name of the device.""" return self.device.device_name @property def is_on(self): """Return True if switch is on.""" return self.device.device_status == "on" @property def available(self) -> bool: """Return True if device is available.""" return self.device.connection_status == "online" def turn_on(self, **kwargs): """Turn the device on.""" self.device.turn_on() def turn_off(self, **kwargs): """Turn the device off.""" self.device.turn_off() def update(self): """Update vesync device.""" self.device.update()
"""Test the owntracks_http platform.""" import asyncio import pytest from homeassistant.setup import async_setup_component from homeassistant.components import owntracks from tests.common import mock_component, MockConfigEntry MINIMAL_LOCATION_MESSAGE = { "_type": "location", "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "tst": 1, } LOCATION_MESSAGE = { "_type": "location", "acc": 60, "alt": 27, "batt": 92, "cog": 248, "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "t": "u", "tst": 1, "vac": 4, "vel": 0, } @pytest.fixture(autouse=True) def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading.""" pass @pytest.fixture def mock_client(hass, aiohttp_client): """Start the Hass HTTP component.""" mock_component(hass, "group") mock_component(hass, "zone") mock_component(hass, "device_tracker") MockConfigEntry( domain="owntracks", data={"webhook_id": "owntracks_test", "secret": "abcd"} ).add_to_hass(hass) hass.loop.run_until_complete(async_setup_component(hass, "owntracks", {})) return hass.loop.run_until_complete(aiohttp_client(hass.http.app)) @asyncio.coroutine def test_handle_valid_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_valid_minimal_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=MINIMAL_LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_value_error(mock_client): """Test we don't disclose that this is a valid webhook.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json="", headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.text() assert json == "" @asyncio.coroutine def test_returns_error_missing_username(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-d": "Pixel"}, ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "No topic or user found" in caplog.text @asyncio.coroutine def test_returns_error_incorrect_json(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"} ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "invalid JSON" in caplog.text @asyncio.coroutine def test_returns_error_missing_device(mock_client): """Test that an error is returned when device name is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] def test_context_delivers_pending_msg(): """Test that context is able to hold pending messages while being init.""" context = owntracks.OwnTracksContext(None, None, None, None, None, None, None, None) context.async_see(hello="world") context.async_see(world="hello") received = [] context.set_async_see(lambda **data: received.append(data)) assert len(received) == 2 assert received[0] == {"hello": "world"} assert received[1] == {"world": "hello"} received.clear() context.set_async_see(lambda **data: received.append(data)) assert len(received) == 0
fbradyirl/home-assistant
tests/components/owntracks/test_init.py
homeassistant/components/vesync/common.py
"""Support for RESTful API sensors.""" import logging import json import voluptuous as vol import requests from requests.auth import HTTPBasicAuth, HTTPDigestAuth from homeassistant.components.sensor import PLATFORM_SCHEMA, DEVICE_CLASSES_SCHEMA from homeassistant.const import ( CONF_AUTHENTICATION, CONF_FORCE_UPDATE, CONF_HEADERS, CONF_NAME, CONF_METHOD, CONF_PASSWORD, CONF_PAYLOAD, CONF_RESOURCE, CONF_UNIT_OF_MEASUREMENT, CONF_USERNAME, CONF_TIMEOUT, CONF_VALUE_TEMPLATE, CONF_VERIFY_SSL, CONF_DEVICE_CLASS, HTTP_BASIC_AUTHENTICATION, HTTP_DIGEST_AUTHENTICATION, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.entity import Entity import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) DEFAULT_METHOD = "GET" DEFAULT_NAME = "REST Sensor" DEFAULT_VERIFY_SSL = True DEFAULT_FORCE_UPDATE = False DEFAULT_TIMEOUT = 10 CONF_JSON_ATTRS = "json_attributes" METHODS = ["POST", "GET"] PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_RESOURCE): cv.url, vol.Optional(CONF_AUTHENTICATION): vol.In( [HTTP_BASIC_AUTHENTICATION, HTTP_DIGEST_AUTHENTICATION] ), vol.Optional(CONF_HEADERS): vol.Schema({cv.string: cv.string}), vol.Optional(CONF_JSON_ATTRS, default=[]): cv.ensure_list_csv, vol.Optional(CONF_METHOD, default=DEFAULT_METHOD): vol.In(METHODS), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_PASSWORD): cv.string, vol.Optional(CONF_PAYLOAD): cv.string, vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string, vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA, vol.Optional(CONF_USERNAME): cv.string, vol.Optional(CONF_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean, vol.Optional(CONF_FORCE_UPDATE, default=DEFAULT_FORCE_UPDATE): cv.boolean, vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the RESTful sensor.""" name = config.get(CONF_NAME) resource = config.get(CONF_RESOURCE) method = config.get(CONF_METHOD) payload = config.get(CONF_PAYLOAD) verify_ssl = config.get(CONF_VERIFY_SSL) username = config.get(CONF_USERNAME) password = config.get(CONF_PASSWORD) headers = config.get(CONF_HEADERS) unit = config.get(CONF_UNIT_OF_MEASUREMENT) device_class = config.get(CONF_DEVICE_CLASS) value_template = config.get(CONF_VALUE_TEMPLATE) json_attrs = config.get(CONF_JSON_ATTRS) force_update = config.get(CONF_FORCE_UPDATE) timeout = config.get(CONF_TIMEOUT) if value_template is not None: value_template.hass = hass if username and password: if config.get(CONF_AUTHENTICATION) == HTTP_DIGEST_AUTHENTICATION: auth = HTTPDigestAuth(username, password) else: auth = HTTPBasicAuth(username, password) else: auth = None rest = RestData(method, resource, auth, headers, payload, verify_ssl, timeout) rest.update() if rest.data is None: raise PlatformNotReady # Must update the sensor now (including fetching the rest resource) to # ensure it's updating its state. add_entities( [ RestSensor( hass, rest, name, unit, device_class, value_template, json_attrs, force_update, ) ], True, ) class RestSensor(Entity): """Implementation of a REST sensor.""" def __init__( self, hass, rest, name, unit_of_measurement, device_class, value_template, json_attrs, force_update, ): """Initialize the REST sensor.""" self._hass = hass self.rest = rest self._name = name self._state = None self._unit_of_measurement = unit_of_measurement self._device_class = device_class self._value_template = value_template self._json_attrs = json_attrs self._attributes = None self._force_update = force_update @property def name(self): """Return the name of the sensor.""" return self._name @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return self._unit_of_measurement @property def device_class(self): """Return the class of this sensor.""" return self._device_class @property def available(self): """Return if the sensor data are available.""" return self.rest.data is not None @property def state(self): """Return the state of the device.""" return self._state @property def force_update(self): """Force update.""" return self._force_update def update(self): """Get the latest data from REST API and update the state.""" self.rest.update() value = self.rest.data if self._json_attrs: self._attributes = {} if value: try: json_dict = json.loads(value) if isinstance(json_dict, dict): attrs = { k: json_dict[k] for k in self._json_attrs if k in json_dict } self._attributes = attrs else: _LOGGER.warning("JSON result was not a dictionary") except ValueError: _LOGGER.warning("REST result could not be parsed as JSON") _LOGGER.debug("Erroneous JSON: %s", value) else: _LOGGER.warning("Empty reply found when expecting JSON data") if value is not None and self._value_template is not None: value = self._value_template.render_with_possible_json_value(value, None) self._state = value @property def device_state_attributes(self): """Return the state attributes.""" return self._attributes class RestData: """Class for handling the data retrieval.""" def __init__( self, method, resource, auth, headers, data, verify_ssl, timeout=DEFAULT_TIMEOUT ): """Initialize the data object.""" self._request = requests.Request( method, resource, headers=headers, auth=auth, data=data ).prepare() self._verify_ssl = verify_ssl self._timeout = timeout self.data = None def update(self): """Get the latest data from REST service with provided method.""" _LOGGER.debug("Updating from %s", self._request.url) try: with requests.Session() as sess: response = sess.send( self._request, timeout=self._timeout, verify=self._verify_ssl ) self.data = response.text except requests.exceptions.RequestException as ex: _LOGGER.error( "Error fetching data: %s from %s failed with %s", self._request, self._request.url, ex, ) self.data = None
"""Test the owntracks_http platform.""" import asyncio import pytest from homeassistant.setup import async_setup_component from homeassistant.components import owntracks from tests.common import mock_component, MockConfigEntry MINIMAL_LOCATION_MESSAGE = { "_type": "location", "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "tst": 1, } LOCATION_MESSAGE = { "_type": "location", "acc": 60, "alt": 27, "batt": 92, "cog": 248, "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "t": "u", "tst": 1, "vac": 4, "vel": 0, } @pytest.fixture(autouse=True) def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading.""" pass @pytest.fixture def mock_client(hass, aiohttp_client): """Start the Hass HTTP component.""" mock_component(hass, "group") mock_component(hass, "zone") mock_component(hass, "device_tracker") MockConfigEntry( domain="owntracks", data={"webhook_id": "owntracks_test", "secret": "abcd"} ).add_to_hass(hass) hass.loop.run_until_complete(async_setup_component(hass, "owntracks", {})) return hass.loop.run_until_complete(aiohttp_client(hass.http.app)) @asyncio.coroutine def test_handle_valid_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_valid_minimal_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=MINIMAL_LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_value_error(mock_client): """Test we don't disclose that this is a valid webhook.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json="", headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.text() assert json == "" @asyncio.coroutine def test_returns_error_missing_username(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-d": "Pixel"}, ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "No topic or user found" in caplog.text @asyncio.coroutine def test_returns_error_incorrect_json(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"} ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "invalid JSON" in caplog.text @asyncio.coroutine def test_returns_error_missing_device(mock_client): """Test that an error is returned when device name is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] def test_context_delivers_pending_msg(): """Test that context is able to hold pending messages while being init.""" context = owntracks.OwnTracksContext(None, None, None, None, None, None, None, None) context.async_see(hello="world") context.async_see(world="hello") received = [] context.set_async_see(lambda **data: received.append(data)) assert len(received) == 2 assert received[0] == {"hello": "world"} assert received[1] == {"world": "hello"} received.clear() context.set_async_see(lambda **data: received.append(data)) assert len(received) == 0
fbradyirl/home-assistant
tests/components/owntracks/test_init.py
homeassistant/components/rest/sensor.py
"""Http views to control the config manager.""" from homeassistant import config_entries, data_entry_flow from homeassistant.auth.permissions.const import CAT_CONFIG_ENTRIES from homeassistant.components.http import HomeAssistantView from homeassistant.exceptions import Unauthorized from homeassistant.helpers.data_entry_flow import ( FlowManagerIndexView, FlowManagerResourceView, ) from homeassistant.loader import async_get_config_flows async def async_setup(hass): """Enable the Home Assistant views.""" hass.http.register_view(ConfigManagerEntryIndexView) hass.http.register_view(ConfigManagerEntryResourceView) hass.http.register_view(ConfigManagerFlowIndexView(hass.config_entries.flow)) hass.http.register_view(ConfigManagerFlowResourceView(hass.config_entries.flow)) hass.http.register_view(ConfigManagerAvailableFlowView) hass.http.register_view( OptionManagerFlowIndexView(hass.config_entries.options.flow) ) hass.http.register_view( OptionManagerFlowResourceView(hass.config_entries.options.flow) ) return True def _prepare_json(result): """Convert result for JSON.""" if result["type"] != data_entry_flow.RESULT_TYPE_FORM: return result import voluptuous_serialize data = result.copy() schema = data["data_schema"] if schema is None: data["data_schema"] = [] else: data["data_schema"] = voluptuous_serialize.convert(schema) return data class ConfigManagerEntryIndexView(HomeAssistantView): """View to get available config entries.""" url = "/api/config/config_entries/entry" name = "api:config:config_entries:entry" async def get(self, request): """List available config entries.""" hass = request.app["hass"] return self.json( [ { "entry_id": entry.entry_id, "domain": entry.domain, "title": entry.title, "source": entry.source, "state": entry.state, "connection_class": entry.connection_class, "supports_options": hasattr( config_entries.HANDLERS.get(entry.domain), "async_get_options_flow", ), } for entry in hass.config_entries.async_entries() ] ) class ConfigManagerEntryResourceView(HomeAssistantView): """View to interact with a config entry.""" url = "/api/config/config_entries/entry/{entry_id}" name = "api:config:config_entries:entry:resource" async def delete(self, request, entry_id): """Delete a config entry.""" if not request["hass_user"].is_admin: raise Unauthorized(config_entry_id=entry_id, permission="remove") hass = request.app["hass"] try: result = await hass.config_entries.async_remove(entry_id) except config_entries.UnknownEntry: return self.json_message("Invalid entry specified", 404) return self.json(result) class ConfigManagerFlowIndexView(FlowManagerIndexView): """View to create config flows.""" url = "/api/config/config_entries/flow" name = "api:config:config_entries:flow" async def get(self, request): """List flows that are in progress but not started by a user. Example of a non-user initiated flow is a discovered Hue hub that requires user interaction to finish setup. """ if not request["hass_user"].is_admin: raise Unauthorized(perm_category=CAT_CONFIG_ENTRIES, permission="add") hass = request.app["hass"] return self.json( [ flw for flw in hass.config_entries.flow.async_progress() if flw["context"]["source"] != config_entries.SOURCE_USER ] ) # pylint: disable=arguments-differ async def post(self, request): """Handle a POST request.""" if not request["hass_user"].is_admin: raise Unauthorized(perm_category=CAT_CONFIG_ENTRIES, permission="add") # pylint: disable=no-value-for-parameter return await super().post(request) def _prepare_result_json(self, result): """Convert result to JSON.""" if result["type"] != data_entry_flow.RESULT_TYPE_CREATE_ENTRY: return super()._prepare_result_json(result) data = result.copy() data["result"] = data["result"].entry_id data.pop("data") return data class ConfigManagerFlowResourceView(FlowManagerResourceView): """View to interact with the flow manager.""" url = "/api/config/config_entries/flow/{flow_id}" name = "api:config:config_entries:flow:resource" async def get(self, request, flow_id): """Get the current state of a data_entry_flow.""" if not request["hass_user"].is_admin: raise Unauthorized(perm_category=CAT_CONFIG_ENTRIES, permission="add") return await super().get(request, flow_id) # pylint: disable=arguments-differ async def post(self, request, flow_id): """Handle a POST request.""" if not request["hass_user"].is_admin: raise Unauthorized(perm_category=CAT_CONFIG_ENTRIES, permission="add") # pylint: disable=no-value-for-parameter return await super().post(request, flow_id) def _prepare_result_json(self, result): """Convert result to JSON.""" if result["type"] != data_entry_flow.RESULT_TYPE_CREATE_ENTRY: return super()._prepare_result_json(result) data = result.copy() data["result"] = data["result"].entry_id data.pop("data") return data class ConfigManagerAvailableFlowView(HomeAssistantView): """View to query available flows.""" url = "/api/config/config_entries/flow_handlers" name = "api:config:config_entries:flow_handlers" async def get(self, request): """List available flow handlers.""" hass = request.app["hass"] return self.json(await async_get_config_flows(hass)) class OptionManagerFlowIndexView(FlowManagerIndexView): """View to create option flows.""" url = "/api/config/config_entries/entry/option/flow" name = "api:config:config_entries:entry:resource:option:flow" # pylint: disable=arguments-differ async def post(self, request): """Handle a POST request. handler in request is entry_id. """ if not request["hass_user"].is_admin: raise Unauthorized(perm_category=CAT_CONFIG_ENTRIES, permission="edit") # pylint: disable=no-value-for-parameter return await super().post(request) class OptionManagerFlowResourceView(FlowManagerResourceView): """View to interact with the option flow manager.""" url = "/api/config/config_entries/options/flow/{flow_id}" name = "api:config:config_entries:options:flow:resource" async def get(self, request, flow_id): """Get the current state of a data_entry_flow.""" if not request["hass_user"].is_admin: raise Unauthorized(perm_category=CAT_CONFIG_ENTRIES, permission="edit") return await super().get(request, flow_id) # pylint: disable=arguments-differ async def post(self, request, flow_id): """Handle a POST request.""" if not request["hass_user"].is_admin: raise Unauthorized(perm_category=CAT_CONFIG_ENTRIES, permission="edit") # pylint: disable=no-value-for-parameter return await super().post(request, flow_id)
"""Test the owntracks_http platform.""" import asyncio import pytest from homeassistant.setup import async_setup_component from homeassistant.components import owntracks from tests.common import mock_component, MockConfigEntry MINIMAL_LOCATION_MESSAGE = { "_type": "location", "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "tst": 1, } LOCATION_MESSAGE = { "_type": "location", "acc": 60, "alt": 27, "batt": 92, "cog": 248, "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "t": "u", "tst": 1, "vac": 4, "vel": 0, } @pytest.fixture(autouse=True) def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading.""" pass @pytest.fixture def mock_client(hass, aiohttp_client): """Start the Hass HTTP component.""" mock_component(hass, "group") mock_component(hass, "zone") mock_component(hass, "device_tracker") MockConfigEntry( domain="owntracks", data={"webhook_id": "owntracks_test", "secret": "abcd"} ).add_to_hass(hass) hass.loop.run_until_complete(async_setup_component(hass, "owntracks", {})) return hass.loop.run_until_complete(aiohttp_client(hass.http.app)) @asyncio.coroutine def test_handle_valid_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_valid_minimal_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=MINIMAL_LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_value_error(mock_client): """Test we don't disclose that this is a valid webhook.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json="", headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.text() assert json == "" @asyncio.coroutine def test_returns_error_missing_username(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-d": "Pixel"}, ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "No topic or user found" in caplog.text @asyncio.coroutine def test_returns_error_incorrect_json(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"} ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "invalid JSON" in caplog.text @asyncio.coroutine def test_returns_error_missing_device(mock_client): """Test that an error is returned when device name is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] def test_context_delivers_pending_msg(): """Test that context is able to hold pending messages while being init.""" context = owntracks.OwnTracksContext(None, None, None, None, None, None, None, None) context.async_see(hello="world") context.async_see(world="hello") received = [] context.set_async_see(lambda **data: received.append(data)) assert len(received) == 2 assert received[0] == {"hello": "world"} assert received[1] == {"world": "hello"} received.clear() context.set_async_see(lambda **data: received.append(data)) assert len(received) == 0
fbradyirl/home-assistant
tests/components/owntracks/test_init.py
homeassistant/components/config/config_entries.py
"""Support for interacting with Smappee Comport Plugs.""" import logging from homeassistant.components.switch import SwitchDevice from . import DATA_SMAPPEE _LOGGER = logging.getLogger(__name__) ICON = "mdi:power-plug" def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Smappee Comfort Plugs.""" smappee = hass.data[DATA_SMAPPEE] dev = [] if smappee.is_remote_active: for location_id in smappee.locations.keys(): for items in smappee.info[location_id].get("actuators"): if items.get("name") != "": _LOGGER.debug("Remote actuator %s", items) dev.append( SmappeeSwitch( smappee, items.get("name"), location_id, items.get("id") ) ) elif smappee.is_local_active: for items in smappee.local_devices: _LOGGER.debug("Local actuator %s", items) dev.append( SmappeeSwitch(smappee, items.get("value"), None, items.get("key")) ) add_entities(dev) class SmappeeSwitch(SwitchDevice): """Representation of a Smappee Comport Plug.""" def __init__(self, smappee, name, location_id, switch_id): """Initialize a new Smappee Comfort Plug.""" self._name = name self._state = False self._smappee = smappee self._location_id = location_id self._switch_id = switch_id self._remoteswitch = True if location_id is None: self._remoteswitch = False @property def name(self): """Return the name of the switch.""" return self._name @property def is_on(self): """Return true if switch is on.""" return self._state @property def icon(self): """Icon to use in the frontend.""" return ICON def turn_on(self, **kwargs): """Turn on Comport Plug.""" if self._smappee.actuator_on( self._location_id, self._switch_id, self._remoteswitch ): self._state = True def turn_off(self, **kwargs): """Turn off Comport Plug.""" if self._smappee.actuator_off( self._location_id, self._switch_id, self._remoteswitch ): self._state = False @property def device_state_attributes(self): """Return the state attributes of the device.""" attr = {} if self._remoteswitch: attr["Location Id"] = self._location_id attr["Location Name"] = self._smappee.locations[self._location_id] attr["Switch Id"] = self._switch_id return attr
"""Test the owntracks_http platform.""" import asyncio import pytest from homeassistant.setup import async_setup_component from homeassistant.components import owntracks from tests.common import mock_component, MockConfigEntry MINIMAL_LOCATION_MESSAGE = { "_type": "location", "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "tst": 1, } LOCATION_MESSAGE = { "_type": "location", "acc": 60, "alt": 27, "batt": 92, "cog": 248, "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "t": "u", "tst": 1, "vac": 4, "vel": 0, } @pytest.fixture(autouse=True) def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading.""" pass @pytest.fixture def mock_client(hass, aiohttp_client): """Start the Hass HTTP component.""" mock_component(hass, "group") mock_component(hass, "zone") mock_component(hass, "device_tracker") MockConfigEntry( domain="owntracks", data={"webhook_id": "owntracks_test", "secret": "abcd"} ).add_to_hass(hass) hass.loop.run_until_complete(async_setup_component(hass, "owntracks", {})) return hass.loop.run_until_complete(aiohttp_client(hass.http.app)) @asyncio.coroutine def test_handle_valid_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_valid_minimal_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=MINIMAL_LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_value_error(mock_client): """Test we don't disclose that this is a valid webhook.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json="", headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.text() assert json == "" @asyncio.coroutine def test_returns_error_missing_username(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-d": "Pixel"}, ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "No topic or user found" in caplog.text @asyncio.coroutine def test_returns_error_incorrect_json(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"} ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "invalid JSON" in caplog.text @asyncio.coroutine def test_returns_error_missing_device(mock_client): """Test that an error is returned when device name is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] def test_context_delivers_pending_msg(): """Test that context is able to hold pending messages while being init.""" context = owntracks.OwnTracksContext(None, None, None, None, None, None, None, None) context.async_see(hello="world") context.async_see(world="hello") received = [] context.set_async_see(lambda **data: received.append(data)) assert len(received) == 2 assert received[0] == {"hello": "world"} assert received[1] == {"world": "hello"} received.clear() context.set_async_see(lambda **data: received.append(data)) assert len(received) == 0
fbradyirl/home-assistant
tests/components/owntracks/test_init.py
homeassistant/components/smappee/switch.py
"""Offer time listening automation rules.""" import logging import voluptuous as vol from homeassistant.core import callback from homeassistant.const import CONF_AT, CONF_PLATFORM from homeassistant.helpers import config_validation as cv from homeassistant.helpers.event import async_track_time_change _LOGGER = logging.getLogger(__name__) TRIGGER_SCHEMA = vol.Schema( {vol.Required(CONF_PLATFORM): "time", vol.Required(CONF_AT): cv.time} ) async def async_trigger(hass, config, action, automation_info): """Listen for state changes based on configuration.""" at_time = config.get(CONF_AT) hours, minutes, seconds = at_time.hour, at_time.minute, at_time.second @callback def time_automation_listener(now): """Listen for time changes and calls action.""" hass.async_run_job(action, {"trigger": {"platform": "time", "now": now}}) return async_track_time_change( hass, time_automation_listener, hour=hours, minute=minutes, second=seconds )
"""Test the owntracks_http platform.""" import asyncio import pytest from homeassistant.setup import async_setup_component from homeassistant.components import owntracks from tests.common import mock_component, MockConfigEntry MINIMAL_LOCATION_MESSAGE = { "_type": "location", "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "tst": 1, } LOCATION_MESSAGE = { "_type": "location", "acc": 60, "alt": 27, "batt": 92, "cog": 248, "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "t": "u", "tst": 1, "vac": 4, "vel": 0, } @pytest.fixture(autouse=True) def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading.""" pass @pytest.fixture def mock_client(hass, aiohttp_client): """Start the Hass HTTP component.""" mock_component(hass, "group") mock_component(hass, "zone") mock_component(hass, "device_tracker") MockConfigEntry( domain="owntracks", data={"webhook_id": "owntracks_test", "secret": "abcd"} ).add_to_hass(hass) hass.loop.run_until_complete(async_setup_component(hass, "owntracks", {})) return hass.loop.run_until_complete(aiohttp_client(hass.http.app)) @asyncio.coroutine def test_handle_valid_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_valid_minimal_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=MINIMAL_LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_value_error(mock_client): """Test we don't disclose that this is a valid webhook.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json="", headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.text() assert json == "" @asyncio.coroutine def test_returns_error_missing_username(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-d": "Pixel"}, ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "No topic or user found" in caplog.text @asyncio.coroutine def test_returns_error_incorrect_json(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"} ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "invalid JSON" in caplog.text @asyncio.coroutine def test_returns_error_missing_device(mock_client): """Test that an error is returned when device name is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] def test_context_delivers_pending_msg(): """Test that context is able to hold pending messages while being init.""" context = owntracks.OwnTracksContext(None, None, None, None, None, None, None, None) context.async_see(hello="world") context.async_see(world="hello") received = [] context.set_async_see(lambda **data: received.append(data)) assert len(received) == 2 assert received[0] == {"hello": "world"} assert received[1] == {"world": "hello"} received.clear() context.set_async_see(lambda **data: received.append(data)) assert len(received) == 0
fbradyirl/home-assistant
tests/components/owntracks/test_init.py
homeassistant/components/automation/time.py
"""Support for Keene Electronics IR-IP devices.""" import functools as ft import logging from homeassistant.components import remote from homeassistant.const import CONF_DEVICE, CONF_NAME from homeassistant.helpers.entity import Entity DOMAIN = "kira" _LOGGER = logging.getLogger(__name__) CONF_REMOTE = "remote" def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Kira platform.""" if discovery_info: name = discovery_info.get(CONF_NAME) device = discovery_info.get(CONF_DEVICE) kira = hass.data[DOMAIN][CONF_REMOTE][name] add_entities([KiraRemote(device, kira)]) return True class KiraRemote(Entity): """Remote representation used to send commands to a Kira device.""" def __init__(self, name, kira): """Initialize KiraRemote class.""" _LOGGER.debug("KiraRemote device init started for: %s", name) self._name = name self._kira = kira @property def name(self): """Return the Kira device's name.""" return self._name def update(self): """No-op.""" def send_command(self, command, **kwargs): """Send a command to one device.""" for single_command in command: code_tuple = (single_command, kwargs.get(remote.ATTR_DEVICE)) _LOGGER.info("Sending Command: %s to %s", *code_tuple) self._kira.sendCode(code_tuple) def async_send_command(self, command, **kwargs): """Send a command to a device. This method must be run in the event loop and returns a coroutine. """ return self.hass.async_add_job(ft.partial(self.send_command, command, **kwargs))
"""Test the owntracks_http platform.""" import asyncio import pytest from homeassistant.setup import async_setup_component from homeassistant.components import owntracks from tests.common import mock_component, MockConfigEntry MINIMAL_LOCATION_MESSAGE = { "_type": "location", "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "tst": 1, } LOCATION_MESSAGE = { "_type": "location", "acc": 60, "alt": 27, "batt": 92, "cog": 248, "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "t": "u", "tst": 1, "vac": 4, "vel": 0, } @pytest.fixture(autouse=True) def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading.""" pass @pytest.fixture def mock_client(hass, aiohttp_client): """Start the Hass HTTP component.""" mock_component(hass, "group") mock_component(hass, "zone") mock_component(hass, "device_tracker") MockConfigEntry( domain="owntracks", data={"webhook_id": "owntracks_test", "secret": "abcd"} ).add_to_hass(hass) hass.loop.run_until_complete(async_setup_component(hass, "owntracks", {})) return hass.loop.run_until_complete(aiohttp_client(hass.http.app)) @asyncio.coroutine def test_handle_valid_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_valid_minimal_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=MINIMAL_LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_value_error(mock_client): """Test we don't disclose that this is a valid webhook.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json="", headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.text() assert json == "" @asyncio.coroutine def test_returns_error_missing_username(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-d": "Pixel"}, ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "No topic or user found" in caplog.text @asyncio.coroutine def test_returns_error_incorrect_json(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"} ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "invalid JSON" in caplog.text @asyncio.coroutine def test_returns_error_missing_device(mock_client): """Test that an error is returned when device name is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] def test_context_delivers_pending_msg(): """Test that context is able to hold pending messages while being init.""" context = owntracks.OwnTracksContext(None, None, None, None, None, None, None, None) context.async_see(hello="world") context.async_see(world="hello") received = [] context.set_async_see(lambda **data: received.append(data)) assert len(received) == 2 assert received[0] == {"hello": "world"} assert received[1] == {"world": "hello"} received.clear() context.set_async_see(lambda **data: received.append(data)) assert len(received) == 0
fbradyirl/home-assistant
tests/components/owntracks/test_init.py
homeassistant/components/kira/remote.py
"""Support for Tikteck lights.""" import logging import voluptuous as vol from homeassistant.const import CONF_DEVICES, CONF_NAME, CONF_PASSWORD from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_HS_COLOR, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, Light, PLATFORM_SCHEMA, ) import homeassistant.helpers.config_validation as cv import homeassistant.util.color as color_util _LOGGER = logging.getLogger(__name__) SUPPORT_TIKTECK_LED = SUPPORT_BRIGHTNESS | SUPPORT_COLOR DEVICE_SCHEMA = vol.Schema( {vol.Optional(CONF_NAME): cv.string, vol.Required(CONF_PASSWORD): cv.string} ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Optional(CONF_DEVICES, default={}): {cv.string: DEVICE_SCHEMA}} ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Tikteck platform.""" lights = [] for address, device_config in config[CONF_DEVICES].items(): device = {} device["name"] = device_config[CONF_NAME] device["password"] = device_config[CONF_PASSWORD] device["address"] = address light = TikteckLight(device) if light.is_valid: lights.append(light) add_entities(lights) class TikteckLight(Light): """Representation of a Tikteck light.""" def __init__(self, device): """Initialize the light.""" import tikteck self._name = device["name"] self._address = device["address"] self._password = device["password"] self._brightness = 255 self._hs = [0, 0] self._state = False self.is_valid = True self._bulb = tikteck.tikteck(self._address, "Smart Light", self._password) if self._bulb.connect() is False: self.is_valid = False _LOGGER.error("Failed to connect to bulb %s, %s", self._address, self._name) @property def unique_id(self): """Return the ID of this light.""" return self._address @property def name(self): """Return the name of the device if any.""" return self._name @property def is_on(self): """Return true if device is on.""" return self._state @property def brightness(self): """Return the brightness of this light between 0..255.""" return self._brightness @property def hs_color(self): """Return the color property.""" return self._hs @property def supported_features(self): """Flag supported features.""" return SUPPORT_TIKTECK_LED @property def should_poll(self): """Return the polling state.""" return False @property def assumed_state(self): """Return the assumed state.""" return True def set_state(self, red, green, blue, brightness): """Set the bulb state.""" return self._bulb.set_state(red, green, blue, brightness) def turn_on(self, **kwargs): """Turn the specified light on.""" self._state = True hs_color = kwargs.get(ATTR_HS_COLOR) brightness = kwargs.get(ATTR_BRIGHTNESS) if hs_color is not None: self._hs = hs_color if brightness is not None: self._brightness = brightness rgb = color_util.color_hs_to_RGB(*self._hs) self.set_state(rgb[0], rgb[1], rgb[2], self.brightness) self.schedule_update_ha_state() def turn_off(self, **kwargs): """Turn the specified light off.""" self._state = False self.set_state(0, 0, 0, 0) self.schedule_update_ha_state()
"""Test the owntracks_http platform.""" import asyncio import pytest from homeassistant.setup import async_setup_component from homeassistant.components import owntracks from tests.common import mock_component, MockConfigEntry MINIMAL_LOCATION_MESSAGE = { "_type": "location", "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "tst": 1, } LOCATION_MESSAGE = { "_type": "location", "acc": 60, "alt": 27, "batt": 92, "cog": 248, "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "t": "u", "tst": 1, "vac": 4, "vel": 0, } @pytest.fixture(autouse=True) def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading.""" pass @pytest.fixture def mock_client(hass, aiohttp_client): """Start the Hass HTTP component.""" mock_component(hass, "group") mock_component(hass, "zone") mock_component(hass, "device_tracker") MockConfigEntry( domain="owntracks", data={"webhook_id": "owntracks_test", "secret": "abcd"} ).add_to_hass(hass) hass.loop.run_until_complete(async_setup_component(hass, "owntracks", {})) return hass.loop.run_until_complete(aiohttp_client(hass.http.app)) @asyncio.coroutine def test_handle_valid_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_valid_minimal_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=MINIMAL_LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_value_error(mock_client): """Test we don't disclose that this is a valid webhook.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json="", headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.text() assert json == "" @asyncio.coroutine def test_returns_error_missing_username(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-d": "Pixel"}, ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "No topic or user found" in caplog.text @asyncio.coroutine def test_returns_error_incorrect_json(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"} ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "invalid JSON" in caplog.text @asyncio.coroutine def test_returns_error_missing_device(mock_client): """Test that an error is returned when device name is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] def test_context_delivers_pending_msg(): """Test that context is able to hold pending messages while being init.""" context = owntracks.OwnTracksContext(None, None, None, None, None, None, None, None) context.async_see(hello="world") context.async_see(world="hello") received = [] context.set_async_see(lambda **data: received.append(data)) assert len(received) == 2 assert received[0] == {"hello": "world"} assert received[1] == {"world": "hello"} received.clear() context.set_async_see(lambda **data: received.append(data)) assert len(received) == 0
fbradyirl/home-assistant
tests/components/owntracks/test_init.py
homeassistant/components/tikteck/light.py
"""Support for HomematicIP Cloud alarm control panel.""" import logging from homematicip.aio.group import AsyncSecurityZoneGroup from homematicip.aio.home import AsyncHome from homematicip.base.enums import WindowState from homeassistant.components.alarm_control_panel import AlarmControlPanel from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, STATE_ALARM_DISARMED, STATE_ALARM_TRIGGERED, ) from homeassistant.core import HomeAssistant from . import DOMAIN as HMIPC_DOMAIN, HMIPC_HAPID _LOGGER = logging.getLogger(__name__) CONST_ALARM_CONTROL_PANEL_NAME = "HmIP Alarm Control Panel" async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the HomematicIP Cloud alarm control devices.""" pass async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities ) -> None: """Set up the HomematicIP alrm control panel from a config entry.""" home = hass.data[HMIPC_DOMAIN][config_entry.data[HMIPC_HAPID]].home devices = [] security_zones = [] for group in home.groups: if isinstance(group, AsyncSecurityZoneGroup): security_zones.append(group) if security_zones: devices.append(HomematicipAlarmControlPanel(home, security_zones)) if devices: async_add_entities(devices) class HomematicipAlarmControlPanel(AlarmControlPanel): """Representation of an alarm control panel.""" def __init__(self, home: AsyncHome, security_zones) -> None: """Initialize the alarm control panel.""" self._home = home self.alarm_state = STATE_ALARM_DISARMED for security_zone in security_zones: if security_zone.label == "INTERNAL": self._internal_alarm_zone = security_zone else: self._external_alarm_zone = security_zone @property def state(self) -> str: """Return the state of the device.""" activation_state = self._home.get_security_zones_activation() # check arm_away if activation_state == (True, True): if self._internal_alarm_zone_state or self._external_alarm_zone_state: return STATE_ALARM_TRIGGERED return STATE_ALARM_ARMED_AWAY # check arm_home if activation_state == (False, True): if self._external_alarm_zone_state: return STATE_ALARM_TRIGGERED return STATE_ALARM_ARMED_HOME return STATE_ALARM_DISARMED @property def _internal_alarm_zone_state(self) -> bool: return _get_zone_alarm_state(self._internal_alarm_zone) @property def _external_alarm_zone_state(self) -> bool: """Return the state of the device.""" return _get_zone_alarm_state(self._external_alarm_zone) async def async_alarm_disarm(self, code=None): """Send disarm command.""" await self._home.set_security_zones_activation(False, False) async def async_alarm_arm_home(self, code=None): """Send arm home command.""" await self._home.set_security_zones_activation(False, True) async def async_alarm_arm_away(self, code=None): """Send arm away command.""" await self._home.set_security_zones_activation(True, True) async def async_added_to_hass(self): """Register callbacks.""" self._internal_alarm_zone.on_update(self._async_device_changed) self._external_alarm_zone.on_update(self._async_device_changed) def _async_device_changed(self, *args, **kwargs): """Handle device state changes.""" _LOGGER.debug("Event %s (%s)", self.name, CONST_ALARM_CONTROL_PANEL_NAME) self.async_schedule_update_ha_state() @property def name(self) -> str: """Return the name of the generic device.""" name = CONST_ALARM_CONTROL_PANEL_NAME if self._home.name: name = "{} {}".format(self._home.name, name) return name @property def should_poll(self) -> bool: """No polling needed.""" return False @property def available(self) -> bool: """Device available.""" return ( not self._internal_alarm_zone.unreach or not self._external_alarm_zone.unreach ) @property def unique_id(self) -> str: """Return a unique ID.""" return "{}_{}".format(self.__class__.__name__, self._home.id) def _get_zone_alarm_state(security_zone) -> bool: if security_zone.active: if ( security_zone.sabotage or security_zone.motionDetected or security_zone.presenceDetected or security_zone.windowState == WindowState.OPEN or security_zone.windowState == WindowState.TILTED ): return True return False
"""Test the owntracks_http platform.""" import asyncio import pytest from homeassistant.setup import async_setup_component from homeassistant.components import owntracks from tests.common import mock_component, MockConfigEntry MINIMAL_LOCATION_MESSAGE = { "_type": "location", "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "tst": 1, } LOCATION_MESSAGE = { "_type": "location", "acc": 60, "alt": 27, "batt": 92, "cog": 248, "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "t": "u", "tst": 1, "vac": 4, "vel": 0, } @pytest.fixture(autouse=True) def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading.""" pass @pytest.fixture def mock_client(hass, aiohttp_client): """Start the Hass HTTP component.""" mock_component(hass, "group") mock_component(hass, "zone") mock_component(hass, "device_tracker") MockConfigEntry( domain="owntracks", data={"webhook_id": "owntracks_test", "secret": "abcd"} ).add_to_hass(hass) hass.loop.run_until_complete(async_setup_component(hass, "owntracks", {})) return hass.loop.run_until_complete(aiohttp_client(hass.http.app)) @asyncio.coroutine def test_handle_valid_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_valid_minimal_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=MINIMAL_LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_value_error(mock_client): """Test we don't disclose that this is a valid webhook.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json="", headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.text() assert json == "" @asyncio.coroutine def test_returns_error_missing_username(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-d": "Pixel"}, ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "No topic or user found" in caplog.text @asyncio.coroutine def test_returns_error_incorrect_json(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"} ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "invalid JSON" in caplog.text @asyncio.coroutine def test_returns_error_missing_device(mock_client): """Test that an error is returned when device name is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] def test_context_delivers_pending_msg(): """Test that context is able to hold pending messages while being init.""" context = owntracks.OwnTracksContext(None, None, None, None, None, None, None, None) context.async_see(hello="world") context.async_see(world="hello") received = [] context.set_async_see(lambda **data: received.append(data)) assert len(received) == 2 assert received[0] == {"hello": "world"} assert received[1] == {"world": "hello"} received.clear() context.set_async_see(lambda **data: received.append(data)) assert len(received) == 0
fbradyirl/home-assistant
tests/components/owntracks/test_init.py
homeassistant/components/homematicip_cloud/alarm_control_panel.py
"""The totalconnect component.""" import logging import voluptuous as vol from total_connect_client import TotalConnectClient import homeassistant.helpers.config_validation as cv from homeassistant.helpers import discovery from homeassistant.const import CONF_PASSWORD, CONF_USERNAME _LOGGER = logging.getLogger(__name__) DOMAIN = "totalconnect" CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, } ) }, extra=vol.ALLOW_EXTRA, ) TOTALCONNECT_PLATFORMS = ["alarm_control_panel"] def setup(hass, config): """Set up TotalConnect component.""" conf = config[DOMAIN] username = conf[CONF_USERNAME] password = conf[CONF_PASSWORD] client = TotalConnectClient.TotalConnectClient(username, password) if client.token is False: _LOGGER.error("TotalConnect authentication failed") return False hass.data[DOMAIN] = TotalConnectSystem(username, password, client) for platform in TOTALCONNECT_PLATFORMS: discovery.load_platform(hass, platform, DOMAIN, {}, config) return True class TotalConnectSystem: """TotalConnect System class.""" def __init__(self, username, password, client): """Initialize the TotalConnect system.""" self._username = username self._password = password self.client = client
"""Test the owntracks_http platform.""" import asyncio import pytest from homeassistant.setup import async_setup_component from homeassistant.components import owntracks from tests.common import mock_component, MockConfigEntry MINIMAL_LOCATION_MESSAGE = { "_type": "location", "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "tst": 1, } LOCATION_MESSAGE = { "_type": "location", "acc": 60, "alt": 27, "batt": 92, "cog": 248, "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "t": "u", "tst": 1, "vac": 4, "vel": 0, } @pytest.fixture(autouse=True) def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading.""" pass @pytest.fixture def mock_client(hass, aiohttp_client): """Start the Hass HTTP component.""" mock_component(hass, "group") mock_component(hass, "zone") mock_component(hass, "device_tracker") MockConfigEntry( domain="owntracks", data={"webhook_id": "owntracks_test", "secret": "abcd"} ).add_to_hass(hass) hass.loop.run_until_complete(async_setup_component(hass, "owntracks", {})) return hass.loop.run_until_complete(aiohttp_client(hass.http.app)) @asyncio.coroutine def test_handle_valid_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_valid_minimal_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=MINIMAL_LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_value_error(mock_client): """Test we don't disclose that this is a valid webhook.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json="", headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.text() assert json == "" @asyncio.coroutine def test_returns_error_missing_username(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-d": "Pixel"}, ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "No topic or user found" in caplog.text @asyncio.coroutine def test_returns_error_incorrect_json(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"} ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "invalid JSON" in caplog.text @asyncio.coroutine def test_returns_error_missing_device(mock_client): """Test that an error is returned when device name is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] def test_context_delivers_pending_msg(): """Test that context is able to hold pending messages while being init.""" context = owntracks.OwnTracksContext(None, None, None, None, None, None, None, None) context.async_see(hello="world") context.async_see(world="hello") received = [] context.set_async_see(lambda **data: received.append(data)) assert len(received) == 2 assert received[0] == {"hello": "world"} assert received[1] == {"world": "hello"} received.clear() context.set_async_see(lambda **data: received.append(data)) assert len(received) == 0
fbradyirl/home-assistant
tests/components/owntracks/test_init.py
homeassistant/components/totalconnect/__init__.py
"""Twilio SMS platform for notify component.""" import logging import voluptuous as vol from homeassistant.components.twilio import DATA_TWILIO import homeassistant.helpers.config_validation as cv from homeassistant.components.notify import ( ATTR_TARGET, PLATFORM_SCHEMA, BaseNotificationService, ATTR_DATA, ) _LOGGER = logging.getLogger(__name__) CONF_FROM_NUMBER = "from_number" ATTR_MEDIAURL = "media_url" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_FROM_NUMBER): vol.All( cv.string, vol.Match( r"^\+?[1-9]\d{1,14}$|" r"^(?=.{1,11}$)[a-zA-Z0-9\s]*" r"[a-zA-Z][a-zA-Z0-9\s]*$" ), ) } ) def get_service(hass, config, discovery_info=None): """Get the Twilio SMS notification service.""" return TwilioSMSNotificationService( hass.data[DATA_TWILIO], config[CONF_FROM_NUMBER] ) class TwilioSMSNotificationService(BaseNotificationService): """Implement the notification service for the Twilio SMS service.""" def __init__(self, twilio_client, from_number): """Initialize the service.""" self.client = twilio_client self.from_number = from_number def send_message(self, message="", **kwargs): """Send SMS to specified target user cell.""" targets = kwargs.get(ATTR_TARGET) data = kwargs.get(ATTR_DATA) or {} twilio_args = {"body": message, "from_": self.from_number} if ATTR_MEDIAURL in data: twilio_args[ATTR_MEDIAURL] = data[ATTR_MEDIAURL] if not targets: _LOGGER.info("At least 1 target is required") return for target in targets: self.client.messages.create(to=target, **twilio_args)
"""Test the owntracks_http platform.""" import asyncio import pytest from homeassistant.setup import async_setup_component from homeassistant.components import owntracks from tests.common import mock_component, MockConfigEntry MINIMAL_LOCATION_MESSAGE = { "_type": "location", "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "tst": 1, } LOCATION_MESSAGE = { "_type": "location", "acc": 60, "alt": 27, "batt": 92, "cog": 248, "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "t": "u", "tst": 1, "vac": 4, "vel": 0, } @pytest.fixture(autouse=True) def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading.""" pass @pytest.fixture def mock_client(hass, aiohttp_client): """Start the Hass HTTP component.""" mock_component(hass, "group") mock_component(hass, "zone") mock_component(hass, "device_tracker") MockConfigEntry( domain="owntracks", data={"webhook_id": "owntracks_test", "secret": "abcd"} ).add_to_hass(hass) hass.loop.run_until_complete(async_setup_component(hass, "owntracks", {})) return hass.loop.run_until_complete(aiohttp_client(hass.http.app)) @asyncio.coroutine def test_handle_valid_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_valid_minimal_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=MINIMAL_LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_value_error(mock_client): """Test we don't disclose that this is a valid webhook.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json="", headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.text() assert json == "" @asyncio.coroutine def test_returns_error_missing_username(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-d": "Pixel"}, ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "No topic or user found" in caplog.text @asyncio.coroutine def test_returns_error_incorrect_json(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"} ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "invalid JSON" in caplog.text @asyncio.coroutine def test_returns_error_missing_device(mock_client): """Test that an error is returned when device name is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] def test_context_delivers_pending_msg(): """Test that context is able to hold pending messages while being init.""" context = owntracks.OwnTracksContext(None, None, None, None, None, None, None, None) context.async_see(hello="world") context.async_see(world="hello") received = [] context.set_async_see(lambda **data: received.append(data)) assert len(received) == 2 assert received[0] == {"hello": "world"} assert received[1] == {"world": "hello"} received.clear() context.set_async_see(lambda **data: received.append(data)) assert len(received) == 0
fbradyirl/home-assistant
tests/components/owntracks/test_init.py
homeassistant/components/twilio_sms/notify.py
"""Support for the IBM Watson IoT Platform.""" import logging import queue import threading import time import voluptuous as vol from homeassistant.const import ( CONF_DOMAINS, CONF_ENTITIES, CONF_EXCLUDE, CONF_ID, CONF_INCLUDE, CONF_TOKEN, CONF_TYPE, EVENT_HOMEASSISTANT_STOP, EVENT_STATE_CHANGED, STATE_UNAVAILABLE, STATE_UNKNOWN, ) from homeassistant.helpers import state as state_helper import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_ORG = "organization" DOMAIN = "watson_iot" MAX_TRIES = 3 RETRY_DELAY = 20 CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.All( vol.Schema( { vol.Required(CONF_ORG): cv.string, vol.Required(CONF_TYPE): cv.string, vol.Required(CONF_ID): cv.string, vol.Required(CONF_TOKEN): cv.string, vol.Optional(CONF_EXCLUDE, default={}): vol.Schema( { vol.Optional(CONF_ENTITIES, default=[]): cv.entity_ids, vol.Optional(CONF_DOMAINS, default=[]): vol.All( cv.ensure_list, [cv.string] ), } ), vol.Optional(CONF_INCLUDE, default={}): vol.Schema( { vol.Optional(CONF_ENTITIES, default=[]): cv.entity_ids, vol.Optional(CONF_DOMAINS, default=[]): vol.All( cv.ensure_list, [cv.string] ), } ), } ) ) }, extra=vol.ALLOW_EXTRA, ) def setup(hass, config): """Set up the Watson IoT Platform component.""" from ibmiotf import gateway conf = config[DOMAIN] include = conf[CONF_INCLUDE] exclude = conf[CONF_EXCLUDE] whitelist_e = set(include[CONF_ENTITIES]) whitelist_d = set(include[CONF_DOMAINS]) blacklist_e = set(exclude[CONF_ENTITIES]) blacklist_d = set(exclude[CONF_DOMAINS]) client_args = { "org": conf[CONF_ORG], "type": conf[CONF_TYPE], "id": conf[CONF_ID], "auth-method": "token", "auth-token": conf[CONF_TOKEN], } watson_gateway = gateway.Client(client_args) def event_to_json(event): """Add an event to the outgoing list.""" state = event.data.get("new_state") if ( state is None or state.state in (STATE_UNKNOWN, "", STATE_UNAVAILABLE) or state.entity_id in blacklist_e or state.domain in blacklist_d ): return if (whitelist_e and state.entity_id not in whitelist_e) or ( whitelist_d and state.domain not in whitelist_d ): return try: _state_as_value = float(state.state) except ValueError: _state_as_value = None if _state_as_value is None: try: _state_as_value = float(state_helper.state_as_number(state)) except ValueError: _state_as_value = None out_event = { "tags": {"domain": state.domain, "entity_id": state.object_id}, "time": event.time_fired.isoformat(), "fields": {"state": state.state}, } if _state_as_value is not None: out_event["fields"]["state_value"] = _state_as_value for key, value in state.attributes.items(): if key != "unit_of_measurement": # If the key is already in fields if key in out_event["fields"]: key = "{}_".format(key) # For each value we try to cast it as float # But if we can not do it we store the value # as string try: out_event["fields"][key] = float(value) except (ValueError, TypeError): out_event["fields"][key] = str(value) return out_event instance = hass.data[DOMAIN] = WatsonIOTThread(hass, watson_gateway, event_to_json) instance.start() def shutdown(event): """Shut down the thread.""" instance.queue.put(None) instance.join() hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, shutdown) return True class WatsonIOTThread(threading.Thread): """A threaded event handler class.""" def __init__(self, hass, gateway, event_to_json): """Initialize the listener.""" threading.Thread.__init__(self, name="WatsonIOT") self.queue = queue.Queue() self.gateway = gateway self.gateway.connect() self.event_to_json = event_to_json self.write_errors = 0 self.shutdown = False hass.bus.listen(EVENT_STATE_CHANGED, self._event_listener) def _event_listener(self, event): """Listen for new messages on the bus and queue them for Watson IoT.""" item = (time.monotonic(), event) self.queue.put(item) def get_events_json(self): """Return an event formatted for writing.""" events = [] try: item = self.queue.get() if item is None: self.shutdown = True else: event_json = self.event_to_json(item[1]) if event_json: events.append(event_json) except queue.Empty: pass return events def write_to_watson(self, events): """Write preprocessed events to watson.""" import ibmiotf for event in events: for retry in range(MAX_TRIES + 1): try: for field in event["fields"]: value = event["fields"][field] device_success = self.gateway.publishDeviceEvent( event["tags"]["domain"], event["tags"]["entity_id"], field, "json", value, ) if not device_success: _LOGGER.error("Failed to publish message to Watson IoT") continue break except (ibmiotf.MissingMessageEncoderException, IOError): if retry < MAX_TRIES: time.sleep(RETRY_DELAY) else: _LOGGER.exception("Failed to publish message to Watson IoT") def run(self): """Process incoming events.""" while not self.shutdown: event = self.get_events_json() if event: self.write_to_watson(event) self.queue.task_done() def block_till_done(self): """Block till all events processed.""" self.queue.join()
"""Test the owntracks_http platform.""" import asyncio import pytest from homeassistant.setup import async_setup_component from homeassistant.components import owntracks from tests.common import mock_component, MockConfigEntry MINIMAL_LOCATION_MESSAGE = { "_type": "location", "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "tst": 1, } LOCATION_MESSAGE = { "_type": "location", "acc": 60, "alt": 27, "batt": 92, "cog": 248, "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "t": "u", "tst": 1, "vac": 4, "vel": 0, } @pytest.fixture(autouse=True) def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading.""" pass @pytest.fixture def mock_client(hass, aiohttp_client): """Start the Hass HTTP component.""" mock_component(hass, "group") mock_component(hass, "zone") mock_component(hass, "device_tracker") MockConfigEntry( domain="owntracks", data={"webhook_id": "owntracks_test", "secret": "abcd"} ).add_to_hass(hass) hass.loop.run_until_complete(async_setup_component(hass, "owntracks", {})) return hass.loop.run_until_complete(aiohttp_client(hass.http.app)) @asyncio.coroutine def test_handle_valid_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_valid_minimal_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=MINIMAL_LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_value_error(mock_client): """Test we don't disclose that this is a valid webhook.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json="", headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.text() assert json == "" @asyncio.coroutine def test_returns_error_missing_username(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-d": "Pixel"}, ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "No topic or user found" in caplog.text @asyncio.coroutine def test_returns_error_incorrect_json(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"} ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "invalid JSON" in caplog.text @asyncio.coroutine def test_returns_error_missing_device(mock_client): """Test that an error is returned when device name is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] def test_context_delivers_pending_msg(): """Test that context is able to hold pending messages while being init.""" context = owntracks.OwnTracksContext(None, None, None, None, None, None, None, None) context.async_see(hello="world") context.async_see(world="hello") received = [] context.set_async_see(lambda **data: received.append(data)) assert len(received) == 2 assert received[0] == {"hello": "world"} assert received[1] == {"world": "hello"} received.clear() context.set_async_see(lambda **data: received.append(data)) assert len(received) == 0
fbradyirl/home-assistant
tests/components/owntracks/test_init.py
homeassistant/components/watson_iot/__init__.py
"""Allow users to set and activate scenes.""" from collections import namedtuple import logging import voluptuous as vol from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_STATE, CONF_ENTITIES, CONF_NAME, CONF_PLATFORM, STATE_OFF, STATE_ON, SERVICE_RELOAD, ) from homeassistant.core import State, DOMAIN from homeassistant import config as conf_util from homeassistant.exceptions import HomeAssistantError from homeassistant.loader import async_get_integration from homeassistant.helpers import ( config_per_platform, config_validation as cv, entity_platform, ) from homeassistant.helpers.state import HASS_DOMAIN, async_reproduce_state from homeassistant.components.scene import DOMAIN as SCENE_DOMAIN, STATES, Scene PLATFORM_SCHEMA = vol.Schema( { vol.Required(CONF_PLATFORM): HASS_DOMAIN, vol.Required(STATES): vol.All( cv.ensure_list, [ { vol.Required(CONF_NAME): cv.string, vol.Required(CONF_ENTITIES): { cv.entity_id: vol.Any(str, bool, dict) }, } ], ), }, extra=vol.ALLOW_EXTRA, ) SCENECONFIG = namedtuple("SceneConfig", [CONF_NAME, STATES]) _LOGGER = logging.getLogger(__name__) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up home assistant scene entries.""" _process_scenes_config(hass, async_add_entities, config) # This platform can be loaded multiple times. Only first time register the service. if hass.services.has_service(SCENE_DOMAIN, SERVICE_RELOAD): return # Store platform for later. platform = entity_platform.current_platform.get() async def reload_config(call): """Reload the scene config.""" try: conf = await conf_util.async_hass_config_yaml(hass) except HomeAssistantError as err: _LOGGER.error(err) return integration = await async_get_integration(hass, SCENE_DOMAIN) conf = await conf_util.async_process_component_config(hass, conf, integration) if not conf or not platform: return await platform.async_reset() # Extract only the config for the Home Assistant platform, ignore the rest. for p_type, p_config in config_per_platform(conf, SCENE_DOMAIN): if p_type != DOMAIN: continue _process_scenes_config(hass, async_add_entities, p_config) hass.helpers.service.async_register_admin_service( SCENE_DOMAIN, SERVICE_RELOAD, reload_config ) def _process_scenes_config(hass, async_add_entities, config): """Process multiple scenes and add them.""" scene_config = config[STATES] # Check empty list if not scene_config: return async_add_entities( HomeAssistantScene(hass, _process_scene_config(scene)) for scene in scene_config ) def _process_scene_config(scene_config): """Process passed in config into a format to work with. Async friendly. """ name = scene_config.get(CONF_NAME) states = {} c_entities = dict(scene_config.get(CONF_ENTITIES, {})) for entity_id in c_entities: if isinstance(c_entities[entity_id], dict): entity_attrs = c_entities[entity_id].copy() state = entity_attrs.pop(ATTR_STATE, None) attributes = entity_attrs else: state = c_entities[entity_id] attributes = {} # YAML translates 'on' to a boolean # http://yaml.org/type/bool.html if isinstance(state, bool): state = STATE_ON if state else STATE_OFF else: state = str(state) states[entity_id.lower()] = State(entity_id, state, attributes) return SCENECONFIG(name, states) class HomeAssistantScene(Scene): """A scene is a group of entities and the states we want them to be.""" def __init__(self, hass, scene_config): """Initialize the scene.""" self.hass = hass self.scene_config = scene_config @property def name(self): """Return the name of the scene.""" return self.scene_config.name @property def device_state_attributes(self): """Return the scene state attributes.""" return {ATTR_ENTITY_ID: list(self.scene_config.states.keys())} async def async_activate(self): """Activate scene. Try to get entities into requested state.""" await async_reproduce_state(self.hass, self.scene_config.states.values(), True)
"""Test the owntracks_http platform.""" import asyncio import pytest from homeassistant.setup import async_setup_component from homeassistant.components import owntracks from tests.common import mock_component, MockConfigEntry MINIMAL_LOCATION_MESSAGE = { "_type": "location", "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "tst": 1, } LOCATION_MESSAGE = { "_type": "location", "acc": 60, "alt": 27, "batt": 92, "cog": 248, "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "t": "u", "tst": 1, "vac": 4, "vel": 0, } @pytest.fixture(autouse=True) def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading.""" pass @pytest.fixture def mock_client(hass, aiohttp_client): """Start the Hass HTTP component.""" mock_component(hass, "group") mock_component(hass, "zone") mock_component(hass, "device_tracker") MockConfigEntry( domain="owntracks", data={"webhook_id": "owntracks_test", "secret": "abcd"} ).add_to_hass(hass) hass.loop.run_until_complete(async_setup_component(hass, "owntracks", {})) return hass.loop.run_until_complete(aiohttp_client(hass.http.app)) @asyncio.coroutine def test_handle_valid_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_valid_minimal_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=MINIMAL_LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_value_error(mock_client): """Test we don't disclose that this is a valid webhook.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json="", headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.text() assert json == "" @asyncio.coroutine def test_returns_error_missing_username(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-d": "Pixel"}, ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "No topic or user found" in caplog.text @asyncio.coroutine def test_returns_error_incorrect_json(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"} ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "invalid JSON" in caplog.text @asyncio.coroutine def test_returns_error_missing_device(mock_client): """Test that an error is returned when device name is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] def test_context_delivers_pending_msg(): """Test that context is able to hold pending messages while being init.""" context = owntracks.OwnTracksContext(None, None, None, None, None, None, None, None) context.async_see(hello="world") context.async_see(world="hello") received = [] context.set_async_see(lambda **data: received.append(data)) assert len(received) == 2 assert received[0] == {"hello": "world"} assert received[1] == {"world": "hello"} received.clear() context.set_async_see(lambda **data: received.append(data)) assert len(received) == 0
fbradyirl/home-assistant
tests/components/owntracks/test_init.py
homeassistant/components/homeassistant/scene.py
"""Pushbullet platform for sensor component.""" import logging import voluptuous as vol from homeassistant.const import CONF_API_KEY, CONF_MONITORED_CONDITIONS from homeassistant.components.sensor import PLATFORM_SCHEMA import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) SENSOR_TYPES = { "application_name": ["Application name"], "body": ["Body"], "notification_id": ["Notification ID"], "notification_tag": ["Notification tag"], "package_name": ["Package name"], "receiver_email": ["Receiver email"], "sender_email": ["Sender email"], "source_device_iden": ["Sender device ID"], "title": ["Title"], "type": ["Type"], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_API_KEY): cv.string, vol.Optional(CONF_MONITORED_CONDITIONS, default=["title", "body"]): vol.All( cv.ensure_list, vol.Length(min=1), [vol.In(SENSOR_TYPES)] ), } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Pushbullet Sensor platform.""" from pushbullet import PushBullet from pushbullet import InvalidKeyError try: pushbullet = PushBullet(config.get(CONF_API_KEY)) except InvalidKeyError: _LOGGER.error("Wrong API key for Pushbullet supplied") return False pbprovider = PushBulletNotificationProvider(pushbullet) devices = [] for sensor_type in config[CONF_MONITORED_CONDITIONS]: devices.append(PushBulletNotificationSensor(pbprovider, sensor_type)) add_entities(devices) class PushBulletNotificationSensor(Entity): """Representation of a Pushbullet Sensor.""" def __init__(self, pb, element): """Initialize the Pushbullet sensor.""" self.pushbullet = pb self._element = element self._state = None self._state_attributes = None def update(self): """Fetch the latest data from the sensor. This will fetch the 'sensor reading' into self._state but also all attributes into self._state_attributes. """ try: self._state = self.pushbullet.data[self._element] self._state_attributes = self.pushbullet.data except (KeyError, TypeError): pass @property def name(self): """Return the name of the sensor.""" return "{} {}".format("Pushbullet", self._element) @property def state(self): """Return the current state of the sensor.""" return self._state @property def device_state_attributes(self): """Return all known attributes of the sensor.""" return self._state_attributes class PushBulletNotificationProvider: """Provider for an account, leading to one or more sensors.""" def __init__(self, pb): """Start to retrieve pushes from the given Pushbullet instance.""" import threading self.pushbullet = pb self._data = None self.listener = None self.thread = threading.Thread(target=self.retrieve_pushes) self.thread.daemon = True self.thread.start() def on_push(self, data): """Update the current data. Currently only monitors pushes but might be extended to monitor different kinds of Pushbullet events. """ if data["type"] == "push": self._data = data["push"] @property def data(self): """Return the current data stored in the provider.""" return self._data def retrieve_pushes(self): """Retrieve_pushes. Spawn a new Listener and links it to self.on_push. """ from pushbullet import Listener self.listener = Listener(account=self.pushbullet, on_push=self.on_push) _LOGGER.debug("Getting pushes") try: self.listener.run_forever() finally: self.listener.close()
"""Test the owntracks_http platform.""" import asyncio import pytest from homeassistant.setup import async_setup_component from homeassistant.components import owntracks from tests.common import mock_component, MockConfigEntry MINIMAL_LOCATION_MESSAGE = { "_type": "location", "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "tst": 1, } LOCATION_MESSAGE = { "_type": "location", "acc": 60, "alt": 27, "batt": 92, "cog": 248, "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "t": "u", "tst": 1, "vac": 4, "vel": 0, } @pytest.fixture(autouse=True) def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading.""" pass @pytest.fixture def mock_client(hass, aiohttp_client): """Start the Hass HTTP component.""" mock_component(hass, "group") mock_component(hass, "zone") mock_component(hass, "device_tracker") MockConfigEntry( domain="owntracks", data={"webhook_id": "owntracks_test", "secret": "abcd"} ).add_to_hass(hass) hass.loop.run_until_complete(async_setup_component(hass, "owntracks", {})) return hass.loop.run_until_complete(aiohttp_client(hass.http.app)) @asyncio.coroutine def test_handle_valid_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_valid_minimal_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=MINIMAL_LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_value_error(mock_client): """Test we don't disclose that this is a valid webhook.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json="", headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.text() assert json == "" @asyncio.coroutine def test_returns_error_missing_username(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-d": "Pixel"}, ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "No topic or user found" in caplog.text @asyncio.coroutine def test_returns_error_incorrect_json(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"} ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "invalid JSON" in caplog.text @asyncio.coroutine def test_returns_error_missing_device(mock_client): """Test that an error is returned when device name is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] def test_context_delivers_pending_msg(): """Test that context is able to hold pending messages while being init.""" context = owntracks.OwnTracksContext(None, None, None, None, None, None, None, None) context.async_see(hello="world") context.async_see(world="hello") received = [] context.set_async_see(lambda **data: received.append(data)) assert len(received) == 2 assert received[0] == {"hello": "world"} assert received[1] == {"world": "hello"} received.clear() context.set_async_see(lambda **data: received.append(data)) assert len(received) == 0
fbradyirl/home-assistant
tests/components/owntracks/test_init.py
homeassistant/components/pushbullet/sensor.py
"""Sensor support for Wireless Sensor Tags platform.""" import logging import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import CONF_MONITORED_CONDITIONS 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_TAG_UPDATE, WirelessTagBaseSensor _LOGGER = logging.getLogger(__name__) SENSOR_TEMPERATURE = "temperature" SENSOR_HUMIDITY = "humidity" SENSOR_MOISTURE = "moisture" SENSOR_LIGHT = "light" SENSOR_TYPES = [SENSOR_TEMPERATURE, SENSOR_HUMIDITY, SENSOR_MOISTURE, SENSOR_LIGHT] 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 sensor platform.""" platform = hass.data.get(WIRELESSTAG_DOMAIN) sensors = [] tags = platform.tags for tag in tags.values(): for sensor_type in config.get(CONF_MONITORED_CONDITIONS): if sensor_type in tag.allowed_sensor_types: sensors.append( WirelessTagSensor(platform, tag, sensor_type, hass.config) ) add_entities(sensors, True) class WirelessTagSensor(WirelessTagBaseSensor): """Representation of a Sensor.""" def __init__(self, api, tag, sensor_type, config): """Initialize a WirelessTag sensor.""" super().__init__(api, tag) self._sensor_type = sensor_type self._name = self._tag.name # I want to see entity_id as: # sensor.wirelesstag_bedroom_temperature # and not as sensor.bedroom for temperature and # sensor.bedroom_2 for humidity self._entity_id = "{}.{}_{}_{}".format( "sensor", WIRELESSTAG_DOMAIN, self.underscored_name, self._sensor_type ) async def async_added_to_hass(self): """Register callbacks.""" async_dispatcher_connect( self.hass, SIGNAL_TAG_UPDATE.format(self.tag_id, self.tag_manager_mac), self._update_tag_info_callback, ) @property def entity_id(self): """Overridden version.""" return self._entity_id @property def underscored_name(self): """Provide name savvy to be used in entity_id name of self.""" return self.name.lower().replace(" ", "_") @property def state(self): """Return the state of the sensor.""" return self._state @property def device_class(self): """Return the class of the sensor.""" return self._sensor_type @property def unit_of_measurement(self): """Return the unit of measurement.""" return self._sensor.unit @property def principal_value(self): """Return sensor current value.""" return self._sensor.value @property def _sensor(self): """Return tag sensor entity.""" return self._tag.sensor[self._sensor_type] @callback def _update_tag_info_callback(self, event): """Handle push notification sent by tag manager.""" _LOGGER.debug("Entity to update state: %s event data: %s", self, event.data) new_value = self._sensor.value_from_update_event(event.data) self._state = self.decorate_value(new_value) self.async_schedule_update_ha_state()
"""Test the owntracks_http platform.""" import asyncio import pytest from homeassistant.setup import async_setup_component from homeassistant.components import owntracks from tests.common import mock_component, MockConfigEntry MINIMAL_LOCATION_MESSAGE = { "_type": "location", "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "tst": 1, } LOCATION_MESSAGE = { "_type": "location", "acc": 60, "alt": 27, "batt": 92, "cog": 248, "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "t": "u", "tst": 1, "vac": 4, "vel": 0, } @pytest.fixture(autouse=True) def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading.""" pass @pytest.fixture def mock_client(hass, aiohttp_client): """Start the Hass HTTP component.""" mock_component(hass, "group") mock_component(hass, "zone") mock_component(hass, "device_tracker") MockConfigEntry( domain="owntracks", data={"webhook_id": "owntracks_test", "secret": "abcd"} ).add_to_hass(hass) hass.loop.run_until_complete(async_setup_component(hass, "owntracks", {})) return hass.loop.run_until_complete(aiohttp_client(hass.http.app)) @asyncio.coroutine def test_handle_valid_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_valid_minimal_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=MINIMAL_LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_value_error(mock_client): """Test we don't disclose that this is a valid webhook.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json="", headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.text() assert json == "" @asyncio.coroutine def test_returns_error_missing_username(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-d": "Pixel"}, ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "No topic or user found" in caplog.text @asyncio.coroutine def test_returns_error_incorrect_json(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"} ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "invalid JSON" in caplog.text @asyncio.coroutine def test_returns_error_missing_device(mock_client): """Test that an error is returned when device name is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] def test_context_delivers_pending_msg(): """Test that context is able to hold pending messages while being init.""" context = owntracks.OwnTracksContext(None, None, None, None, None, None, None, None) context.async_see(hello="world") context.async_see(world="hello") received = [] context.set_async_see(lambda **data: received.append(data)) assert len(received) == 2 assert received[0] == {"hello": "world"} assert received[1] == {"world": "hello"} received.clear() context.set_async_see(lambda **data: received.append(data)) assert len(received) == 0
fbradyirl/home-assistant
tests/components/owntracks/test_init.py
homeassistant/components/wirelesstag/sensor.py
"""Support to trigger Maker IFTTT recipes.""" import json import logging import requests import voluptuous as vol from homeassistant.const import CONF_WEBHOOK_ID from homeassistant.helpers import config_entry_flow import homeassistant.helpers.config_validation as cv from .const import DOMAIN _LOGGER = logging.getLogger(__name__) EVENT_RECEIVED = "ifttt_webhook_received" ATTR_EVENT = "event" ATTR_TARGET = "target" ATTR_VALUE1 = "value1" ATTR_VALUE2 = "value2" ATTR_VALUE3 = "value3" CONF_KEY = "key" SERVICE_TRIGGER = "trigger" SERVICE_TRIGGER_SCHEMA = vol.Schema( { vol.Required(ATTR_EVENT): cv.string, vol.Optional(ATTR_TARGET): vol.All(cv.ensure_list, [cv.string]), vol.Optional(ATTR_VALUE1): cv.string, vol.Optional(ATTR_VALUE2): cv.string, vol.Optional(ATTR_VALUE3): cv.string, } ) CONFIG_SCHEMA = vol.Schema( { vol.Optional(DOMAIN): vol.Schema( {vol.Required(CONF_KEY): vol.Any({cv.string: cv.string}, cv.string)} ) }, extra=vol.ALLOW_EXTRA, ) async def async_setup(hass, config): """Set up the IFTTT service component.""" if DOMAIN not in config: return True api_keys = config[DOMAIN][CONF_KEY] if isinstance(api_keys, str): api_keys = {"default": api_keys} def trigger_service(call): """Handle IFTTT trigger service calls.""" event = call.data[ATTR_EVENT] targets = call.data.get(ATTR_TARGET, list(api_keys)) value1 = call.data.get(ATTR_VALUE1) value2 = call.data.get(ATTR_VALUE2) value3 = call.data.get(ATTR_VALUE3) target_keys = dict() for target in targets: if target not in api_keys: _LOGGER.error("No IFTTT api key for %s", target) continue target_keys[target] = api_keys[target] try: import pyfttt for target, key in target_keys.items(): res = pyfttt.send_event(key, event, value1, value2, value3) if res.status_code != 200: _LOGGER.error("IFTTT reported error sending event to %s.", target) except requests.exceptions.RequestException: _LOGGER.exception("Error communicating with IFTTT") hass.services.async_register( DOMAIN, SERVICE_TRIGGER, trigger_service, schema=SERVICE_TRIGGER_SCHEMA ) return True async def handle_webhook(hass, webhook_id, request): """Handle webhook callback.""" body = await request.text() try: data = json.loads(body) if body else {} except ValueError: return None if isinstance(data, dict): data["webhook_id"] = webhook_id hass.bus.async_fire(EVENT_RECEIVED, data) async def async_setup_entry(hass, entry): """Configure based on config entry.""" hass.components.webhook.async_register( DOMAIN, "IFTTT", entry.data[CONF_WEBHOOK_ID], handle_webhook ) return True async def async_unload_entry(hass, entry): """Unload a config entry.""" hass.components.webhook.async_unregister(entry.data[CONF_WEBHOOK_ID]) return True # pylint: disable=invalid-name async_remove_entry = config_entry_flow.webhook_async_remove_entry
"""Test the owntracks_http platform.""" import asyncio import pytest from homeassistant.setup import async_setup_component from homeassistant.components import owntracks from tests.common import mock_component, MockConfigEntry MINIMAL_LOCATION_MESSAGE = { "_type": "location", "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "tst": 1, } LOCATION_MESSAGE = { "_type": "location", "acc": 60, "alt": 27, "batt": 92, "cog": 248, "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "t": "u", "tst": 1, "vac": 4, "vel": 0, } @pytest.fixture(autouse=True) def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading.""" pass @pytest.fixture def mock_client(hass, aiohttp_client): """Start the Hass HTTP component.""" mock_component(hass, "group") mock_component(hass, "zone") mock_component(hass, "device_tracker") MockConfigEntry( domain="owntracks", data={"webhook_id": "owntracks_test", "secret": "abcd"} ).add_to_hass(hass) hass.loop.run_until_complete(async_setup_component(hass, "owntracks", {})) return hass.loop.run_until_complete(aiohttp_client(hass.http.app)) @asyncio.coroutine def test_handle_valid_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_valid_minimal_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=MINIMAL_LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_value_error(mock_client): """Test we don't disclose that this is a valid webhook.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json="", headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.text() assert json == "" @asyncio.coroutine def test_returns_error_missing_username(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-d": "Pixel"}, ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "No topic or user found" in caplog.text @asyncio.coroutine def test_returns_error_incorrect_json(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"} ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "invalid JSON" in caplog.text @asyncio.coroutine def test_returns_error_missing_device(mock_client): """Test that an error is returned when device name is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] def test_context_delivers_pending_msg(): """Test that context is able to hold pending messages while being init.""" context = owntracks.OwnTracksContext(None, None, None, None, None, None, None, None) context.async_see(hello="world") context.async_see(world="hello") received = [] context.set_async_see(lambda **data: received.append(data)) assert len(received) == 2 assert received[0] == {"hello": "world"} assert received[1] == {"world": "hello"} received.clear() context.set_async_see(lambda **data: received.append(data)) assert len(received) == 0
fbradyirl/home-assistant
tests/components/owntracks/test_init.py
homeassistant/components/ifttt/__init__.py
"""Support for esphome devices.""" import asyncio import logging import math from typing import Any, Callable, Dict, List, Optional from aioesphomeapi import ( APIClient, APIConnectionError, DeviceInfo, EntityInfo, EntityState, HomeassistantServiceCall, UserService, UserServiceArgType, ) import voluptuous as vol from homeassistant import const from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT, EVENT_HOMEASSISTANT_STOP, ) from homeassistant.core import Event, State, callback from homeassistant.exceptions import TemplateError from homeassistant.helpers import template import homeassistant.helpers.config_validation as cv import homeassistant.helpers.device_registry as dr from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity import Entity from homeassistant.helpers.event import async_track_state_change from homeassistant.helpers.json import JSONEncoder from homeassistant.helpers.storage import Store from homeassistant.helpers.template import Template from homeassistant.helpers.typing import ConfigType, HomeAssistantType # Import config flow so that it's added to the registry from .config_flow import EsphomeFlowHandler # noqa from .entry_data import ( DATA_KEY, DISPATCHER_ON_DEVICE_UPDATE, DISPATCHER_ON_LIST, DISPATCHER_ON_STATE, DISPATCHER_REMOVE_ENTITY, DISPATCHER_UPDATE_ENTITY, RuntimeEntryData, ) DOMAIN = "esphome" _LOGGER = logging.getLogger(__name__) STORAGE_KEY = "esphome.{}" STORAGE_VERSION = 1 # No config schema - only configuration entry CONFIG_SCHEMA = vol.Schema({}, extra=vol.ALLOW_EXTRA) async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool: """Stub to allow setting up this component. Configuration through YAML is not supported at this time. """ return True async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: """Set up the esphome component.""" hass.data.setdefault(DATA_KEY, {}) host = entry.data[CONF_HOST] port = entry.data[CONF_PORT] password = entry.data[CONF_PASSWORD] cli = APIClient( hass.loop, host, port, password, client_info="Home Assistant {}".format(const.__version__), ) # Store client in per-config-entry hass.data store = Store( hass, STORAGE_VERSION, STORAGE_KEY.format(entry.entry_id), encoder=JSONEncoder ) entry_data = hass.data[DATA_KEY][entry.entry_id] = RuntimeEntryData( client=cli, entry_id=entry.entry_id, store=store ) async def on_stop(event: Event) -> None: """Cleanup the socket client on HA stop.""" await _cleanup_instance(hass, entry) entry_data.cleanup_callbacks.append( hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, on_stop) ) @callback def async_on_state(state: EntityState) -> None: """Send dispatcher updates when a new state is received.""" entry_data.async_update_state(hass, state) @callback def async_on_service_call(service: HomeassistantServiceCall) -> None: """Call service when user automation in ESPHome config is triggered.""" domain, service_name = service.service.split(".", 1) service_data = service.data if service.data_template: try: data_template = { key: Template(value) for key, value in service.data_template.items() } template.attach(hass, data_template) service_data.update( template.render_complex(data_template, service.variables) ) except TemplateError as ex: _LOGGER.error("Error rendering data template: %s", ex) return if service.is_event: # ESPHome uses servicecall packet for both events and service calls # Ensure the user can only send events of form 'esphome.xyz' if domain != "esphome": _LOGGER.error("Can only generate events under esphome " "domain!") return hass.bus.async_fire(service.service, service_data) else: hass.async_create_task( hass.services.async_call( domain, service_name, service_data, blocking=True ) ) async def send_home_assistant_state( entity_id: str, _, new_state: Optional[State] ) -> None: """Forward Home Assistant states to ESPHome.""" if new_state is None: return await cli.send_home_assistant_state(entity_id, new_state.state) @callback def async_on_state_subscription(entity_id: str) -> None: """Subscribe and forward states for requested entities.""" unsub = async_track_state_change(hass, entity_id, send_home_assistant_state) entry_data.disconnect_callbacks.append(unsub) # Send initial state hass.async_create_task( send_home_assistant_state(entity_id, None, hass.states.get(entity_id)) ) async def on_login() -> None: """Subscribe to states and list entities on successful API login.""" try: entry_data.device_info = await cli.device_info() entry_data.available = True await _async_setup_device_registry(hass, entry, entry_data.device_info) entry_data.async_update_device_state(hass) entity_infos, services = await cli.list_entities_services() await entry_data.async_update_static_infos(hass, entry, entity_infos) await _setup_services(hass, entry_data, services) await cli.subscribe_states(async_on_state) await cli.subscribe_service_calls(async_on_service_call) await cli.subscribe_home_assistant_states(async_on_state_subscription) hass.async_create_task(entry_data.async_save_to_store()) except APIConnectionError as err: _LOGGER.warning("Error getting initial data: %s", err) # Re-connection logic will trigger after this await cli.disconnect() try_connect = await _setup_auto_reconnect_logic(hass, cli, entry, host, on_login) async def complete_setup() -> None: """Complete the config entry setup.""" infos, services = await entry_data.async_load_from_store() await entry_data.async_update_static_infos(hass, entry, infos) await _setup_services(hass, entry_data, services) # Create connection attempt outside of HA's tracked task in order # not to delay startup. hass.loop.create_task(try_connect(is_disconnect=False)) hass.async_create_task(complete_setup()) return True async def _setup_auto_reconnect_logic( hass: HomeAssistantType, cli: APIClient, entry: ConfigEntry, host: str, on_login ): """Set up the re-connect logic for the API client.""" async def try_connect(tries: int = 0, is_disconnect: bool = True) -> None: """Try connecting to the API client. Will retry if not successful.""" if entry.entry_id not in hass.data[DOMAIN]: # When removing/disconnecting manually return data = hass.data[DOMAIN][entry.entry_id] # type: RuntimeEntryData for disconnect_cb in data.disconnect_callbacks: disconnect_cb() data.disconnect_callbacks = [] data.available = False data.async_update_device_state(hass) if is_disconnect: # This can happen often depending on WiFi signal strength. # So therefore all these connection warnings are logged # as infos. The "unavailable" logic will still trigger so the # user knows if the device is not connected. _LOGGER.info("Disconnected from ESPHome API for %s", host) if tries != 0: # If not first re-try, wait and print message # Cap wait time at 1 minute. This is because while working on the # device (e.g. soldering stuff), users don't want to have to wait # a long time for their device to show up in HA again (this was # mentioned a lot in early feedback) # # In the future another API will be set up so that the ESP can # notify HA of connectivity directly, but for new we'll use a # really short reconnect interval. tries = min(tries, 10) # prevent OverflowError wait_time = int(round(min(1.8 ** tries, 60.0))) _LOGGER.info("Trying to reconnect in %s seconds", wait_time) await asyncio.sleep(wait_time) try: await cli.connect(on_stop=try_connect, login=True) except APIConnectionError as error: _LOGGER.info("Can't connect to ESPHome API for %s: %s", host, error) # Schedule re-connect in event loop in order not to delay HA # startup. First connect is scheduled in tracked tasks. data.reconnect_task = hass.loop.create_task( try_connect(tries + 1, is_disconnect=False) ) else: _LOGGER.info("Successfully connected to %s", host) hass.async_create_task(on_login()) return try_connect async def _async_setup_device_registry( hass: HomeAssistantType, entry: ConfigEntry, device_info: DeviceInfo ): """Set up device registry feature for a particular config entry.""" sw_version = device_info.esphome_version if device_info.compilation_time: sw_version += " ({})".format(device_info.compilation_time) device_registry = await dr.async_get_registry(hass) device_registry.async_get_or_create( config_entry_id=entry.entry_id, connections={(dr.CONNECTION_NETWORK_MAC, device_info.mac_address)}, name=device_info.name, manufacturer="espressif", model=device_info.model, sw_version=sw_version, ) async def _register_service( hass: HomeAssistantType, entry_data: RuntimeEntryData, service: UserService ): service_name = "{}_{}".format(entry_data.device_info.name, service.name) schema = {} for arg in service.args: schema[vol.Required(arg.name)] = { UserServiceArgType.BOOL: cv.boolean, UserServiceArgType.INT: vol.Coerce(int), UserServiceArgType.FLOAT: vol.Coerce(float), UserServiceArgType.STRING: cv.string, UserServiceArgType.BOOL_ARRAY: [cv.boolean], UserServiceArgType.INT_ARRAY: [vol.Coerce(int)], UserServiceArgType.FLOAT_ARRAY: [vol.Coerce(float)], UserServiceArgType.STRING_ARRAY: [cv.string], }[arg.type_] async def execute_service(call): await entry_data.client.execute_service(service, call.data) hass.services.async_register( DOMAIN, service_name, execute_service, vol.Schema(schema) ) async def _setup_services( hass: HomeAssistantType, entry_data: RuntimeEntryData, services: List[UserService] ): old_services = entry_data.services.copy() to_unregister = [] to_register = [] for service in services: if service.key in old_services: # Already exists matching = old_services.pop(service.key) if matching != service: # Need to re-register to_unregister.append(matching) to_register.append(service) else: # New service to_register.append(service) for service in old_services.values(): to_unregister.append(service) entry_data.services = {serv.key: serv for serv in services} for service in to_unregister: service_name = "{}_{}".format(entry_data.device_info.name, service.name) hass.services.async_remove(DOMAIN, service_name) for service in to_register: await _register_service(hass, entry_data, service) async def _cleanup_instance( hass: HomeAssistantType, entry: ConfigEntry ) -> RuntimeEntryData: """Cleanup the esphome client if it exists.""" data = hass.data[DATA_KEY].pop(entry.entry_id) # type: RuntimeEntryData if data.reconnect_task is not None: data.reconnect_task.cancel() for disconnect_cb in data.disconnect_callbacks: disconnect_cb() for cleanup_callback in data.cleanup_callbacks: cleanup_callback() await data.client.disconnect() return data async def async_unload_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: """Unload an esphome config entry.""" entry_data = await _cleanup_instance(hass, entry) tasks = [] for platform in entry_data.loaded_platforms: tasks.append(hass.config_entries.async_forward_entry_unload(entry, platform)) if tasks: await asyncio.wait(tasks) return True async def platform_async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities, *, component_key: str, info_type, entity_type, state_type, ) -> None: """Set up an esphome platform. This method is in charge of receiving, distributing and storing info and state updates. """ entry_data = hass.data[DOMAIN][entry.entry_id] # type: RuntimeEntryData entry_data.info[component_key] = {} entry_data.state[component_key] = {} @callback def async_list_entities(infos: List[EntityInfo]): """Update entities of this platform when entities are listed.""" old_infos = entry_data.info[component_key] new_infos = {} add_entities = [] for info in infos: if not isinstance(info, info_type): # Filter out infos that don't belong to this platform. continue if info.key in old_infos: # Update existing entity old_infos.pop(info.key) else: # Create new entity entity = entity_type(entry.entry_id, component_key, info.key) add_entities.append(entity) new_infos[info.key] = info # Remove old entities for info in old_infos.values(): entry_data.async_remove_entity(hass, component_key, info.key) entry_data.info[component_key] = new_infos async_add_entities(add_entities) signal = DISPATCHER_ON_LIST.format(entry_id=entry.entry_id) entry_data.cleanup_callbacks.append( async_dispatcher_connect(hass, signal, async_list_entities) ) @callback def async_entity_state(state: EntityState): """Notify the appropriate entity of an updated state.""" if not isinstance(state, state_type): return entry_data.state[component_key][state.key] = state entry_data.async_update_entity(hass, component_key, state.key) signal = DISPATCHER_ON_STATE.format(entry_id=entry.entry_id) entry_data.cleanup_callbacks.append( async_dispatcher_connect(hass, signal, async_entity_state) ) def esphome_state_property(func): """Wrap a state property of an esphome entity. This checks if the state object in the entity is set, and prevents writing NAN values to the Home Assistant state machine. """ @property def _wrapper(self): # pylint: disable=protected-access if self._state is None: return None val = func(self) if isinstance(val, float) and math.isnan(val): # Home Assistant doesn't use NAN values in state machine # (not JSON serializable) return None return val return _wrapper class EsphomeEnumMapper: """Helper class to convert between hass and esphome enum values.""" def __init__(self, func: Callable[[], Dict[int, str]]): """Construct a EsphomeEnumMapper.""" self._func = func def from_esphome(self, value: int) -> str: """Convert from an esphome int representation to a hass string.""" return self._func()[value] def from_hass(self, value: str) -> int: """Convert from a hass string to a esphome int representation.""" inverse = {v: k for k, v in self._func().items()} return inverse[value] def esphome_map_enum(func: Callable[[], Dict[int, str]]): """Map esphome int enum values to hass string constants. This class has to be used as a decorator. This ensures the aioesphomeapi import is only happening at runtime. """ return EsphomeEnumMapper(func) class EsphomeEntity(Entity): """Define a generic esphome entity.""" def __init__(self, entry_id: str, component_key: str, key: int): """Initialize.""" self._entry_id = entry_id self._component_key = component_key self._key = key self._remove_callbacks = [] # type: List[Callable[[], None]] async def async_added_to_hass(self) -> None: """Register callbacks.""" kwargs = { "entry_id": self._entry_id, "component_key": self._component_key, "key": self._key, } self._remove_callbacks.append( async_dispatcher_connect( self.hass, DISPATCHER_UPDATE_ENTITY.format(**kwargs), self._on_update ) ) self._remove_callbacks.append( async_dispatcher_connect( self.hass, DISPATCHER_REMOVE_ENTITY.format(**kwargs), self.async_remove ) ) self._remove_callbacks.append( async_dispatcher_connect( self.hass, DISPATCHER_ON_DEVICE_UPDATE.format(**kwargs), self.async_schedule_update_ha_state, ) ) async def _on_update(self) -> None: """Update the entity state when state or static info changed.""" self.async_schedule_update_ha_state() async def async_will_remove_from_hass(self) -> None: """Unregister callbacks.""" for remove_callback in self._remove_callbacks: remove_callback() self._remove_callbacks = [] @property def _entry_data(self) -> RuntimeEntryData: return self.hass.data[DATA_KEY][self._entry_id] @property def _static_info(self) -> EntityInfo: return self._entry_data.info[self._component_key][self._key] @property def _device_info(self) -> DeviceInfo: return self._entry_data.device_info @property def _client(self) -> APIClient: return self._entry_data.client @property def _state(self) -> Optional[EntityState]: try: return self._entry_data.state[self._component_key][self._key] except KeyError: return None @property def available(self) -> bool: """Return if the entity is available.""" device = self._device_info if device.has_deep_sleep: # During deep sleep the ESP will not be connectable (by design) # For these cases, show it as available return True return self._entry_data.available @property def unique_id(self) -> Optional[str]: """Return a unique id identifying the entity.""" if not self._static_info.unique_id: return None return self._static_info.unique_id @property def device_info(self) -> Dict[str, Any]: """Return device registry information for this entity.""" return { "connections": {(dr.CONNECTION_NETWORK_MAC, self._device_info.mac_address)} } @property def name(self) -> str: """Return the name of the entity.""" return self._static_info.name @property def should_poll(self) -> bool: """Disable polling.""" return False
"""Test the owntracks_http platform.""" import asyncio import pytest from homeassistant.setup import async_setup_component from homeassistant.components import owntracks from tests.common import mock_component, MockConfigEntry MINIMAL_LOCATION_MESSAGE = { "_type": "location", "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "tst": 1, } LOCATION_MESSAGE = { "_type": "location", "acc": 60, "alt": 27, "batt": 92, "cog": 248, "lon": 45, "lat": 90, "p": 101.3977584838867, "tid": "test", "t": "u", "tst": 1, "vac": 4, "vel": 0, } @pytest.fixture(autouse=True) def mock_dev_track(mock_device_tracker_conf): """Mock device tracker config loading.""" pass @pytest.fixture def mock_client(hass, aiohttp_client): """Start the Hass HTTP component.""" mock_component(hass, "group") mock_component(hass, "zone") mock_component(hass, "device_tracker") MockConfigEntry( domain="owntracks", data={"webhook_id": "owntracks_test", "secret": "abcd"} ).add_to_hass(hass) hass.loop.run_until_complete(async_setup_component(hass, "owntracks", {})) return hass.loop.run_until_complete(aiohttp_client(hass.http.app)) @asyncio.coroutine def test_handle_valid_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_valid_minimal_message(mock_client): """Test that we forward messages correctly to OwnTracks.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=MINIMAL_LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] @asyncio.coroutine def test_handle_value_error(mock_client): """Test we don't disclose that this is a valid webhook.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json="", headers={"X-Limit-u": "Paulus", "X-Limit-d": "Pixel"}, ) assert resp.status == 200 json = yield from resp.text() assert json == "" @asyncio.coroutine def test_returns_error_missing_username(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-d": "Pixel"}, ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "No topic or user found" in caplog.text @asyncio.coroutine def test_returns_error_incorrect_json(mock_client, caplog): """Test that an error is returned when username is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", data="not json", headers={"X-Limit-d": "Pixel"} ) # Needs to be 200 or OwnTracks keeps retrying bad packet. assert resp.status == 200 json = yield from resp.json() assert json == [] assert "invalid JSON" in caplog.text @asyncio.coroutine def test_returns_error_missing_device(mock_client): """Test that an error is returned when device name is missing.""" resp = yield from mock_client.post( "/api/webhook/owntracks_test", json=LOCATION_MESSAGE, headers={"X-Limit-u": "Paulus"}, ) assert resp.status == 200 json = yield from resp.json() assert json == [] def test_context_delivers_pending_msg(): """Test that context is able to hold pending messages while being init.""" context = owntracks.OwnTracksContext(None, None, None, None, None, None, None, None) context.async_see(hello="world") context.async_see(world="hello") received = [] context.set_async_see(lambda **data: received.append(data)) assert len(received) == 2 assert received[0] == {"hello": "world"} assert received[1] == {"world": "hello"} received.clear() context.set_async_see(lambda **data: received.append(data)) assert len(received) == 0
fbradyirl/home-assistant
tests/components/owntracks/test_init.py
homeassistant/components/esphome/__init__.py
# -*- coding: utf-8 -*- import attr from navmazing import NavigateToAttribute from navmazing import NavigateToSibling from widgetastic.widget import NoSuchElementException from widgetastic.widget import Text from widgetastic.widget import View from widgetastic_patternfly import BootstrapNav from widgetastic_patternfly import BreadCrumb from widgetastic_patternfly import Button from widgetastic_patternfly import Dropdown from cfme.base.ui import BaseLoggedInPage from cfme.common import Taggable from cfme.common import TagPageView from cfme.exceptions import ItemNotFound from cfme.modeling.base import BaseCollection from cfme.modeling.base import BaseEntity from cfme.utils.appliance.implementations.ui import CFMENavigateStep from cfme.utils.appliance.implementations.ui import navigate_to from cfme.utils.appliance.implementations.ui import navigator from cfme.utils.log import logger from cfme.utils.providers import get_crud_by_name from cfme.utils.wait import wait_for from widgetastic_manageiq import Accordion from widgetastic_manageiq import BaseEntitiesView from widgetastic_manageiq import ItemsToolBarViewSelector from widgetastic_manageiq import ManageIQTree from widgetastic_manageiq import Search from widgetastic_manageiq import SummaryTable class VolumeSnapshotToolbar(View): """The toolbar on the Volume Snapshot page""" policy = Dropdown('Policy') download = Dropdown('Download') view_selector = View.nested(ItemsToolBarViewSelector) class VolumeSnapshotDetailsToolbar(View): """The toolbar on the Volume Snapshot detail page""" configuration = Dropdown('Configuration') policy = Dropdown('Policy') download = Button('Print or export summary') class VolumeSnapshotDetailsEntities(View): """The entities on the Volume Snapshot detail page""" breadcrumb = BreadCrumb() title = Text('.//div[@id="center_div" or @id="main-content"]//h1') properties = SummaryTable('Properties') relationships = SummaryTable('Relationships') smart_management = SummaryTable('Smart Management') class VolumeSnapshotDetailSidebar(View): """The accordion on the Volume Snapshot details page""" @View.nested class properties(Accordion): # noqa tree = ManageIQTree() @View.nested class relationships(Accordion): # noqa tree = ManageIQTree() class VolumeSnapshotView(BaseLoggedInPage): """A base view for all the Volume Snapshot pages""" @property def in_volume_snapshots(self): return ( self.logged_in_as_current_user and self.navigation.currently_selected == ['Storage', 'Block Storage', 'Volume Snapshots'] ) @property def is_displayed(self): return self.in_volume_snapshots class VolumeSnapshotAllView(VolumeSnapshotView): """The all Volume Snapshot page""" toolbar = View.nested(VolumeSnapshotToolbar) search = View.nested(Search) including_entities = View.include(BaseEntitiesView, use_parent=True) @property def is_displayed(self): return ( self.in_volume_snapshots and self.entities.title.text == 'Cloud Volume Snapshots') @View.nested class my_filters(Accordion): # noqa ACCORDION_NAME = "My Filters" navigation = BootstrapNav('.//div/ul') tree = ManageIQTree() class VolumeSnapshotDetailsView(VolumeSnapshotView): """The detail Volume Snapshot page""" @property def is_displayed(self): obj = self.context['object'] return ( self.in_volume_snapshots and self.entities.title.text == obj.expected_details_title and self.entities.breadcrumb.active_location == obj.expected_details_breadcrumb ) toolbar = View.nested(VolumeSnapshotDetailsToolbar) sidebar = View.nested(VolumeSnapshotDetailSidebar) entities = View.nested(VolumeSnapshotDetailsEntities) @attr.s class VolumeSnapshot(BaseEntity, Taggable): """ Model of an Storage Volume Snapshots in cfme Args: name: name of the snapshot provider: provider """ name = attr.ib() provider = attr.ib() def refresh(self): self.provider.refresh_provider_relationships() self.browser.refresh() @property def exists(self): """ check for snapshot exist on UI. Returns: :py:class:`bool` """ view = navigate_to(self.parent, 'All') return self.name in view.entities.all_entity_names @property def status(self): """ status of cloud volume snapshot. Returns: :py:class:`str` Status of volume snapshot. """ view = navigate_to(self.parent, 'All') view.toolbar.view_selector.select("List View") try: ent = view.entities.get_entity(name=self.name, surf_pages=True) return ent.data["status"] except ItemNotFound: return False @property def size(self): """ size of cloud volume snapshot. Returns: :py:class:`int` size of volume snapshot in GB. """ view = navigate_to(self, 'Details') return int(view.entities.properties.get_text_of('Size').split()[0]) @property def volume_name(self): """ volume name of snapshot. Returns: :py:class:`str` respective volume name. """ view = navigate_to(self, 'Details') return view.entities.relationships.get_text_of('Cloud Volume') @property def tenant_name(self): """ Tenant name of snapshot. Returns: :py:class:`str` respective tenant name for snapshot. """ view = navigate_to(self, 'Details') return view.entities.relationships.get_text_of('Cloud Tenants') def delete(self, wait=True): """Delete snapshot """ view = navigate_to(self, 'Details') view.toolbar.configuration.item_select('Delete Cloud Volume Snapshot') view.flash.assert_success_message('Delete initiated for 1 Cloud Volume Snapshot.') if wait: wait_for( lambda: not self.exists, message="Wait snapshot to disappear", delay=20, timeout=800, fail_func=self.refresh ) @attr.s class VolumeSnapshotCollection(BaseCollection): """Collection object for :py:class:`cfme.storage.volume_snapshots.VolumeSnapshot`""" ENTITY = VolumeSnapshot def all(self): """returning all Snapshot objects for respective storage manager type""" view = navigate_to(self, 'All') view.toolbar.view_selector.select("List View") snapshots = [] try: if 'provider' in self.filters: for item in view.entities.elements.read(): if self.filters.get('provider').name in item['Storage Manager']: snapshots.append(self.instantiate(name=item['Name'], provider=self.filters.get('provider'))) else: for item in view.entities.elements.read(): provider_name = item['Storage Manager'].split()[0] provider = get_crud_by_name(provider_name) snapshots.append(self.instantiate(name=item['Name'], provider=provider)) except NoSuchElementException: if snapshots: logger.error('VolumeSnapshotCollection: ' 'NoSuchElementException in the middle of entities read') else: logger.warning('The snapshot table is probably not present or empty') return snapshots @navigator.register(VolumeSnapshotCollection, 'All') class All(CFMENavigateStep): VIEW = VolumeSnapshotAllView prerequisite = NavigateToAttribute('appliance.server', 'LoggedIn') def step(self, *args, **kwargs): self.prerequisite_view.navigation.select('Storage', 'Block Storage', 'Volume Snapshots') @navigator.register(VolumeSnapshot, 'Details') class Details(CFMENavigateStep): VIEW = VolumeSnapshotDetailsView prerequisite = NavigateToAttribute('parent', 'All') def step(self, *args, **kwargs): try: self.prerequisite_view.entities.get_entity(name=self.obj.name, surf_pages=True).click() except ItemNotFound: raise ItemNotFound( 'Could not locate volume snapshot {}'.format(self.obj.name) ) @navigator.register(VolumeSnapshot, 'EditTagsFromDetails') class SnapshotDetailEditTag(CFMENavigateStep): """ This navigation destination help to Taggable""" VIEW = TagPageView prerequisite = NavigateToSibling('Details') def step(self, *args, **kwargs): self.prerequisite_view.toolbar.policy.item_select('Edit Tags')
import pytest from cfme import test_requirements from cfme.cloud.provider.azure import AzureProvider from cfme.cloud.provider.ec2 import EC2Provider from cfme.cloud.provider.gce import GCEProvider from cfme.common.candu_views import UtilizationZoomView from cfme.tests.candu import compare_data from cfme.utils.appliance.implementations.ui import navigate_to from cfme.utils.blockers import BZ from cfme.utils.log import logger from cfme.utils.wait import wait_for pytestmark = [ pytest.mark.tier(3), test_requirements.c_and_u, pytest.mark.usefixtures("setup_provider"), pytest.mark.provider( [AzureProvider, EC2Provider, GCEProvider], required_fields=[["cap_and_util", "capandu_azone"]], ), ] GRAPHS = ["azone_cpu", "azone_memory", "azone_disk", "azone_network", "azone_instance"] # To-Do: Add support for Daily interval INTERVAL = ["Hourly"] @pytest.fixture(scope="function") def azone(appliance, provider): collection = appliance.collections.cloud_av_zones azone_name = provider.data["cap_and_util"]["capandu_azone"] return collection.instantiate(name=azone_name, provider=provider) @pytest.mark.parametrize("interval", INTERVAL) @pytest.mark.parametrize("graph_type", GRAPHS) @pytest.mark.meta( blockers=[BZ(1724415, forced_streams=['5.10', '5.11'], unblock=lambda provider, graph_type: not provider.one_of(AzureProvider) and graph_type != "azone_memory")] ) @pytest.mark.uncollectif(lambda provider, graph_type: provider.one_of(EC2Provider) and graph_type == "azone_disk") def test_azone_graph_screen(provider, azone, graph_type, interval, enable_candu): """Test Availibility zone graphs for Hourly prerequisites: * C&U enabled appliance Steps: * Navigate to Availibility Zone Utilization Page * Check graph displayed or not * Select interval Hourly * Zoom graph to get Table * Compare table and graph data Polarion: assignee: nachandr caseimportance: medium casecomponent: CandU initialEstimate: 1/4h """ azone.wait_candu_data_available(timeout=1200) view = navigate_to(azone, "Utilization") view.options.interval.fill(interval) # Check graph displayed or not try: graph = getattr(view, graph_type) except AttributeError as e: logger.error(e) assert graph.is_displayed def refresh(): provider.browser.refresh() view.options.interval.fill(interval) # wait, some time graph take time to load wait_for(lambda: len(graph.all_legends) > 0, delay=5, timeout=200, fail_func=refresh) # zoom in button not available with normal graph except Instance in Azone Utilization page. # We have to use vm average graph for zoom in operation. avg_graph = graph_type if graph_type == "azone_instance" else "{}_avg".format(graph_type) try: avg_graph = getattr(view, avg_graph) except AttributeError as e: logger.error(e) avg_graph.zoom_in() view = view.browser.create_view(UtilizationZoomView) # wait, some time graph take time to load wait_for(lambda: len(view.chart.all_legends) > 0, delay=5, timeout=300, fail_func=refresh) assert view.chart.is_displayed view.flush_widget_cache() legends = view.chart.all_legends graph_data = view.chart.all_data # Clear cache of table widget before read else it will mismatch headers. view.table.clear_cache() table_data = view.table.read() compare_data(table_data=table_data, graph_data=graph_data, legends=legends)
apagac/cfme_tests
cfme/tests/candu/test_azone_graph.py
cfme/storage/volume_snapshot.py
""" NOT TESTED YET """ import re from cfme.utils.conf import cfme_data from cfme.utils.log import logger from cfme.utils.template.base import log_wrap from cfme.utils.template.base import ProviderTemplateUpload from cfme.utils.template.base import TemplateUploadException class RHEVMTemplateUpload(ProviderTemplateUpload): provider_type = 'rhevm' log_name = 'RHEVM' image_pattern = re.compile( r'<a href="?\'?([^"\']*(?:(?:rhevm|ovirt)[^"\']*\.(?:qcow2|qc2))[^"\'>]*)') @log_wrap('add glance to rhevm provider') def add_glance_to_provider(self): """Add glance as an external provider if needed""" glance_data = cfme_data.template_upload.get(self.glance_key) if self.mgmt.does_glance_server_exist(self.glance_key): logger.info('RHEVM provider already has glance added, skipping step') else: self.mgmt.add_glance_server(name=self.glance_key, description=self.glance_key, url=glance_data.url, requires_authentication=False) return True @log_wrap("import template from Glance server") def import_template_from_glance(self): """Import the template from glance to local rhevm datastore, sucks.""" self.mgmt.import_glance_image( source_storage_domain_name=self.glance_key, target_cluster_name=self.provider_data.template_upload.cluster, source_template_name=self.image_name, target_template_name=self.temp_template_name, target_storage_domain_name=self.provider_data.template_upload.storage_domain) mgmt_network = self.provider_data.template_upload.get('management_network') rv_tmpl = self.mgmt.get_template(self.temp_template_name) if mgmt_network: # network devices, qcow template doesn't have any temp_nics = rv_tmpl.get_nics() nic_args = dict(network_name=mgmt_network, nic_name='eth0') if 'eth0' not in [n.name for n in temp_nics]: rv_tmpl.add_nic(**nic_args) else: rv_tmpl.update_nic(**nic_args) return True @log_wrap('Deploy template to vm - before templatizing') def deploy_vm_from_template(self): """Deploy a VM from the raw template with resource limits set from yaml""" stream_hardware = cfme_data.template_upload.hardware[self.stream] self.mgmt.get_template(self.temp_template_name).deploy( vm_name=self.temp_vm_name, cluster=self.provider_data.template_upload.cluster, storage_domain=self.provider_data.template_upload.storage_domain, cpu=stream_hardware.cores, sockets=stream_hardware.sockets, ram=int(stream_hardware.memory) * 2**30) # GB -> B # check, if the vm is really there if not self.mgmt.does_vm_exist(self.temp_vm_name): raise TemplateUploadException('Failed to deploy VM from imported template') return True @log_wrap('Add db disk to temp vm') def add_disk_to_vm(self): """Add a disk with specs from cfme_data.template_upload Generally for database disk """ temp_vm = self.mgmt.get_vm(self.temp_vm_name) if temp_vm.get_disks_count() > 1: logger.warning('%s Warning: found more than one disk in existing VM (%s).', self.provider_key, self.temp_vm_name) return rhevm_specs = cfme_data.template_upload.template_upload_rhevm disk_kwargs = dict(storage_domain=self.provider_data.template_upload.storage_domain, size=rhevm_specs.get('disk_size', 5000000000), interface=rhevm_specs.get('disk_interface', 'virtio'), format=rhevm_specs.get('disk_format', 'cow'), name=rhevm_specs.get('disk_name')) temp_vm.add_disk(**disk_kwargs) # check, if there are two disks if temp_vm.get_disks_count() < 2: raise TemplateUploadException('%s disk failed to add with specs: %r', self.provider_key, disk_kwargs) logger.info('%s:%s Successfully added disk', self.provider_key, self.temp_vm_name) return True @log_wrap('templatize temp vm with disk') def templatize_vm(self): """Templatizes temporary VM. Result is template with two disks. """ self.mgmt.get_vm(self.temp_vm_name).mark_as_template( template_name=self.template_name, cluster_name=self.provider_data.template_upload.cluster, storage_domain_name=self.provider_data.template_upload.get('template_domain', None), delete=False # leave vm in place in case it fails, for debug ) # check, if template is really there if not self.mgmt.does_template_exist(self.template_name): raise TemplateUploadException('%s templatizing %s to %s FAILED', self.provider_key, self.temp_vm_name, self.template_name) logger.info(":%s successfully templatized %s to %s", self.provider_key, self.temp_vm_name, self.template_name) return True @log_wrap('cleanup temp resources') def teardown(self): """Cleans up all the mess that the previous functions left behind.""" logger.info('%s Deleting temp_vm "%s"', self.provider_key, self.temp_vm_name) if self.mgmt.does_vm_exist(self.temp_vm_name): self.mgmt.get_vm(self.temp_vm_name).cleanup() logger.info('%s Deleting temp_template "%s"on storage domain', self.provider_key, self.temp_template_name) if self.mgmt.does_template_exist(self.temp_template_name): self.mgmt.get_template(self.temp_template_name).cleanup() return True def run(self): """call methods for individual steps of CFME templatization of qcow2 image from glance""" try: self.glance_upload() self.add_glance_to_provider() self.import_template_from_glance() self.deploy_vm_from_template() if self.stream == 'upstream': self.manageiq_cleanup() self.add_disk_to_vm() self.templatize_vm() return True except Exception: logger.exception('template creation failed for provider {}'.format( self.provider_data.name)) return False
import pytest from cfme import test_requirements from cfme.cloud.provider.azure import AzureProvider from cfme.cloud.provider.ec2 import EC2Provider from cfme.cloud.provider.gce import GCEProvider from cfme.common.candu_views import UtilizationZoomView from cfme.tests.candu import compare_data from cfme.utils.appliance.implementations.ui import navigate_to from cfme.utils.blockers import BZ from cfme.utils.log import logger from cfme.utils.wait import wait_for pytestmark = [ pytest.mark.tier(3), test_requirements.c_and_u, pytest.mark.usefixtures("setup_provider"), pytest.mark.provider( [AzureProvider, EC2Provider, GCEProvider], required_fields=[["cap_and_util", "capandu_azone"]], ), ] GRAPHS = ["azone_cpu", "azone_memory", "azone_disk", "azone_network", "azone_instance"] # To-Do: Add support for Daily interval INTERVAL = ["Hourly"] @pytest.fixture(scope="function") def azone(appliance, provider): collection = appliance.collections.cloud_av_zones azone_name = provider.data["cap_and_util"]["capandu_azone"] return collection.instantiate(name=azone_name, provider=provider) @pytest.mark.parametrize("interval", INTERVAL) @pytest.mark.parametrize("graph_type", GRAPHS) @pytest.mark.meta( blockers=[BZ(1724415, forced_streams=['5.10', '5.11'], unblock=lambda provider, graph_type: not provider.one_of(AzureProvider) and graph_type != "azone_memory")] ) @pytest.mark.uncollectif(lambda provider, graph_type: provider.one_of(EC2Provider) and graph_type == "azone_disk") def test_azone_graph_screen(provider, azone, graph_type, interval, enable_candu): """Test Availibility zone graphs for Hourly prerequisites: * C&U enabled appliance Steps: * Navigate to Availibility Zone Utilization Page * Check graph displayed or not * Select interval Hourly * Zoom graph to get Table * Compare table and graph data Polarion: assignee: nachandr caseimportance: medium casecomponent: CandU initialEstimate: 1/4h """ azone.wait_candu_data_available(timeout=1200) view = navigate_to(azone, "Utilization") view.options.interval.fill(interval) # Check graph displayed or not try: graph = getattr(view, graph_type) except AttributeError as e: logger.error(e) assert graph.is_displayed def refresh(): provider.browser.refresh() view.options.interval.fill(interval) # wait, some time graph take time to load wait_for(lambda: len(graph.all_legends) > 0, delay=5, timeout=200, fail_func=refresh) # zoom in button not available with normal graph except Instance in Azone Utilization page. # We have to use vm average graph for zoom in operation. avg_graph = graph_type if graph_type == "azone_instance" else "{}_avg".format(graph_type) try: avg_graph = getattr(view, avg_graph) except AttributeError as e: logger.error(e) avg_graph.zoom_in() view = view.browser.create_view(UtilizationZoomView) # wait, some time graph take time to load wait_for(lambda: len(view.chart.all_legends) > 0, delay=5, timeout=300, fail_func=refresh) assert view.chart.is_displayed view.flush_widget_cache() legends = view.chart.all_legends graph_data = view.chart.all_data # Clear cache of table widget before read else it will mismatch headers. view.table.clear_cache() table_data = view.table.read() compare_data(table_data=table_data, graph_data=graph_data, legends=legends)
apagac/cfme_tests
cfme/tests/candu/test_azone_graph.py
cfme/utils/template/rhevm.py
# -*- coding: utf-8 -*- import attr from cached_property import cached_property from navmazing import NavigateToAttribute, NavigateToSibling from widgetastic.utils import ParametrizedLocator from widgetastic.widget import Table, Text, View from widgetastic_manageiq import SummaryFormItem, ScriptBox, Input from widgetastic_patternfly import BootstrapSelect, BootstrapSwitch, Button, CandidateNotFound from cfme.exceptions import ItemNotFound from cfme.modeling.base import BaseCollection, BaseEntity from cfme.utils.appliance.implementations.ui import navigator, CFMENavigateStep, navigate_to from cfme.utils.blockers import BZ from cfme.utils.timeutil import parsetime from cfme.utils.version import Version from cfme.utils.wait import wait_for from . import AutomateExplorerView, check_tree_path from .common import Copiable, CopyViewBase from .klass import ClassDetailsView class MethodCopyView(AutomateExplorerView, CopyViewBase): @property def is_displayed(self): return ( self.in_explorer and self.title.text == 'Copy Automate Method' and self.datastore.is_opened and check_tree_path( self.datastore.tree.currently_selected, self.context['object'].tree_path)) class MethodDetailsView(AutomateExplorerView): title = Text('#explorer_title_text') fqdn = SummaryFormItem( 'Main Info', 'Fully Qualified Name', text_filter=lambda text: [item.strip() for item in text.strip().lstrip('/').split('/')]) name = SummaryFormItem('Main Info', 'Name') display_name = SummaryFormItem('Main Info', 'Display Name') location = SummaryFormItem('Main Info', 'Location') created_on = SummaryFormItem('Main Info', 'Created On', text_filter=parsetime.from_iso_with_utc) @property def is_displayed(self): return ( self.in_explorer and self.title.text.startswith('Automate Method [{}'.format( self.context['object'].display_name or self.context['object'].name)) and self.fqdn.is_displayed and # We need to chop off the leading Domain name. self.fqdn.text == self.context['object'].tree_path_name_only[1:]) class PlaybookBootstrapSelect(BootstrapSelect): """BootstrapSelect widget for Ansible Playbook Method form. BootstrapSelect widgets don't have ``data-id`` attribute in this form, so we have to override ROOT locator. """ ROOT = ParametrizedLocator('.//select[normalize-space(@name)={@id|quote}]/..') class ActionsCell(View): edit = Button(**{"ng-click": "vm.editKeyValue(this.arr[0], this.arr[1], this.arr[2], $index)"}) delete = Button(**{"ng-click": "vm.removeKeyValue($index)"}) class PlaybookInputParameters(View): """Represents input parameters part of playbook method edit form. """ input_name = Input(name="provisioning_key") default_value = Input(name="provisioning_value") provisioning_type = PlaybookBootstrapSelect("provisioning_type") add_button = Button(**{"ng-click": "vm.addKeyValue()"}) variables_table = Table( ".//div[@id='inputs_div']//table", column_widgets={"Actions": ActionsCell()} ) def _values_to_remove(self, values): return list(set(self.all_vars) - set(values)) def _values_to_add(self, values): return list(set(values) - set(self.all_vars)) def fill(self, values): """ Args: values (list): [] to remove all vars or [("var", "value", "type"), ...] to fill the view """ if set(values) == set(self.all_vars): return False else: for value in self._values_to_remove(values): rows = list(self.variables_table) for row in rows: if row[0].text == value[0]: row["Actions"].widget.delete.click() break for value in self._values_to_add(values): self.input_name.fill(value[0]) self.default_value.fill(value[1]) self.provisioning_type.fill(value[2]) self.add_button.click() return True @property def all_vars(self): if self.variables_table.is_displayed: return [(row["Input Name"].text, row["Default value"].text, row["Data Type"].text) for row in self.variables_table] else: return [] def read(self): return self.all_vars class MethodAddView(AutomateExplorerView): title = Text('#explorer_title_text') location = BootstrapSelect('cls_method_location', can_hide_on_select=True) inline_name = Input(name='cls_method_name') inline_display_name = Input(name='cls_method_display_name') script = ScriptBox() data = Input(name='cls_method_data') validate_button = Button('Validate') # TODO: inline input parameters playbook_name = Input(name='name') playbook_display_name = Input(name='display_name') repository = PlaybookBootstrapSelect('provisioning_repository_id') playbook = PlaybookBootstrapSelect('provisioning_playbook_id') machine_credential = PlaybookBootstrapSelect('provisioning_machine_credential_id') hosts = Input('provisioning_inventory') max_ttl = Input('provisioning_execution_ttl') escalate_privilege = BootstrapSwitch('provisioning_become_enabled') verbosity = PlaybookBootstrapSelect('provisioning_verbosity') playbook_input_parameters = PlaybookInputParameters() add_button = Button('Add') cancel_button = Button('Cancel') @property def is_displayed(self): return ( self.in_explorer and self.datastore.is_opened and self.title.text == 'Adding a new Automate Method' and check_tree_path( self.datastore.tree.currently_selected, self.context['object'].tree_path)) class MethodEditView(AutomateExplorerView): title = Text('#explorer_title_text') # inline inline_name = Input(name='method_name') inline_display_name = Input(name='method_display_name') script = ScriptBox() data = Input(name='method_data') validate_button = Button('Validate') # TODO: inline input parameters # playbook playbook_name = Input(name='name') playbook_display_name = Input(name='display_name') repository = PlaybookBootstrapSelect('provisioning_repository_id') playbook = PlaybookBootstrapSelect('provisioning_playbook_id') machine_credential = PlaybookBootstrapSelect('provisioning_machine_credential_id') hosts = Input('provisioning_inventory') max_ttl = Input('provisioning_execution_ttl') escalate_privilege = BootstrapSwitch('provisioning_become_enabled') verbosity = PlaybookBootstrapSelect('provisioning_verbosity') playbook_input_parameters = PlaybookInputParameters() save_button = Button('Save') reset_button = Button('Reset') cancel_button = Button('Cancel') def before_fill(self, values): location = self.context['object'].location if 'display_name' in values and location in ['inline', 'playbook']: values['{}_display_name'.format(location)] = values['display_name'] del values['display_name'] elif 'name' in values and location in ['inline', 'playbook']: values['{}_name'.format(location)] = values['name'] del values['name'] @property def is_displayed(self): return ( self.in_explorer and self.datastore.is_opened and self.title.text == 'Editing Automate Method "{}"'.format( self.context['object'].name) and check_tree_path( self.datastore.tree.currently_selected, self.context['object'].tree_path)) class Method(BaseEntity, Copiable): def __init__(self, collection, name=None, display_name=None, location='inline', script=None, data=None, repository=None, playbook=None, machine_credential=None, hosts=None, max_ttl=None, escalate_privilege=None, verbosity=None, playbook_input_parameters=None, cancel=False, validate=True): super(Method, self).__init__(collection) self.name = name if display_name is not None: self.display_name = display_name self.location = location self.script = script self.data = data self.repository = repository self.playbook = playbook self.machine_credential = machine_credential self.hosts = hosts self.max_ttl = max_ttl self.escalate_privilege = escalate_privilege self.verbosity = verbosity self.playbook_input_parameters = playbook_input_parameters __repr__ = object.__repr__ @cached_property def display_name(self): return self.db_object.display_name @cached_property def db_id(self): table = self.appliance.db.client['miq_ae_methods'] try: return self.appliance.db.client.session.query(table.id).filter( table.name == self.name, table.class_id == self.klass.db_id)[0] # noqa except IndexError: raise ItemNotFound('Method named {} not found in the database'.format(self.name)) @property def db_object(self): table = self.appliance.db.client['miq_ae_methods'] return self.appliance.db.client.session.query(table).filter(table.id == self.db_id).first() @property def klass(self): return self.parent_obj @property def namespace(self): return self.klass.namespace @property def parent_obj(self): return self.parent.parent @property def domain(self): return self.parent_obj.domain @property def tree_path(self): if self.appliance.version < '5.9': icon_name_map = {'inline': 'product-method'} else: icon_name_map = {'inline': 'fa-ruby', 'playbook': 'vendor-ansible'} if self.display_name: return self.parent_obj.tree_path + [ (icon_name_map[self.location], '{} ({})'.format(self.display_name, self.name))] else: return self.parent_obj.tree_path + [(icon_name_map[self.location], self.name)] @property def tree_path_name_only(self): return self.parent_obj.tree_path_name_only + [self.name] def update(self, updates): view = navigate_to(self, 'Edit') changed = view.fill(updates) if changed: view.save_button.click() else: view.cancel_button.click() view = self.create_view(MethodDetailsView, override=updates) assert view.is_displayed view.flash.assert_no_error() if changed: view.flash.assert_message( 'Automate Method "{}" was saved'.format(updates.get('name', self.name))) else: view.flash.assert_message( 'Edit of Automate Method "{}" was cancelled by the user'.format(self.name)) def delete(self, cancel=False): details_page = navigate_to(self, 'Details') details_page.configuration.item_select('Remove this Method', handle_alert=not cancel) if cancel: assert details_page.is_displayed details_page.flash.assert_no_error() else: result_view = self.create_view(ClassDetailsView, self.parent_obj) assert result_view.is_displayed result_view.flash.assert_no_error() result_view.flash.assert_message( 'Automate Method "{}": Delete successful'.format(self.name)) @property def exists(self): try: navigate_to(self, 'Details') return True except CandidateNotFound: return False def delete_if_exists(self): if self.exists: self.delete() @attr.s class MethodCollection(BaseCollection): ENTITY = Method @property def tree_path(self): return self.parent.tree_path def create( self, name=None, display_name=None, location='inline', script=None, data=None, cancel=False, validate=True, repository=None, playbook=None, machine_credential=None, hosts=None, max_ttl=None, escalate_privilege=None, verbosity=None, playbook_input_parameters=None): add_page = navigate_to(self, 'Add', wait_for_view=True) add_page.fill({'location': location}) if location == 'inline': add_page.fill({ 'inline_name': name, 'inline_display_name': display_name, 'script': script, 'data': data }) if location == 'playbook': add_page.fill({ 'playbook_name': name, 'playbook_display_name': display_name, 'repository': repository }) wait_for(lambda: add_page.playbook.is_displayed, delay=0.5, num_sec=2) add_page.fill({ 'playbook': playbook, 'machine_credential': machine_credential, 'hosts': hosts, 'max_ttl': max_ttl, 'escalate_privilege': escalate_privilege, 'verbosity': verbosity, 'playbook_input_parameters': playbook_input_parameters }) validate = False if validate and not BZ(1499881, forced_streams=['5.9']).blocks: add_page.validate_button.click() add_page.flash.assert_no_error() add_page.flash.assert_message('Data validated successfully') if cancel: add_page.cancel_button.click() add_page.flash.assert_no_error() add_page.flash.assert_message('Add of new Automate Method was cancelled by the user') return None else: add_page.add_button.click() if self.appliance.version < "5.9": msg = 'Automate Method "{}" was added'.format(name) else: msg = 'Automate Method "{}" was saved'.format(name) add_page.flash.assert_success_message(msg) return self.instantiate( name=name, display_name=display_name, location=location, script=script, data=data, repository=repository, playbook=playbook, machine_credential=machine_credential, hosts=hosts, max_ttl=max_ttl, escalate_privilege=escalate_privilege, verbosity=verbosity, playbook_input_parameters=playbook_input_parameters) def delete(self, *methods): all_page = navigate_to(self.parent, 'Details') all_page.methods.select() methods = list(methods) parents = set() for method in methods: parents.add(method.parent) if len(parents) > 1: raise ValueError('You passed methods that are not under one class.') checked_methods = [] if not all_page.methods.table.is_displayed: raise ValueError('No method found!') all_page.methods.table.uncheck_all() for row in all_page.instances.table: name = row[2].text for method in methods: if ( (method.display_name and method.display_name == name) or method.name == name): checked_methods.append(method) row[0].check() break if set(methods) == set(checked_methods): break if set(methods) != set(checked_methods): raise ValueError('Some of the instances were not found in the UI.') all_page.configuration.item_select('Remove Methods', handle_alert=True) all_page.flash.assert_no_error() for method in checked_methods: all_page.flash.assert_message( 'Automate Method "{}": Delete successful'.format(method.name)) @navigator.register(MethodCollection) class Add(CFMENavigateStep): VIEW = MethodAddView prerequisite = NavigateToAttribute('parent', 'Details') def step(self): self.prerequisite_view.methods.select() self.prerequisite_view.configuration.item_select('Add a New Method') @navigator.register(Method) class Details(CFMENavigateStep): VIEW = MethodDetailsView prerequisite = NavigateToAttribute('domain', 'Details') def step(self): self.prerequisite_view.datastore.tree.click_path(*self.obj.tree_path) @navigator.register(Method) class Edit(CFMENavigateStep): VIEW = MethodEditView prerequisite = NavigateToSibling('Details') def step(self): self.prerequisite_view.configuration.item_select('Edit this Method') @navigator.register(Method) class Copy(CFMENavigateStep): VIEW = MethodCopyView prerequisite = NavigateToSibling('Details') def step(self): self.prerequisite_view.configuration.item_select('Copy this Method')
# -*- coding: utf-8 -*- import uuid import fauxfactory import pytest from copy import copy, deepcopy from cfme import test_requirements from cfme.base.credential import Credential from cfme.common.provider_views import (InfraProviderAddView, InfraProvidersView, InfraProvidersDiscoverView) from cfme.infrastructure.provider import discover, wait_for_a_provider, InfraProvider from cfme.infrastructure.provider.rhevm import RHEVMProvider, RHEVMEndpoint from cfme.infrastructure.provider.virtualcenter import VMwareProvider, VirtualCenterEndpoint from cfme.utils import error from cfme.utils.blockers import BZ from cfme.utils.update import update pytestmark = [ test_requirements.discovery, pytest.mark.tier(3), pytest.mark.provider([InfraProvider], scope="function"), ] @pytest.mark.sauce def test_empty_discovery_form_validation(appliance): """ Tests that the flash message is correct when discovery form is empty.""" discover(None) view = appliance.browser.create_view(InfraProvidersDiscoverView) view.flash.assert_message('At least 1 item must be selected for discovery') @pytest.mark.sauce def test_discovery_cancelled_validation(appliance): """ Tests that the flash message is correct when discovery is cancelled.""" discover(None, cancel=True) view = appliance.browser.create_view(InfraProvidersView) view.flash.assert_success_message('Infrastructure Providers ' 'Discovery was cancelled by the user') @pytest.mark.sauce def test_add_cancelled_validation(appliance): """Tests that the flash message is correct when add is cancelled.""" prov = VMwareProvider() prov.create(cancel=True) view = appliance.browser.create_view(InfraProvidersView) view.flash.assert_success_message('Add of Infrastructure Provider was cancelled by the user') @pytest.mark.sauce def test_type_required_validation(): """Test to validate type while adding a provider""" prov = InfraProvider() with pytest.raises(AssertionError): prov.create() view = prov.create_view(InfraProviderAddView) assert not view.add.active def test_name_required_validation(): """Tests to validate the name while adding a provider""" endpoint = VirtualCenterEndpoint(hostname=fauxfactory.gen_alphanumeric(5)) prov = VMwareProvider( name=None, endpoints=endpoint) with pytest.raises(AssertionError): prov.create() view = prov.create_view(InfraProviderAddView) assert view.name.help_block == "Required" assert not view.add.active def test_host_name_required_validation(): """Test to validate the hostname while adding a provider""" endpoint = VirtualCenterEndpoint(hostname=None) prov = VMwareProvider( name=fauxfactory.gen_alphanumeric(5), endpoints=endpoint) with pytest.raises(AssertionError): prov.create() view = prov.create_view(prov.endpoints_form) assert view.hostname.help_block == "Required" view = prov.create_view(InfraProviderAddView) assert not view.add.active def test_name_max_character_validation(request, infra_provider): """Test to validate max character for name field""" request.addfinalizer(lambda: infra_provider.delete_if_exists(cancel=False)) name = fauxfactory.gen_alphanumeric(255) with update(infra_provider): infra_provider.name = name assert infra_provider.exists def test_host_name_max_character_validation(): """Test to validate max character for host name field""" endpoint = VirtualCenterEndpoint(hostname=fauxfactory.gen_alphanumeric(256)) prov = VMwareProvider(name=fauxfactory.gen_alphanumeric(5), endpoints=endpoint) try: prov.create() except AssertionError: view = prov.create_view(prov.endpoints_form) assert view.hostname.value == prov.hostname[0:255] def test_api_port_max_character_validation(): """Test to validate max character for api port field""" endpoint = RHEVMEndpoint(hostname=fauxfactory.gen_alphanumeric(5), api_port=fauxfactory.gen_alphanumeric(16), verify_tls=None, ca_certs=None) prov = RHEVMProvider(name=fauxfactory.gen_alphanumeric(5), endpoints=endpoint) try: prov.create() except AssertionError: view = prov.create_view(prov.endpoints_form) text = view.default.api_port.value assert text == prov.default_endpoint.api_port[0:15] @pytest.mark.usefixtures('has_no_infra_providers') @pytest.mark.tier(1) def test_providers_discovery(request, provider): """Tests provider discovery Metadata: test_flag: crud """ provider.discover() view = provider.create_view(InfraProvidersView) view.flash.assert_success_message('Infrastructure Providers: Discovery successfully initiated') request.addfinalizer(InfraProvider.clear_providers) wait_for_a_provider() @pytest.mark.uncollectif(lambda provider: provider.type == 'rhevm', 'blocker=1399622') @pytest.mark.usefixtures('has_no_infra_providers') def test_provider_add_with_bad_credentials(provider): """Tests provider add with bad credentials Metadata: test_flag: crud """ provider.default_endpoint.credentials = Credential( principal='bad', secret='reallybad', verify_secret='reallybad' ) with error.expected(provider.bad_credentials_error_msg): provider.create(validate_credentials=True) @pytest.mark.usefixtures('has_no_infra_providers') @pytest.mark.tier(1) @pytest.mark.smoke @pytest.mark.meta(blockers=[BZ(1450527, unblock=lambda provider: provider.type != 'scvmm')]) def test_provider_crud(provider): """Tests provider add with good credentials Metadata: test_flag: crud """ provider.create() # Fails on upstream, all provider types - BZ1087476 provider.validate_stats(ui=True) old_name = provider.name with update(provider): provider.name = str(uuid.uuid4()) # random uuid with update(provider): provider.name = old_name # old name provider.delete(cancel=False) provider.wait_for_delete() @pytest.mark.usefixtures('has_no_infra_providers') @pytest.mark.tier(1) @pytest.mark.parametrize('verify_tls', [False, True], ids=['no_tls', 'tls']) @pytest.mark.uncollectif(lambda provider: not (provider.one_of(RHEVMProvider) and provider.endpoints.get('default').__dict__.get('verify_tls'))) def test_provider_rhv_create_delete_tls(request, provider, verify_tls): """Tests RHV provider creation with and without TLS encryption Metadata: test_flag: crud """ prov = copy(provider) request.addfinalizer(lambda: prov.delete_if_exists(cancel=False)) if not verify_tls: endpoints = deepcopy(prov.endpoints) endpoints['default'].verify_tls = False endpoints['default'].ca_certs = None prov.endpoints = endpoints prov.name = "{}-no-tls".format(provider.name) prov.create() prov.validate_stats(ui=True) prov.delete(cancel=False) prov.wait_for_delete()
jkandasa/integration_tests
cfme/tests/infrastructure/test_providers.py
cfme/automate/explorer/method.py
from wrapanapi.google import GoogleCloudSystem from widgetastic.widget import View from widgetastic_patternfly import Button, Input from cfme.base.credential import ServiceAccountCredential from cfme.common.provider import DefaultEndpoint from . import CloudProvider class GCEEndpoint(DefaultEndpoint): """ represents default GCE endpoint (Add/Edit dialogs) """ credential_class = ServiceAccountCredential @property def view_value_mapping(self): return {} class GCEEndpointForm(View): """ represents default GCE endpoint form in UI (Add/Edit dialogs) """ service_account = Input('service_account') validate = Button('Validate') class GCEProvider(CloudProvider): """ BaseProvider->CloudProvider->GCEProvider class. represents CFME provider and operations available in UI """ type_name = "gce" mgmt_class = GoogleCloudSystem db_types = ["Google::CloudManager"] endpoints_form = GCEEndpointForm def __init__(self, name=None, project=None, zone=None, region=None, region_name=None, endpoints=None, key=None, appliance=None): super(GCEProvider, self).__init__(name=name, zone=zone, key=key, endpoints=endpoints, appliance=appliance) self.region = region self.region_name = region_name self.project = project @property def view_value_mapping(self): return { 'name': self.name, 'prov_type': 'Google Compute Engine', 'region': self.region_name, 'project_id': self.project } @classmethod def from_config(cls, prov_config, prov_key, appliance=None): endpoint = GCEEndpoint(**prov_config['endpoints']['default']) return cls(name=prov_config['name'], project=prov_config['project'], zone=prov_config['zone'], region=prov_config['region'], region_name=prov_config['region_name'], endpoints={endpoint.name: endpoint}, key=prov_key, appliance=appliance) @classmethod def get_credentials(cls, credential_dict, cred_type=None): """Processes a credential dictionary into a credential object. Args: credential_dict: A credential dictionary. cred_type: Type of credential (None, token, ssh, amqp, ...) Returns: A :py:class:`cfme.base.credential.ServiceAccountCredential` instance. """ return ServiceAccountCredential.from_config(credential_dict)
# -*- coding: utf-8 -*- import uuid import fauxfactory import pytest from copy import copy, deepcopy from cfme import test_requirements from cfme.base.credential import Credential from cfme.common.provider_views import (InfraProviderAddView, InfraProvidersView, InfraProvidersDiscoverView) from cfme.infrastructure.provider import discover, wait_for_a_provider, InfraProvider from cfme.infrastructure.provider.rhevm import RHEVMProvider, RHEVMEndpoint from cfme.infrastructure.provider.virtualcenter import VMwareProvider, VirtualCenterEndpoint from cfme.utils import error from cfme.utils.blockers import BZ from cfme.utils.update import update pytestmark = [ test_requirements.discovery, pytest.mark.tier(3), pytest.mark.provider([InfraProvider], scope="function"), ] @pytest.mark.sauce def test_empty_discovery_form_validation(appliance): """ Tests that the flash message is correct when discovery form is empty.""" discover(None) view = appliance.browser.create_view(InfraProvidersDiscoverView) view.flash.assert_message('At least 1 item must be selected for discovery') @pytest.mark.sauce def test_discovery_cancelled_validation(appliance): """ Tests that the flash message is correct when discovery is cancelled.""" discover(None, cancel=True) view = appliance.browser.create_view(InfraProvidersView) view.flash.assert_success_message('Infrastructure Providers ' 'Discovery was cancelled by the user') @pytest.mark.sauce def test_add_cancelled_validation(appliance): """Tests that the flash message is correct when add is cancelled.""" prov = VMwareProvider() prov.create(cancel=True) view = appliance.browser.create_view(InfraProvidersView) view.flash.assert_success_message('Add of Infrastructure Provider was cancelled by the user') @pytest.mark.sauce def test_type_required_validation(): """Test to validate type while adding a provider""" prov = InfraProvider() with pytest.raises(AssertionError): prov.create() view = prov.create_view(InfraProviderAddView) assert not view.add.active def test_name_required_validation(): """Tests to validate the name while adding a provider""" endpoint = VirtualCenterEndpoint(hostname=fauxfactory.gen_alphanumeric(5)) prov = VMwareProvider( name=None, endpoints=endpoint) with pytest.raises(AssertionError): prov.create() view = prov.create_view(InfraProviderAddView) assert view.name.help_block == "Required" assert not view.add.active def test_host_name_required_validation(): """Test to validate the hostname while adding a provider""" endpoint = VirtualCenterEndpoint(hostname=None) prov = VMwareProvider( name=fauxfactory.gen_alphanumeric(5), endpoints=endpoint) with pytest.raises(AssertionError): prov.create() view = prov.create_view(prov.endpoints_form) assert view.hostname.help_block == "Required" view = prov.create_view(InfraProviderAddView) assert not view.add.active def test_name_max_character_validation(request, infra_provider): """Test to validate max character for name field""" request.addfinalizer(lambda: infra_provider.delete_if_exists(cancel=False)) name = fauxfactory.gen_alphanumeric(255) with update(infra_provider): infra_provider.name = name assert infra_provider.exists def test_host_name_max_character_validation(): """Test to validate max character for host name field""" endpoint = VirtualCenterEndpoint(hostname=fauxfactory.gen_alphanumeric(256)) prov = VMwareProvider(name=fauxfactory.gen_alphanumeric(5), endpoints=endpoint) try: prov.create() except AssertionError: view = prov.create_view(prov.endpoints_form) assert view.hostname.value == prov.hostname[0:255] def test_api_port_max_character_validation(): """Test to validate max character for api port field""" endpoint = RHEVMEndpoint(hostname=fauxfactory.gen_alphanumeric(5), api_port=fauxfactory.gen_alphanumeric(16), verify_tls=None, ca_certs=None) prov = RHEVMProvider(name=fauxfactory.gen_alphanumeric(5), endpoints=endpoint) try: prov.create() except AssertionError: view = prov.create_view(prov.endpoints_form) text = view.default.api_port.value assert text == prov.default_endpoint.api_port[0:15] @pytest.mark.usefixtures('has_no_infra_providers') @pytest.mark.tier(1) def test_providers_discovery(request, provider): """Tests provider discovery Metadata: test_flag: crud """ provider.discover() view = provider.create_view(InfraProvidersView) view.flash.assert_success_message('Infrastructure Providers: Discovery successfully initiated') request.addfinalizer(InfraProvider.clear_providers) wait_for_a_provider() @pytest.mark.uncollectif(lambda provider: provider.type == 'rhevm', 'blocker=1399622') @pytest.mark.usefixtures('has_no_infra_providers') def test_provider_add_with_bad_credentials(provider): """Tests provider add with bad credentials Metadata: test_flag: crud """ provider.default_endpoint.credentials = Credential( principal='bad', secret='reallybad', verify_secret='reallybad' ) with error.expected(provider.bad_credentials_error_msg): provider.create(validate_credentials=True) @pytest.mark.usefixtures('has_no_infra_providers') @pytest.mark.tier(1) @pytest.mark.smoke @pytest.mark.meta(blockers=[BZ(1450527, unblock=lambda provider: provider.type != 'scvmm')]) def test_provider_crud(provider): """Tests provider add with good credentials Metadata: test_flag: crud """ provider.create() # Fails on upstream, all provider types - BZ1087476 provider.validate_stats(ui=True) old_name = provider.name with update(provider): provider.name = str(uuid.uuid4()) # random uuid with update(provider): provider.name = old_name # old name provider.delete(cancel=False) provider.wait_for_delete() @pytest.mark.usefixtures('has_no_infra_providers') @pytest.mark.tier(1) @pytest.mark.parametrize('verify_tls', [False, True], ids=['no_tls', 'tls']) @pytest.mark.uncollectif(lambda provider: not (provider.one_of(RHEVMProvider) and provider.endpoints.get('default').__dict__.get('verify_tls'))) def test_provider_rhv_create_delete_tls(request, provider, verify_tls): """Tests RHV provider creation with and without TLS encryption Metadata: test_flag: crud """ prov = copy(provider) request.addfinalizer(lambda: prov.delete_if_exists(cancel=False)) if not verify_tls: endpoints = deepcopy(prov.endpoints) endpoints['default'].verify_tls = False endpoints['default'].ca_certs = None prov.endpoints = endpoints prov.name = "{}-no-tls".format(provider.name) prov.create() prov.validate_stats(ui=True) prov.delete(cancel=False) prov.wait_for_delete()
jkandasa/integration_tests
cfme/tests/infrastructure/test_providers.py
cfme/cloud/provider/gce.py
import pandas as pd from pandas.core.internals import ObjectBlock from .base import BaseExtensionTests class BaseCastingTests(BaseExtensionTests): """Casting to and from ExtensionDtypes""" def test_astype_object_series(self, all_data): ser = pd.Series({"A": all_data}) result = ser.astype(object) assert isinstance(result._data.blocks[0], ObjectBlock) def test_tolist(self, data): result = pd.Series(data).tolist() expected = list(data) assert result == expected def test_astype_str(self, data): result = pd.Series(data[:5]).astype(str) expected = pd.Series(data[:5].astype(str)) self.assert_series_equal(result, expected)
# -*- coding: utf-8 -*- import numpy as np import pandas as pd import pytest from pandas import Index, IntervalIndex, MultiIndex def test_is_monotonic_increasing(): i = MultiIndex.from_product([np.arange(10), np.arange(10)], names=['one', 'two']) assert i.is_monotonic assert i._is_strictly_monotonic_increasing assert Index(i.values).is_monotonic assert i._is_strictly_monotonic_increasing i = MultiIndex.from_product([np.arange(10, 0, -1), np.arange(10)], names=['one', 'two']) assert not i.is_monotonic assert not i._is_strictly_monotonic_increasing assert not Index(i.values).is_monotonic assert not Index(i.values)._is_strictly_monotonic_increasing i = MultiIndex.from_product([np.arange(10), np.arange(10, 0, -1)], names=['one', 'two']) assert not i.is_monotonic assert not i._is_strictly_monotonic_increasing assert not Index(i.values).is_monotonic assert not Index(i.values)._is_strictly_monotonic_increasing i = MultiIndex.from_product([[1.0, np.nan, 2.0], ['a', 'b', 'c']]) assert not i.is_monotonic assert not i._is_strictly_monotonic_increasing assert not Index(i.values).is_monotonic assert not Index(i.values)._is_strictly_monotonic_increasing # string ordering i = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'], ['one', 'two', 'three']], labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=['first', 'second']) assert not i.is_monotonic assert not Index(i.values).is_monotonic assert not i._is_strictly_monotonic_increasing assert not Index(i.values)._is_strictly_monotonic_increasing i = MultiIndex(levels=[['bar', 'baz', 'foo', 'qux'], ['mom', 'next', 'zenith']], labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=['first', 'second']) assert i.is_monotonic assert Index(i.values).is_monotonic assert i._is_strictly_monotonic_increasing assert Index(i.values)._is_strictly_monotonic_increasing # mixed levels, hits the TypeError i = MultiIndex( levels=[[1, 2, 3, 4], ['gb00b03mlx29', 'lu0197800237', 'nl0000289783', 'nl0000289965', 'nl0000301109']], labels=[[0, 1, 1, 2, 2, 2, 3], [4, 2, 0, 0, 1, 3, -1]], names=['household_id', 'asset_id']) assert not i.is_monotonic assert not i._is_strictly_monotonic_increasing # empty i = MultiIndex.from_arrays([[], []]) assert i.is_monotonic assert Index(i.values).is_monotonic assert i._is_strictly_monotonic_increasing assert Index(i.values)._is_strictly_monotonic_increasing def test_is_monotonic_decreasing(): i = MultiIndex.from_product([np.arange(9, -1, -1), np.arange(9, -1, -1)], names=['one', 'two']) assert i.is_monotonic_decreasing assert i._is_strictly_monotonic_decreasing assert Index(i.values).is_monotonic_decreasing assert i._is_strictly_monotonic_decreasing i = MultiIndex.from_product([np.arange(10), np.arange(10, 0, -1)], names=['one', 'two']) assert not i.is_monotonic_decreasing assert not i._is_strictly_monotonic_decreasing assert not Index(i.values).is_monotonic_decreasing assert not Index(i.values)._is_strictly_monotonic_decreasing i = MultiIndex.from_product([np.arange(10, 0, -1), np.arange(10)], names=['one', 'two']) assert not i.is_monotonic_decreasing assert not i._is_strictly_monotonic_decreasing assert not Index(i.values).is_monotonic_decreasing assert not Index(i.values)._is_strictly_monotonic_decreasing i = MultiIndex.from_product([[2.0, np.nan, 1.0], ['c', 'b', 'a']]) assert not i.is_monotonic_decreasing assert not i._is_strictly_monotonic_decreasing assert not Index(i.values).is_monotonic_decreasing assert not Index(i.values)._is_strictly_monotonic_decreasing # string ordering i = MultiIndex(levels=[['qux', 'foo', 'baz', 'bar'], ['three', 'two', 'one']], labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=['first', 'second']) assert not i.is_monotonic_decreasing assert not Index(i.values).is_monotonic_decreasing assert not i._is_strictly_monotonic_decreasing assert not Index(i.values)._is_strictly_monotonic_decreasing i = MultiIndex(levels=[['qux', 'foo', 'baz', 'bar'], ['zenith', 'next', 'mom']], labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=['first', 'second']) assert i.is_monotonic_decreasing assert Index(i.values).is_monotonic_decreasing assert i._is_strictly_monotonic_decreasing assert Index(i.values)._is_strictly_monotonic_decreasing # mixed levels, hits the TypeError i = MultiIndex( levels=[[4, 3, 2, 1], ['nl0000301109', 'nl0000289965', 'nl0000289783', 'lu0197800237', 'gb00b03mlx29']], labels=[[0, 1, 1, 2, 2, 2, 3], [4, 2, 0, 0, 1, 3, -1]], names=['household_id', 'asset_id']) assert not i.is_monotonic_decreasing assert not i._is_strictly_monotonic_decreasing # empty i = MultiIndex.from_arrays([[], []]) assert i.is_monotonic_decreasing assert Index(i.values).is_monotonic_decreasing assert i._is_strictly_monotonic_decreasing assert Index(i.values)._is_strictly_monotonic_decreasing def test_is_strictly_monotonic_increasing(): idx = pd.MultiIndex(levels=[['bar', 'baz'], ['mom', 'next']], labels=[[0, 0, 1, 1], [0, 0, 0, 1]]) assert idx.is_monotonic_increasing assert not idx._is_strictly_monotonic_increasing def test_is_strictly_monotonic_decreasing(): idx = pd.MultiIndex(levels=[['baz', 'bar'], ['next', 'mom']], labels=[[0, 0, 1, 1], [0, 0, 0, 1]]) assert idx.is_monotonic_decreasing assert not idx._is_strictly_monotonic_decreasing def test_searchsorted_monotonic(indices): # GH17271 # not implemented for tuple searches in MultiIndex # or Intervals searches in IntervalIndex if isinstance(indices, (MultiIndex, IntervalIndex)): return # nothing to test if the index is empty if indices.empty: return value = indices[0] # determine the expected results (handle dupes for 'right') expected_left, expected_right = 0, (indices == value).argmin() if expected_right == 0: # all values are the same, expected_right should be length expected_right = len(indices) # test _searchsorted_monotonic in all cases # test searchsorted only for increasing if indices.is_monotonic_increasing: ssm_left = indices._searchsorted_monotonic(value, side='left') assert expected_left == ssm_left ssm_right = indices._searchsorted_monotonic(value, side='right') assert expected_right == ssm_right ss_left = indices.searchsorted(value, side='left') assert expected_left == ss_left ss_right = indices.searchsorted(value, side='right') assert expected_right == ss_right elif indices.is_monotonic_decreasing: ssm_left = indices._searchsorted_monotonic(value, side='left') assert expected_left == ssm_left ssm_right = indices._searchsorted_monotonic(value, side='right') assert expected_right == ssm_right else: # non-monotonic should raise. with pytest.raises(ValueError): indices._searchsorted_monotonic(value, side='left')
pratapvardhan/pandas
pandas/tests/indexes/multi/test_monotonic.py
pandas/tests/extension/base/casting.py
# -*- coding: utf-8 -*- import numpy as np import pytest from pandas import Index, MultiIndex @pytest.fixture def idx(): # a MultiIndex used to test the general functionality of the # general functionality of this object major_axis = Index(['foo', 'bar', 'baz', 'qux']) minor_axis = Index(['one', 'two']) major_labels = np.array([0, 0, 1, 2, 3, 3]) minor_labels = np.array([0, 1, 0, 1, 0, 1]) index_names = ['first', 'second'] index = MultiIndex( levels=[major_axis, minor_axis], labels=[major_labels, minor_labels], names=index_names, verify_integrity=False ) return index @pytest.fixture def index_names(): # names that match those in the idx fixture for testing equality of # names assigned to the idx return ['first', 'second'] @pytest.fixture def holder(): # the MultiIndex constructor used to base compatibility with pickle return MultiIndex @pytest.fixture def compat_props(): # a MultiIndex must have these properties associated with it return ['shape', 'ndim', 'size']
# -*- coding: utf-8 -*- import numpy as np import pandas as pd import pytest from pandas import Index, IntervalIndex, MultiIndex def test_is_monotonic_increasing(): i = MultiIndex.from_product([np.arange(10), np.arange(10)], names=['one', 'two']) assert i.is_monotonic assert i._is_strictly_monotonic_increasing assert Index(i.values).is_monotonic assert i._is_strictly_monotonic_increasing i = MultiIndex.from_product([np.arange(10, 0, -1), np.arange(10)], names=['one', 'two']) assert not i.is_monotonic assert not i._is_strictly_monotonic_increasing assert not Index(i.values).is_monotonic assert not Index(i.values)._is_strictly_monotonic_increasing i = MultiIndex.from_product([np.arange(10), np.arange(10, 0, -1)], names=['one', 'two']) assert not i.is_monotonic assert not i._is_strictly_monotonic_increasing assert not Index(i.values).is_monotonic assert not Index(i.values)._is_strictly_monotonic_increasing i = MultiIndex.from_product([[1.0, np.nan, 2.0], ['a', 'b', 'c']]) assert not i.is_monotonic assert not i._is_strictly_monotonic_increasing assert not Index(i.values).is_monotonic assert not Index(i.values)._is_strictly_monotonic_increasing # string ordering i = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux'], ['one', 'two', 'three']], labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=['first', 'second']) assert not i.is_monotonic assert not Index(i.values).is_monotonic assert not i._is_strictly_monotonic_increasing assert not Index(i.values)._is_strictly_monotonic_increasing i = MultiIndex(levels=[['bar', 'baz', 'foo', 'qux'], ['mom', 'next', 'zenith']], labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=['first', 'second']) assert i.is_monotonic assert Index(i.values).is_monotonic assert i._is_strictly_monotonic_increasing assert Index(i.values)._is_strictly_monotonic_increasing # mixed levels, hits the TypeError i = MultiIndex( levels=[[1, 2, 3, 4], ['gb00b03mlx29', 'lu0197800237', 'nl0000289783', 'nl0000289965', 'nl0000301109']], labels=[[0, 1, 1, 2, 2, 2, 3], [4, 2, 0, 0, 1, 3, -1]], names=['household_id', 'asset_id']) assert not i.is_monotonic assert not i._is_strictly_monotonic_increasing # empty i = MultiIndex.from_arrays([[], []]) assert i.is_monotonic assert Index(i.values).is_monotonic assert i._is_strictly_monotonic_increasing assert Index(i.values)._is_strictly_monotonic_increasing def test_is_monotonic_decreasing(): i = MultiIndex.from_product([np.arange(9, -1, -1), np.arange(9, -1, -1)], names=['one', 'two']) assert i.is_monotonic_decreasing assert i._is_strictly_monotonic_decreasing assert Index(i.values).is_monotonic_decreasing assert i._is_strictly_monotonic_decreasing i = MultiIndex.from_product([np.arange(10), np.arange(10, 0, -1)], names=['one', 'two']) assert not i.is_monotonic_decreasing assert not i._is_strictly_monotonic_decreasing assert not Index(i.values).is_monotonic_decreasing assert not Index(i.values)._is_strictly_monotonic_decreasing i = MultiIndex.from_product([np.arange(10, 0, -1), np.arange(10)], names=['one', 'two']) assert not i.is_monotonic_decreasing assert not i._is_strictly_monotonic_decreasing assert not Index(i.values).is_monotonic_decreasing assert not Index(i.values)._is_strictly_monotonic_decreasing i = MultiIndex.from_product([[2.0, np.nan, 1.0], ['c', 'b', 'a']]) assert not i.is_monotonic_decreasing assert not i._is_strictly_monotonic_decreasing assert not Index(i.values).is_monotonic_decreasing assert not Index(i.values)._is_strictly_monotonic_decreasing # string ordering i = MultiIndex(levels=[['qux', 'foo', 'baz', 'bar'], ['three', 'two', 'one']], labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=['first', 'second']) assert not i.is_monotonic_decreasing assert not Index(i.values).is_monotonic_decreasing assert not i._is_strictly_monotonic_decreasing assert not Index(i.values)._is_strictly_monotonic_decreasing i = MultiIndex(levels=[['qux', 'foo', 'baz', 'bar'], ['zenith', 'next', 'mom']], labels=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], names=['first', 'second']) assert i.is_monotonic_decreasing assert Index(i.values).is_monotonic_decreasing assert i._is_strictly_monotonic_decreasing assert Index(i.values)._is_strictly_monotonic_decreasing # mixed levels, hits the TypeError i = MultiIndex( levels=[[4, 3, 2, 1], ['nl0000301109', 'nl0000289965', 'nl0000289783', 'lu0197800237', 'gb00b03mlx29']], labels=[[0, 1, 1, 2, 2, 2, 3], [4, 2, 0, 0, 1, 3, -1]], names=['household_id', 'asset_id']) assert not i.is_monotonic_decreasing assert not i._is_strictly_monotonic_decreasing # empty i = MultiIndex.from_arrays([[], []]) assert i.is_monotonic_decreasing assert Index(i.values).is_monotonic_decreasing assert i._is_strictly_monotonic_decreasing assert Index(i.values)._is_strictly_monotonic_decreasing def test_is_strictly_monotonic_increasing(): idx = pd.MultiIndex(levels=[['bar', 'baz'], ['mom', 'next']], labels=[[0, 0, 1, 1], [0, 0, 0, 1]]) assert idx.is_monotonic_increasing assert not idx._is_strictly_monotonic_increasing def test_is_strictly_monotonic_decreasing(): idx = pd.MultiIndex(levels=[['baz', 'bar'], ['next', 'mom']], labels=[[0, 0, 1, 1], [0, 0, 0, 1]]) assert idx.is_monotonic_decreasing assert not idx._is_strictly_monotonic_decreasing def test_searchsorted_monotonic(indices): # GH17271 # not implemented for tuple searches in MultiIndex # or Intervals searches in IntervalIndex if isinstance(indices, (MultiIndex, IntervalIndex)): return # nothing to test if the index is empty if indices.empty: return value = indices[0] # determine the expected results (handle dupes for 'right') expected_left, expected_right = 0, (indices == value).argmin() if expected_right == 0: # all values are the same, expected_right should be length expected_right = len(indices) # test _searchsorted_monotonic in all cases # test searchsorted only for increasing if indices.is_monotonic_increasing: ssm_left = indices._searchsorted_monotonic(value, side='left') assert expected_left == ssm_left ssm_right = indices._searchsorted_monotonic(value, side='right') assert expected_right == ssm_right ss_left = indices.searchsorted(value, side='left') assert expected_left == ss_left ss_right = indices.searchsorted(value, side='right') assert expected_right == ss_right elif indices.is_monotonic_decreasing: ssm_left = indices._searchsorted_monotonic(value, side='left') assert expected_left == ssm_left ssm_right = indices._searchsorted_monotonic(value, side='right') assert expected_right == ssm_right else: # non-monotonic should raise. with pytest.raises(ValueError): indices._searchsorted_monotonic(value, side='left')
pratapvardhan/pandas
pandas/tests/indexes/multi/test_monotonic.py
pandas/tests/indexes/multi/conftest.py
import json import os from typing import Dict, List, Optional, Union import requests CONTENT_TYPE_HEADER = {"Content-Type": "application/json"} DEFAULT_API_CONF = { "ANCHORE_API_USER": "admin", "ANCHORE_API_PASS": "foobar", "ANCHORE_BASE_URL": "http://localhost:8228/v1", "ANCHORE_API_ACCOUNT": "admin", } def get_api_conf(): api_conf = DEFAULT_API_CONF for key in DEFAULT_API_CONF.keys(): env_value = os.environ.get(key) if env_value: api_conf[key] = env_value return api_conf class APIResponse(object): def __init__(self, status_code, response=None): self.code = status_code if response is not None: self.url = response.url try: self.body = response.json() except json.decoder.JSONDecodeError: self.body = response.content except ValueError: self.body = response.text or "" def __eq__(self, other): return isinstance(other, APIResponse) and self.code == other.code def __str__(self): api_resp_str = "APIResponse(code={}".format(self.code) if hasattr(self, "url") and self.url: api_resp_str += ", url={}".format(self.url) if hasattr(self, "body") and self.body: api_resp_str += ", body={}".format(self.body) api_resp_str += ")" return api_resp_str def __repr__(self): return str(self) class RequestFailedError(Exception): def __init__(self, url, status_code, body): self.url = url self.status_code = status_code self.body = body def __str__(self): return "Request to {} failed with Status Code {} and Body {}".format( self.url, self.status_code, self.body ) class InsufficientRequestDetailsError(Exception): def __init__(self, missing_field_names): self.missing_field_names = missing_field_names def __str__(self): return "Insufficient Request Details given, cannot make request: {}".format( ", ".join(self.missing_field_names) ) def build_url(path_parts, config): if path_parts: path_parts = os.path.join(*path_parts) return os.path.join(config["ANCHORE_BASE_URL"], path_parts) return config["ANCHORE_BASE_URL"] def get_headers(config, content_type_override=None): headers = content_type_override or CONTENT_TYPE_HEADER headers["x-anchore-account"] = config["ANCHORE_API_ACCOUNT"] return headers def http_post(path_parts, payload, query=None, config: callable = get_api_conf): api_conf = config() if path_parts is None: raise InsufficientRequestDetailsError(["path_parts"]) resp = requests.post( build_url(path_parts, api_conf), data=json.dumps(payload), auth=(api_conf["ANCHORE_API_USER"], api_conf["ANCHORE_API_PASS"]), headers=get_headers(api_conf), params=query, ) return APIResponse(resp.status_code, response=resp) def http_post_bytes( path_parts: List[str], payload: bytes, query: Optional[Union[Dict, List, bytes]] = None, config: callable = get_api_conf, ) -> APIResponse: """ Send HTTP POST request with byte payload. http_utils.http_post does not support this. :param path_parts: list of URI path parts :type path_parts: List[str] :param payload: byte array payload :type payload: bytes :param query: Dictionary, list of tuples or bytes to send in the query string, defaults to None :type query: Optional[Union[Dict, List, bytes]], optional :param config: [description], defaults to get_api_conf :type config: callable, optional :raises InsufficientRequestDetailsError: if path_parts is empty :return: api response :rtype: APIResponse """ api_conf = config() if path_parts is None: raise InsufficientRequestDetailsError(["path_parts"]) resp = requests.post( build_url(path_parts, api_conf), data=payload, auth=(api_conf["ANCHORE_API_USER"], api_conf["ANCHORE_API_PASS"]), headers=get_headers(api_conf), params=query, ) return APIResponse(resp.status_code, response=resp) def http_get( path_parts, query=None, config: callable = get_api_conf, extra_headers=None, ): api_conf = config() if path_parts is None: raise InsufficientRequestDetailsError(["path_parts"]) resp = requests.get( build_url(path_parts, api_conf), auth=(api_conf["ANCHORE_API_USER"], api_conf["ANCHORE_API_PASS"]), headers=get_headers(api_conf, extra_headers), params=query, ) return APIResponse(resp.status_code, response=resp) def http_del(path_parts, query=None, config: callable = get_api_conf): api_conf = config() if path_parts is None: raise InsufficientRequestDetailsError(["path_parts"]) resp = requests.delete( build_url(path_parts, api_conf), auth=(api_conf["ANCHORE_API_USER"], api_conf["ANCHORE_API_PASS"]), headers=get_headers(api_conf), params=query, ) return APIResponse(resp.status_code, resp) def http_put(path_parts, payload, query=None, config: callable = get_api_conf): api_conf = config() if path_parts is None: raise InsufficientRequestDetailsError(["path_parts"]) resp = requests.put( build_url(path_parts, api_conf), data=json.dumps(payload), auth=(api_conf["ANCHORE_API_USER"], api_conf["ANCHORE_API_PASS"]), headers=get_headers(api_conf), params=query, ) return APIResponse(resp.status_code, response=resp) def http_post_url_encoded( path_parts, payload=None, query=None, config: callable = get_api_conf ): api_conf = config() if path_parts is None: raise InsufficientRequestDetailsError(["path_parts"]) resp = requests.post( build_url(path_parts, api_conf), data=payload, auth=(api_conf["ANCHORE_API_USER"], api_conf["ANCHORE_API_PASS"]), headers=get_headers( api_conf, {"Content-Type": "application/x-www-form-urlencoded"} ), params=query, ) return APIResponse(resp.status_code, response=resp)
import json import pytest import tests.functional.services.policy_engine.utils.api as policy_engine_api from tests.functional.services.utils import http_utils @pytest.mark.parametrize( "image_digest", [ "sha256:80a31c3ce2e99c3691c27ac3b1753163214494e9b2ca07bfdccf29a5cca2bfbe", # alpine-test "sha256:406413437f26223183d133ccc7186f24c827729e1b21adc7330dd43fcdc030b3", # debian-test "sha256:fe3ca35038008b0eac0fa4e686bd072c9430000ab7d7853001bde5f5b8ccf60c", # centos-test ], ) class TestVulnerabilityScanner: def test_image_load_schema(self, image_digest, ingress_image, schema_validator): # ingress image and check that response is 200 image_load_resp: http_utils.APIResponse = ingress_image(image_digest) assert image_load_resp == http_utils.APIResponse(200) # check that response schema matches expected format ingress_schema_validator = schema_validator("ingress_image.schema.json") is_valid: bool = ingress_schema_validator.is_valid(image_load_resp.body) assert is_valid, "\n".join( [str(e) for e in ingress_schema_validator.iter_errors(image_load_resp.body)] ) # check that there are no errors in response assert len(image_load_resp.body["problems"]) == 0, image_load_resp.body[ "problems" ] def test_get_vulnerabilities_schema( self, image_digest, image_digest_id_map, ingress_image, schema_validator ): # ingress image ingress_image(image_digest) # now that image is ingressed, can query vulnerabilities and assert response is 200 image_id = image_digest_id_map[image_digest] images_vuln_resp: http_utils.APIResponse = ( policy_engine_api.users.get_image_vulnerabilities(image_id) ) assert images_vuln_resp == http_utils.APIResponse(200) # check that response schema matches expected format vulnerability_schema_validator = schema_validator( "vulnerability_report.schema.json" ) is_valid: bool = vulnerability_schema_validator.is_valid(images_vuln_resp.body) assert is_valid, "\n".join( [ str(e) for e in vulnerability_schema_validator.iter_errors( images_vuln_resp.body ) ] ) def test_image_load_content(self, image_digest, ingress_image, expected_content): # ingress image and check that response is 200 image_load_resp: http_utils.APIResponse = ingress_image(image_digest) assert image_load_resp == http_utils.APIResponse(200) # check that there are no errors in response assert len(image_load_resp.body["problems"]) == 0, image_load_resp.body[ "problems" ] assert image_load_resp.body["status"] == "loaded" def test_get_vulnerabilities_content( self, image_digest, image_digest_id_map, ingress_image, expected_content, is_legacy_test, ): # ingress the image and get the image id ingress_image(image_digest) image_id = image_digest_id_map[image_digest] # get the vulnerabilities for the image images_vuln_resp: http_utils.APIResponse = ( policy_engine_api.users.get_image_vulnerabilities(image_id) ) assert images_vuln_resp == http_utils.APIResponse(200) actual_report = images_vuln_resp.body # load the expected results which is just a list of vulnerability matches folder = "legacy" if is_legacy_test else "grype" expected_results = expected_content(f"{folder}/{image_digest}") # impose some order expected_results.sort( key=lambda x: ( x["vulnerability"]["vulnerability_id"], x["vulnerability"]["feed_group"], x["artifact"]["name"], x["artifact"]["location"], ) ) # compare only the vulnerability matches actual_results = actual_report["results"] # impose same order actual_results.sort( key=lambda x: ( x["vulnerability"]["vulnerability_id"], x["vulnerability"]["feed_group"], x["artifact"]["name"], x["artifact"]["location"], ) ) # check number of results assert len(expected_results) == len(actual_results) # check the actual content for index in range(len(expected_results)): # compare only the vulnerability and artifacts, skip match as it contains a dynamic date assert ( expected_results[index]["vulnerability"] == actual_results[index]["vulnerability"] ) # sort cpe array before asserting expected_results[index]["artifact"]["cpes"].sort() actual_results[index]["artifact"]["cpes"].sort() assert ( expected_results[index]["artifact"] == actual_results[index]["artifact"] )
anchore/anchore-engine
tests/functional/services/policy_engine/vulnerability_data_tests/test_vulnerability_scanner.py
tests/functional/services/utils/http_utils.py
"""Support for Volvo On Call.""" from datetime import timedelta import logging import voluptuous as vol from volvooncall import Connection from homeassistant.const import ( CONF_NAME, CONF_PASSWORD, CONF_REGION, CONF_RESOURCES, CONF_SCAN_INTERVAL, CONF_USERNAME, ) from homeassistant.helpers import discovery from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import ( async_dispatcher_connect, async_dispatcher_send, ) from homeassistant.helpers.entity import Entity from homeassistant.helpers.event import async_track_point_in_utc_time from homeassistant.util.dt import utcnow DOMAIN = "volvooncall" DATA_KEY = DOMAIN _LOGGER = logging.getLogger(__name__) MIN_UPDATE_INTERVAL = timedelta(minutes=1) DEFAULT_UPDATE_INTERVAL = timedelta(minutes=1) CONF_SERVICE_URL = "service_url" CONF_SCANDINAVIAN_MILES = "scandinavian_miles" CONF_MUTABLE = "mutable" SIGNAL_STATE_UPDATED = f"{DOMAIN}.updated" PLATFORMS = { "sensor": "sensor", "binary_sensor": "binary_sensor", "lock": "lock", "device_tracker": "device_tracker", "switch": "switch", } RESOURCES = [ "position", "lock", "heater", "odometer", "trip_meter1", "trip_meter2", "average_speed", "fuel_amount", "fuel_amount_level", "average_fuel_consumption", "distance_to_empty", "washer_fluid_level", "brake_fluid", "service_warning_status", "bulb_failures", "battery_range", "battery_level", "time_to_fully_charged", "battery_charge_status", "engine_start", "last_trip", "is_engine_running", "doors_hood_open", "doors_tailgate_open", "doors_front_left_door_open", "doors_front_right_door_open", "doors_rear_left_door_open", "doors_rear_right_door_open", "windows_front_left_window_open", "windows_front_right_window_open", "windows_rear_left_window_open", "windows_rear_right_window_open", "tyre_pressure_front_left_tyre_pressure", "tyre_pressure_front_right_tyre_pressure", "tyre_pressure_rear_left_tyre_pressure", "tyre_pressure_rear_right_tyre_pressure", "any_door_open", "any_window_open", ] CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional( CONF_SCAN_INTERVAL, default=DEFAULT_UPDATE_INTERVAL ): vol.All(cv.time_period, vol.Clamp(min=MIN_UPDATE_INTERVAL)), vol.Optional(CONF_NAME, default={}): cv.schema_with_slug_keys( cv.string ), vol.Optional(CONF_RESOURCES): vol.All( cv.ensure_list, [vol.In(RESOURCES)] ), vol.Optional(CONF_REGION): cv.string, vol.Optional(CONF_SERVICE_URL): cv.string, vol.Optional(CONF_MUTABLE, default=True): cv.boolean, vol.Optional(CONF_SCANDINAVIAN_MILES, default=False): cv.boolean, } ) }, extra=vol.ALLOW_EXTRA, ) async def async_setup(hass, config): """Set up the Volvo On Call component.""" session = async_get_clientsession(hass) connection = Connection( session=session, username=config[DOMAIN].get(CONF_USERNAME), password=config[DOMAIN].get(CONF_PASSWORD), service_url=config[DOMAIN].get(CONF_SERVICE_URL), region=config[DOMAIN].get(CONF_REGION), ) interval = config[DOMAIN][CONF_SCAN_INTERVAL] data = hass.data[DATA_KEY] = VolvoData(config) def is_enabled(attr): """Return true if the user has enabled the resource.""" return attr in config[DOMAIN].get(CONF_RESOURCES, [attr]) def discover_vehicle(vehicle): """Load relevant platforms.""" data.vehicles.add(vehicle.vin) dashboard = vehicle.dashboard( mutable=config[DOMAIN][CONF_MUTABLE], scandinavian_miles=config[DOMAIN][CONF_SCANDINAVIAN_MILES], ) for instrument in ( instrument for instrument in dashboard.instruments if instrument.component in PLATFORMS and is_enabled(instrument.slug_attr) ): data.instruments.add(instrument) hass.async_create_task( discovery.async_load_platform( hass, PLATFORMS[instrument.component], DOMAIN, (vehicle.vin, instrument.component, instrument.attr), config, ) ) async def update(now): """Update status from the online service.""" try: if not await connection.update(journal=True): _LOGGER.warning("Could not query server") return False for vehicle in connection.vehicles: if vehicle.vin not in data.vehicles: discover_vehicle(vehicle) async_dispatcher_send(hass, SIGNAL_STATE_UPDATED) return True finally: async_track_point_in_utc_time(hass, update, utcnow() + interval) _LOGGER.info("Logging in to service") return await update(utcnow()) class VolvoData: """Hold component state.""" def __init__(self, config): """Initialize the component state.""" self.vehicles = set() self.instruments = set() self.config = config[DOMAIN] self.names = self.config.get(CONF_NAME) def instrument(self, vin, component, attr): """Return corresponding instrument.""" return next( ( instrument for instrument in self.instruments if instrument.vehicle.vin == vin and instrument.component == component and instrument.attr == attr ), None, ) def vehicle_name(self, vehicle): """Provide a friendly name for a vehicle.""" if ( vehicle.registration_number and vehicle.registration_number.lower() ) in self.names: return self.names[vehicle.registration_number.lower()] if vehicle.vin and vehicle.vin.lower() in self.names: return self.names[vehicle.vin.lower()] if vehicle.registration_number: return vehicle.registration_number if vehicle.vin: return vehicle.vin return "" class VolvoEntity(Entity): """Base class for all VOC entities.""" def __init__(self, data, vin, component, attribute): """Initialize the entity.""" self.data = data self.vin = vin self.component = component self.attribute = attribute async def async_added_to_hass(self): """Register update dispatcher.""" self.async_on_remove( async_dispatcher_connect( self.hass, SIGNAL_STATE_UPDATED, self.async_write_ha_state ) ) @property def instrument(self): """Return corresponding instrument.""" return self.data.instrument(self.vin, self.component, self.attribute) @property def icon(self): """Return the icon.""" return self.instrument.icon @property def vehicle(self): """Return vehicle.""" return self.instrument.vehicle @property def _entity_name(self): return self.instrument.name @property def _vehicle_name(self): return self.data.vehicle_name(self.vehicle) @property def name(self): """Return full name of the entity.""" return f"{self._vehicle_name} {self._entity_name}" @property def should_poll(self): """Return the polling state.""" return False @property def assumed_state(self): """Return true if unable to access real state of entity.""" return True @property def extra_state_attributes(self): """Return device specific state attributes.""" return dict( self.instrument.attributes, model=f"{self.vehicle.vehicle_type}/{self.vehicle.model_year}", ) @property def unique_id(self) -> str: """Return a unique ID.""" return f"{self.vin}-{self.component}-{self.attribute}"
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/volvooncall/__init__.py
"""Support for Verisure Smartplugs.""" from __future__ import annotations from time import monotonic from homeassistant.components.switch import SwitchEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import CONF_GIID, DOMAIN from .coordinator import VerisureDataUpdateCoordinator async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up Verisure alarm control panel from a config entry.""" coordinator: VerisureDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id] async_add_entities( VerisureSmartplug(coordinator, serial_number) for serial_number in coordinator.data["smart_plugs"] ) class VerisureSmartplug(CoordinatorEntity, SwitchEntity): """Representation of a Verisure smartplug.""" coordinator: VerisureDataUpdateCoordinator def __init__( self, coordinator: VerisureDataUpdateCoordinator, serial_number: str ) -> None: """Initialize the Verisure device.""" super().__init__(coordinator) self._attr_name = coordinator.data["smart_plugs"][serial_number]["area"] self._attr_unique_id = serial_number self.serial_number = serial_number self._change_timestamp = 0 self._state = False @property def device_info(self) -> DeviceInfo: """Return device information about this entity.""" area = self.coordinator.data["smart_plugs"][self.serial_number]["area"] return { "name": area, "suggested_area": area, "manufacturer": "Verisure", "model": "SmartPlug", "identifiers": {(DOMAIN, self.serial_number)}, "via_device": (DOMAIN, self.coordinator.entry.data[CONF_GIID]), } @property def is_on(self) -> bool: """Return true if on.""" if monotonic() - self._change_timestamp < 10: return self._state self._state = ( self.coordinator.data["smart_plugs"][self.serial_number]["currentState"] == "ON" ) return self._state @property def available(self) -> bool: """Return True if entity is available.""" return ( super().available and self.serial_number in self.coordinator.data["smart_plugs"] ) def turn_on(self, **kwargs) -> None: """Set smartplug status on.""" self.coordinator.verisure.set_smartplug_state(self.serial_number, True) self._state = True self._change_timestamp = monotonic() self.schedule_update_ha_state() def turn_off(self, **kwargs) -> None: """Set smartplug status off.""" self.coordinator.verisure.set_smartplug_state(self.serial_number, False) self._state = False self._change_timestamp = monotonic() self.schedule_update_ha_state()
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/verisure/switch.py
"""Support for WaterHeater devices of (EMEA/EU) Honeywell TCC systems.""" from __future__ import annotations import logging from homeassistant.components.water_heater import ( SUPPORT_AWAY_MODE, SUPPORT_OPERATION_MODE, WaterHeaterEntity, ) from homeassistant.const import PRECISION_TENTHS, PRECISION_WHOLE, STATE_OFF, STATE_ON from homeassistant.core import HomeAssistant from homeassistant.helpers.typing import ConfigType import homeassistant.util.dt as dt_util from . import EvoChild from .const import DOMAIN, EVO_FOLLOW, EVO_PERMOVER _LOGGER = logging.getLogger(__name__) STATE_AUTO = "auto" HA_STATE_TO_EVO = {STATE_AUTO: "", STATE_ON: "On", STATE_OFF: "Off"} EVO_STATE_TO_HA = {v: k for k, v in HA_STATE_TO_EVO.items() if k != ""} STATE_ATTRS_DHW = ["dhwId", "activeFaults", "stateStatus", "temperatureStatus"] async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities, discovery_info=None ) -> None: """Create a DHW controller.""" if discovery_info is None: return broker = hass.data[DOMAIN]["broker"] _LOGGER.debug( "Adding: DhwController (%s), id=%s", broker.tcs.hotwater.zone_type, broker.tcs.hotwater.zoneId, ) new_entity = EvoDHW(broker, broker.tcs.hotwater) async_add_entities([new_entity], update_before_add=True) class EvoDHW(EvoChild, WaterHeaterEntity): """Base for a Honeywell TCC DHW controller (aka boiler).""" def __init__(self, evo_broker, evo_device) -> None: """Initialize an evohome DHW controller.""" super().__init__(evo_broker, evo_device) self._unique_id = evo_device.dhwId self._name = "DHW controller" self._icon = "mdi:thermometer-lines" self._precision = PRECISION_TENTHS if evo_broker.client_v1 else PRECISION_WHOLE self._supported_features = SUPPORT_AWAY_MODE | SUPPORT_OPERATION_MODE @property def state(self): """Return the current state.""" return EVO_STATE_TO_HA[self._evo_device.stateStatus["state"]] @property def current_operation(self) -> str: """Return the current operating mode (Auto, On, or Off).""" if self._evo_device.stateStatus["mode"] == EVO_FOLLOW: return STATE_AUTO return EVO_STATE_TO_HA[self._evo_device.stateStatus["state"]] @property def operation_list(self) -> list[str]: """Return the list of available operations.""" return list(HA_STATE_TO_EVO) @property def is_away_mode_on(self): """Return True if away mode is on.""" is_off = EVO_STATE_TO_HA[self._evo_device.stateStatus["state"]] == STATE_OFF is_permanent = self._evo_device.stateStatus["mode"] == EVO_PERMOVER return is_off and is_permanent async def async_set_operation_mode(self, operation_mode: str) -> None: """Set new operation mode for a DHW controller. Except for Auto, the mode is only until the next SetPoint. """ if operation_mode == STATE_AUTO: await self._evo_broker.call_client_api(self._evo_device.set_dhw_auto()) else: await self._update_schedule() until = dt_util.parse_datetime(self.setpoints.get("next_sp_from", "")) until = dt_util.as_utc(until) if until else None if operation_mode == STATE_ON: await self._evo_broker.call_client_api( self._evo_device.set_dhw_on(until=until) ) else: # STATE_OFF await self._evo_broker.call_client_api( self._evo_device.set_dhw_off(until=until) ) async def async_turn_away_mode_on(self): """Turn away mode on.""" await self._evo_broker.call_client_api(self._evo_device.set_dhw_off()) async def async_turn_away_mode_off(self): """Turn away mode off.""" await self._evo_broker.call_client_api(self._evo_device.set_dhw_auto()) async def async_turn_on(self): """Turn on.""" await self._evo_broker.call_client_api(self._evo_device.set_dhw_on()) async def async_turn_off(self): """Turn off.""" await self._evo_broker.call_client_api(self._evo_device.set_dhw_off()) async def async_update(self) -> None: """Get the latest state data for a DHW controller.""" await super().async_update() for attr in STATE_ATTRS_DHW: self._device_state_attrs[attr] = getattr(self._evo_device, attr)
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/evohome/water_heater.py
"""Provides a binary sensor which gets its values from a TCP socket.""" from __future__ import annotations from typing import Any, Final from homeassistant.components.binary_sensor import ( PLATFORM_SCHEMA as PARENT_PLATFORM_SCHEMA, BinarySensorEntity, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import ConfigType from .common import TCP_PLATFORM_SCHEMA, TcpEntity from .const import CONF_VALUE_ON PLATFORM_SCHEMA: Final = PARENT_PLATFORM_SCHEMA.extend(TCP_PLATFORM_SCHEMA) def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: dict[str, Any] | None = None, ) -> None: """Set up the TCP binary sensor.""" add_entities([TcpBinarySensor(hass, config)]) class TcpBinarySensor(TcpEntity, BinarySensorEntity): """A binary sensor which is on when its state == CONF_VALUE_ON.""" @property def is_on(self) -> bool: """Return true if the binary sensor is on.""" return self._state == self._config[CONF_VALUE_ON]
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/tcp/binary_sensor.py
"""Support for Z-Wave switches.""" import time from homeassistant.components.switch import DOMAIN, SwitchEntity from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from . import ZWaveDeviceEntity, workaround async def async_setup_entry(hass, config_entry, async_add_entities): """Set up Z-Wave Switch from Config Entry.""" @callback def async_add_switch(switch): """Add Z-Wave Switch.""" async_add_entities([switch]) async_dispatcher_connect(hass, "zwave_new_switch", async_add_switch) def get_device(values, **kwargs): """Create zwave entity device.""" return ZwaveSwitch(values) class ZwaveSwitch(ZWaveDeviceEntity, SwitchEntity): """Representation of a Z-Wave switch.""" def __init__(self, values): """Initialize the Z-Wave switch device.""" ZWaveDeviceEntity.__init__(self, values, DOMAIN) self.refresh_on_update = ( workaround.get_device_mapping(values.primary) == workaround.WORKAROUND_REFRESH_NODE_ON_UPDATE ) self.last_update = time.perf_counter() self._state = self.values.primary.data def update_properties(self): """Handle data changes for node values.""" self._state = self.values.primary.data if self.refresh_on_update and time.perf_counter() - self.last_update > 30: self.last_update = time.perf_counter() self.node.request_state() @property def is_on(self): """Return true if device is on.""" return self._state def turn_on(self, **kwargs): """Turn the device on.""" self.node.set_switch(self.values.primary.value_id, True) def turn_off(self, **kwargs): """Turn the device off.""" self.node.set_switch(self.values.primary.value_id, False)
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/zwave/switch.py
"""Provides functionality to interact with fans.""" from __future__ import annotations from datetime import timedelta import functools as ft import logging import math from typing import final import voluptuous as vol from homeassistant.const import ( SERVICE_TOGGLE, SERVICE_TURN_OFF, SERVICE_TURN_ON, STATE_ON, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import ( # noqa: F401 PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) from homeassistant.helpers.entity import ToggleEntity from homeassistant.helpers.entity_component import EntityComponent from homeassistant.loader import bind_hass from homeassistant.util.percentage import ( ordered_list_item_to_percentage, percentage_to_ordered_list_item, percentage_to_ranged_value, ranged_value_to_percentage, ) _LOGGER = logging.getLogger(__name__) DOMAIN = "fan" SCAN_INTERVAL = timedelta(seconds=30) ENTITY_ID_FORMAT = DOMAIN + ".{}" # Bitfield of features supported by the fan entity SUPPORT_SET_SPEED = 1 SUPPORT_OSCILLATE = 2 SUPPORT_DIRECTION = 4 SUPPORT_PRESET_MODE = 8 SERVICE_SET_SPEED = "set_speed" SERVICE_INCREASE_SPEED = "increase_speed" SERVICE_DECREASE_SPEED = "decrease_speed" SERVICE_OSCILLATE = "oscillate" SERVICE_SET_DIRECTION = "set_direction" SERVICE_SET_PERCENTAGE = "set_percentage" SERVICE_SET_PRESET_MODE = "set_preset_mode" SPEED_OFF = "off" SPEED_LOW = "low" SPEED_MEDIUM = "medium" SPEED_HIGH = "high" DIRECTION_FORWARD = "forward" DIRECTION_REVERSE = "reverse" ATTR_SPEED = "speed" ATTR_PERCENTAGE = "percentage" ATTR_PERCENTAGE_STEP = "percentage_step" ATTR_SPEED_LIST = "speed_list" ATTR_OSCILLATING = "oscillating" ATTR_DIRECTION = "direction" ATTR_PRESET_MODE = "preset_mode" ATTR_PRESET_MODES = "preset_modes" # Invalid speeds do not conform to the entity model, but have crept # into core integrations at some point so we are temporarily # accommodating them in the transition to percentages. _NOT_SPEED_OFF = "off" _NOT_SPEED_ON = "on" _NOT_SPEED_AUTO = "auto" _NOT_SPEED_SMART = "smart" _NOT_SPEED_INTERVAL = "interval" _NOT_SPEED_IDLE = "idle" _NOT_SPEED_FAVORITE = "favorite" _NOT_SPEED_SLEEP = "sleep" _NOT_SPEED_SILENT = "silent" _NOT_SPEEDS_FILTER = { _NOT_SPEED_OFF, _NOT_SPEED_ON, _NOT_SPEED_AUTO, _NOT_SPEED_SMART, _NOT_SPEED_INTERVAL, _NOT_SPEED_IDLE, _NOT_SPEED_SILENT, _NOT_SPEED_SLEEP, _NOT_SPEED_FAVORITE, } _FAN_NATIVE = "_fan_native" OFF_SPEED_VALUES = [SPEED_OFF, None] LEGACY_SPEED_LIST = [SPEED_LOW, SPEED_MEDIUM, SPEED_HIGH] class NoValidSpeedsError(ValueError): """Exception class when there are no valid speeds.""" class NotValidSpeedError(ValueError): """Exception class when the speed in not in the speed list.""" class NotValidPresetModeError(ValueError): """Exception class when the preset_mode in not in the preset_modes list.""" @bind_hass def is_on(hass, entity_id: str) -> bool: """Return if the fans are on based on the statemachine.""" state = hass.states.get(entity_id) if ATTR_SPEED in state.attributes: return state.attributes[ATTR_SPEED] not in OFF_SPEED_VALUES return state.state == STATE_ON async def async_setup(hass, config: dict): """Expose fan control via statemachine and services.""" component = hass.data[DOMAIN] = EntityComponent( _LOGGER, DOMAIN, hass, SCAN_INTERVAL ) await component.async_setup(config) # After the transition to percentage and preset_modes concludes, # switch this back to async_turn_on and remove async_turn_on_compat component.async_register_entity_service( SERVICE_TURN_ON, { vol.Optional(ATTR_SPEED): cv.string, vol.Optional(ATTR_PERCENTAGE): vol.All( vol.Coerce(int), vol.Range(min=0, max=100) ), vol.Optional(ATTR_PRESET_MODE): cv.string, }, "async_turn_on_compat", ) component.async_register_entity_service(SERVICE_TURN_OFF, {}, "async_turn_off") component.async_register_entity_service(SERVICE_TOGGLE, {}, "async_toggle") # After the transition to percentage and preset_modes concludes, # remove this service component.async_register_entity_service( SERVICE_SET_SPEED, {vol.Required(ATTR_SPEED): cv.string}, "async_set_speed_deprecated", [SUPPORT_SET_SPEED], ) component.async_register_entity_service( SERVICE_INCREASE_SPEED, { vol.Optional(ATTR_PERCENTAGE_STEP): vol.All( vol.Coerce(int), vol.Range(min=0, max=100) ) }, "async_increase_speed", [SUPPORT_SET_SPEED], ) component.async_register_entity_service( SERVICE_DECREASE_SPEED, { vol.Optional(ATTR_PERCENTAGE_STEP): vol.All( vol.Coerce(int), vol.Range(min=0, max=100) ) }, "async_decrease_speed", [SUPPORT_SET_SPEED], ) component.async_register_entity_service( SERVICE_OSCILLATE, {vol.Required(ATTR_OSCILLATING): cv.boolean}, "async_oscillate", [SUPPORT_OSCILLATE], ) component.async_register_entity_service( SERVICE_SET_DIRECTION, {vol.Optional(ATTR_DIRECTION): cv.string}, "async_set_direction", [SUPPORT_DIRECTION], ) component.async_register_entity_service( SERVICE_SET_PERCENTAGE, { vol.Required(ATTR_PERCENTAGE): vol.All( vol.Coerce(int), vol.Range(min=0, max=100) ) }, "async_set_percentage", [SUPPORT_SET_SPEED], ) component.async_register_entity_service( SERVICE_SET_PRESET_MODE, {vol.Required(ATTR_PRESET_MODE): cv.string}, "async_set_preset_mode", [SUPPORT_SET_SPEED, SUPPORT_PRESET_MODE], ) return True async def async_setup_entry(hass, entry): """Set up a config entry.""" return await hass.data[DOMAIN].async_setup_entry(entry) async def async_unload_entry(hass, entry): """Unload a config entry.""" return await hass.data[DOMAIN].async_unload_entry(entry) def _fan_native(method): """Native fan method not overridden.""" setattr(method, _FAN_NATIVE, True) return method class FanEntity(ToggleEntity): """Base class for fan entities.""" @_fan_native def set_speed(self, speed: str) -> None: """Set the speed of the fan.""" raise NotImplementedError() async def async_set_speed_deprecated(self, speed: str): """Set the speed of the fan.""" _LOGGER.warning( "The fan.set_speed service is deprecated, use fan.set_percentage or fan.set_preset_mode instead" ) await self.async_set_speed(speed) @_fan_native async def async_set_speed(self, speed: str): """Set the speed of the fan.""" if speed == SPEED_OFF: await self.async_turn_off() return if speed in self.preset_modes: if not hasattr(self.async_set_preset_mode, _FAN_NATIVE): await self.async_set_preset_mode(speed) return if not hasattr(self.set_preset_mode, _FAN_NATIVE): await self.hass.async_add_executor_job(self.set_preset_mode, speed) return else: if not hasattr(self.async_set_percentage, _FAN_NATIVE): await self.async_set_percentage(self.speed_to_percentage(speed)) return if not hasattr(self.set_percentage, _FAN_NATIVE): await self.hass.async_add_executor_job( self.set_percentage, self.speed_to_percentage(speed) ) return await self.hass.async_add_executor_job(self.set_speed, speed) @_fan_native def set_percentage(self, percentage: int) -> None: """Set the speed of the fan, as a percentage.""" raise NotImplementedError() @_fan_native async def async_set_percentage(self, percentage: int) -> None: """Set the speed of the fan, as a percentage.""" if percentage == 0: await self.async_turn_off() elif not hasattr(self.set_percentage, _FAN_NATIVE): await self.hass.async_add_executor_job(self.set_percentage, percentage) else: await self.async_set_speed(self.percentage_to_speed(percentage)) async def async_increase_speed(self, percentage_step: int | None = None) -> None: """Increase the speed of the fan.""" await self._async_adjust_speed(1, percentage_step) async def async_decrease_speed(self, percentage_step: int | None = None) -> None: """Decrease the speed of the fan.""" await self._async_adjust_speed(-1, percentage_step) async def _async_adjust_speed( self, modifier: int, percentage_step: int | None ) -> None: """Increase or decrease the speed of the fan.""" current_percentage = self.percentage or 0 if percentage_step is not None: new_percentage = current_percentage + (percentage_step * modifier) else: speed_range = (1, self.speed_count) speed_index = math.ceil( percentage_to_ranged_value(speed_range, current_percentage) ) new_percentage = ranged_value_to_percentage( speed_range, speed_index + modifier ) new_percentage = max(0, min(100, new_percentage)) await self.async_set_percentage(new_percentage) @_fan_native def set_preset_mode(self, preset_mode: str) -> None: """Set new preset mode.""" self._valid_preset_mode_or_raise(preset_mode) self.set_speed(preset_mode) @_fan_native async def async_set_preset_mode(self, preset_mode: str) -> None: """Set new preset mode.""" if not hasattr(self.set_preset_mode, _FAN_NATIVE): await self.hass.async_add_executor_job(self.set_preset_mode, preset_mode) return self._valid_preset_mode_or_raise(preset_mode) await self.async_set_speed(preset_mode) def _valid_preset_mode_or_raise(self, preset_mode): """Raise NotValidPresetModeError on invalid preset_mode.""" preset_modes = self.preset_modes if preset_mode not in preset_modes: raise NotValidPresetModeError( f"The preset_mode {preset_mode} is not a valid preset_mode: {preset_modes}" ) def set_direction(self, direction: str) -> None: """Set the direction of the fan.""" raise NotImplementedError() async def async_set_direction(self, direction: str): """Set the direction of the fan.""" await self.hass.async_add_executor_job(self.set_direction, direction) # pylint: disable=arguments-differ def turn_on( self, speed: str | None = None, percentage: int | None = None, preset_mode: str | None = None, **kwargs, ) -> None: """Turn on the fan.""" raise NotImplementedError() async def async_turn_on_compat( self, speed: str | None = None, percentage: int | None = None, preset_mode: str | None = None, **kwargs, ) -> None: """Turn on the fan. This _compat version wraps async_turn_on with backwards and forward compatibility. After the transition to percentage and preset_modes concludes, it should be removed. """ if preset_mode is not None: self._valid_preset_mode_or_raise(preset_mode) speed = preset_mode percentage = None elif speed is not None: _LOGGER.warning( "Calling fan.turn_on with the speed argument is deprecated, use percentage or preset_mode instead" ) if speed in self.preset_modes: preset_mode = speed percentage = None else: percentage = self.speed_to_percentage(speed) elif percentage is not None: speed = self.percentage_to_speed(percentage) await self.async_turn_on( speed=speed, percentage=percentage, preset_mode=preset_mode, **kwargs, ) # pylint: disable=arguments-differ async def async_turn_on( self, speed: str | None = None, percentage: int | None = None, preset_mode: str | None = None, **kwargs, ) -> None: """Turn on the fan.""" if speed == SPEED_OFF: await self.async_turn_off() else: await self.hass.async_add_executor_job( ft.partial( self.turn_on, speed=speed, percentage=percentage, preset_mode=preset_mode, **kwargs, ) ) def oscillate(self, oscillating: bool) -> None: """Oscillate the fan.""" raise NotImplementedError() async def async_oscillate(self, oscillating: bool): """Oscillate the fan.""" await self.hass.async_add_executor_job(self.oscillate, oscillating) @property def is_on(self): """Return true if the entity is on.""" return self.speed not in [SPEED_OFF, None] @property def _implemented_percentage(self) -> bool: """Return true if percentage has been implemented.""" return not hasattr(self.set_percentage, _FAN_NATIVE) or not hasattr( self.async_set_percentage, _FAN_NATIVE ) @property def _implemented_preset_mode(self) -> bool: """Return true if preset_mode has been implemented.""" return not hasattr(self.set_preset_mode, _FAN_NATIVE) or not hasattr( self.async_set_preset_mode, _FAN_NATIVE ) @property def _implemented_speed(self) -> bool: """Return true if speed has been implemented.""" return not hasattr(self.set_speed, _FAN_NATIVE) or not hasattr( self.async_set_speed, _FAN_NATIVE ) @property def speed(self) -> str | None: """Return the current speed.""" if self._implemented_preset_mode: preset_mode = self.preset_mode if preset_mode: return preset_mode if self._implemented_percentage: percentage = self.percentage if percentage is None: return None return self.percentage_to_speed(percentage) return None @property def percentage(self) -> int | None: """Return the current speed as a percentage.""" if not self._implemented_preset_mode and self.speed in self.preset_modes: return None if not self._implemented_percentage: return self.speed_to_percentage(self.speed) return 0 @property def speed_count(self) -> int: """Return the number of speeds the fan supports.""" speed_list = speed_list_without_preset_modes(self.speed_list) if speed_list: return len(speed_list) return 100 @property def percentage_step(self) -> float: """Return the step size for percentage.""" return 100 / self.speed_count @property def speed_list(self) -> list: """Get the list of available speeds.""" speeds = [] if self._implemented_percentage: speeds += [SPEED_OFF, *LEGACY_SPEED_LIST] if self._implemented_preset_mode: speeds += self.preset_modes return speeds @property def current_direction(self) -> str | None: """Return the current direction of the fan.""" return None @property def oscillating(self): """Return whether or not the fan is currently oscillating.""" return None @property def capability_attributes(self): """Return capability attributes.""" attrs = {} if self.supported_features & SUPPORT_SET_SPEED: attrs[ATTR_SPEED_LIST] = self.speed_list if ( self.supported_features & SUPPORT_SET_SPEED or self.supported_features & SUPPORT_PRESET_MODE ): attrs[ATTR_PRESET_MODES] = self.preset_modes return attrs @property def _speed_list_without_preset_modes(self) -> list: """Return the speed list without preset modes. This property provides forward and backwards compatibility for conversion to percentage speeds. """ if not self._implemented_speed: return LEGACY_SPEED_LIST return speed_list_without_preset_modes(self.speed_list) def speed_to_percentage(self, speed: str) -> int: """ Map a speed to a percentage. Officially this should only have to deal with the 4 pre-defined speeds: return { SPEED_OFF: 0, SPEED_LOW: 33, SPEED_MEDIUM: 66, SPEED_HIGH: 100, }[speed] Unfortunately lots of fans make up their own speeds. So the default mapping is more dynamic. """ if speed in OFF_SPEED_VALUES: return 0 speed_list = self._speed_list_without_preset_modes if speed_list and speed not in speed_list: raise NotValidSpeedError(f"The speed {speed} is not a valid speed.") try: return ordered_list_item_to_percentage(speed_list, speed) except ValueError as ex: raise NoValidSpeedsError( f"The speed_list {speed_list} does not contain any valid speeds." ) from ex def percentage_to_speed(self, percentage: int) -> str: """ Map a percentage onto self.speed_list. Officially, this should only have to deal with 4 pre-defined speeds. if value == 0: return SPEED_OFF elif value <= 33: return SPEED_LOW elif value <= 66: return SPEED_MEDIUM else: return SPEED_HIGH Unfortunately there is currently a high degree of non-conformancy. Until fans have been corrected a more complicated and dynamic mapping is used. """ if percentage == 0: return SPEED_OFF speed_list = self._speed_list_without_preset_modes try: return percentage_to_ordered_list_item(speed_list, percentage) except ValueError as ex: raise NoValidSpeedsError( f"The speed_list {speed_list} does not contain any valid speeds." ) from ex @final @property def state_attributes(self) -> dict: """Return optional state attributes.""" data = {} supported_features = self.supported_features if supported_features & SUPPORT_DIRECTION: data[ATTR_DIRECTION] = self.current_direction if supported_features & SUPPORT_OSCILLATE: data[ATTR_OSCILLATING] = self.oscillating if supported_features & SUPPORT_SET_SPEED: data[ATTR_SPEED] = self.speed data[ATTR_PERCENTAGE] = self.percentage data[ATTR_PERCENTAGE_STEP] = self.percentage_step if ( supported_features & SUPPORT_PRESET_MODE or supported_features & SUPPORT_SET_SPEED ): data[ATTR_PRESET_MODE] = self.preset_mode return data @property def supported_features(self) -> int: """Flag supported features.""" return 0 @property def preset_mode(self) -> str | None: """Return the current preset mode, e.g., auto, smart, interval, favorite. Requires SUPPORT_SET_SPEED. """ speed = self.speed if speed in self.preset_modes: return speed return None @property def preset_modes(self) -> list[str] | None: """Return a list of available preset modes. Requires SUPPORT_SET_SPEED. """ return preset_modes_from_speed_list(self.speed_list) def speed_list_without_preset_modes(speed_list: list): """Filter out non-speeds from the speed list. The goal is to get the speeds in a list from lowest to highest by removing speeds that are not valid or out of order so we can map them to percentages. Examples: input: ["off", "low", "low-medium", "medium", "medium-high", "high", "auto"] output: ["low", "low-medium", "medium", "medium-high", "high"] input: ["off", "auto", "low", "medium", "high"] output: ["low", "medium", "high"] input: ["off", "1", "2", "3", "4", "5", "6", "7", "smart"] output: ["1", "2", "3", "4", "5", "6", "7"] input: ["Auto", "Silent", "Favorite", "Idle", "Medium", "High", "Strong"] output: ["Medium", "High", "Strong"] """ return [speed for speed in speed_list if speed.lower() not in _NOT_SPEEDS_FILTER] def preset_modes_from_speed_list(speed_list: list): """Filter out non-preset modes from the speed list. The goal is to return only preset modes. Examples: input: ["off", "low", "low-medium", "medium", "medium-high", "high", "auto"] output: ["auto"] input: ["off", "auto", "low", "medium", "high"] output: ["auto"] input: ["off", "1", "2", "3", "4", "5", "6", "7", "smart"] output: ["smart"] input: ["Auto", "Silent", "Favorite", "Idle", "Medium", "High", "Strong"] output: ["Auto", "Silent", "Favorite", "Idle"] """ return [ speed for speed in speed_list if speed.lower() in _NOT_SPEEDS_FILTER and speed.lower() != SPEED_OFF ]
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/fan/__init__.py
"""Support for tracking which astronomical or meteorological season it is.""" from datetime import datetime import logging import ephem import voluptuous as vol from homeassistant import util from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import CONF_NAME, CONF_TYPE import homeassistant.helpers.config_validation as cv from homeassistant.util.dt import utcnow _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "Season" EQUATOR = "equator" NORTHERN = "northern" SOUTHERN = "southern" STATE_AUTUMN = "autumn" STATE_SPRING = "spring" STATE_SUMMER = "summer" STATE_WINTER = "winter" TYPE_ASTRONOMICAL = "astronomical" TYPE_METEOROLOGICAL = "meteorological" VALID_TYPES = [TYPE_ASTRONOMICAL, TYPE_METEOROLOGICAL] HEMISPHERE_SEASON_SWAP = { STATE_WINTER: STATE_SUMMER, STATE_SPRING: STATE_AUTUMN, STATE_AUTUMN: STATE_SPRING, STATE_SUMMER: STATE_WINTER, } SEASON_ICONS = { STATE_SPRING: "mdi:flower", STATE_SUMMER: "mdi:sunglasses", STATE_AUTUMN: "mdi:leaf", STATE_WINTER: "mdi:snowflake", } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_TYPE, default=TYPE_ASTRONOMICAL): vol.In(VALID_TYPES), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Display the current season.""" if None in (hass.config.latitude, hass.config.longitude): _LOGGER.error("Latitude or longitude not set in Home Assistant config") return False latitude = util.convert(hass.config.latitude, float) _type = config.get(CONF_TYPE) name = config.get(CONF_NAME) if latitude < 0: hemisphere = SOUTHERN elif latitude > 0: hemisphere = NORTHERN else: hemisphere = EQUATOR _LOGGER.debug(_type) add_entities([Season(hass, hemisphere, _type, name)], True) return True def get_season(date, hemisphere, season_tracking_type): """Calculate the current season.""" if hemisphere == "equator": return None if season_tracking_type == TYPE_ASTRONOMICAL: spring_start = ephem.next_equinox(str(date.year)).datetime() summer_start = ephem.next_solstice(str(date.year)).datetime() autumn_start = ephem.next_equinox(spring_start).datetime() winter_start = ephem.next_solstice(summer_start).datetime() else: spring_start = datetime(2017, 3, 1).replace(year=date.year) summer_start = spring_start.replace(month=6) autumn_start = spring_start.replace(month=9) winter_start = spring_start.replace(month=12) if spring_start <= date < summer_start: season = STATE_SPRING elif summer_start <= date < autumn_start: season = STATE_SUMMER elif autumn_start <= date < winter_start: season = STATE_AUTUMN elif winter_start <= date or spring_start > date: season = STATE_WINTER # If user is located in the southern hemisphere swap the season if hemisphere == NORTHERN: return season return HEMISPHERE_SEASON_SWAP.get(season) class Season(SensorEntity): """Representation of the current season.""" def __init__(self, hass, hemisphere, season_tracking_type, name): """Initialize the season.""" self.hass = hass self._name = name self.hemisphere = hemisphere self.datetime = None self.type = season_tracking_type self.season = None @property def name(self): """Return the name.""" return self._name @property def state(self): """Return the current season.""" return self.season @property def device_class(self): """Return the device class.""" return "season__season" @property def icon(self): """Icon to use in the frontend, if any.""" return SEASON_ICONS.get(self.season, "mdi:cloud") def update(self): """Update season.""" self.datetime = utcnow().replace(tzinfo=None) self.season = get_season(self.datetime, self.hemisphere, self.type)
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/season/sensor.py
"""Methods and classes related to executing Z-Wave commands and publishing these to hass.""" import logging from openzwavemqtt.const import ATTR_LABEL, ATTR_POSITION, ATTR_VALUE from openzwavemqtt.util.node import get_node_from_manager, set_config_parameter import voluptuous as vol from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from . import const _LOGGER = logging.getLogger(__name__) class ZWaveServices: """Class that holds our services ( Zwave Commands) that should be published to hass.""" def __init__(self, hass, manager): """Initialize with both hass and ozwmanager objects.""" self._hass = hass self._manager = manager @callback def async_register(self): """Register all our services.""" self._hass.services.async_register( const.DOMAIN, const.SERVICE_ADD_NODE, self.async_add_node, schema=vol.Schema( { vol.Optional(const.ATTR_INSTANCE_ID, default=1): vol.Coerce(int), vol.Optional(const.ATTR_SECURE, default=False): vol.Coerce(bool), } ), ) self._hass.services.async_register( const.DOMAIN, const.SERVICE_REMOVE_NODE, self.async_remove_node, schema=vol.Schema( {vol.Optional(const.ATTR_INSTANCE_ID, default=1): vol.Coerce(int)} ), ) self._hass.services.async_register( const.DOMAIN, const.SERVICE_CANCEL_COMMAND, self.async_cancel_command, schema=vol.Schema( {vol.Optional(const.ATTR_INSTANCE_ID, default=1): vol.Coerce(int)} ), ) self._hass.services.async_register( const.DOMAIN, const.SERVICE_SET_CONFIG_PARAMETER, self.async_set_config_parameter, schema=vol.Schema( { vol.Optional(const.ATTR_INSTANCE_ID, default=1): vol.Coerce(int), vol.Required(const.ATTR_NODE_ID): vol.Coerce(int), vol.Required(const.ATTR_CONFIG_PARAMETER): vol.Coerce(int), vol.Required(const.ATTR_CONFIG_VALUE): vol.Any( vol.All( cv.ensure_list, [ vol.All( { vol.Exclusive(ATTR_LABEL, "bit"): cv.string, vol.Exclusive(ATTR_POSITION, "bit"): vol.Coerce( int ), vol.Required(ATTR_VALUE): bool, }, cv.has_at_least_one_key(ATTR_LABEL, ATTR_POSITION), ) ], ), vol.Coerce(int), bool, cv.string, ), } ), ) @callback def async_set_config_parameter(self, service): """Set a config parameter to a node.""" instance_id = service.data[const.ATTR_INSTANCE_ID] node_id = service.data[const.ATTR_NODE_ID] param = service.data[const.ATTR_CONFIG_PARAMETER] selection = service.data[const.ATTR_CONFIG_VALUE] # These function calls may raise an exception but that's ok because # the exception will show in the UI to the user node = get_node_from_manager(self._manager, instance_id, node_id) payload = set_config_parameter(node, param, selection) _LOGGER.info( "Setting configuration parameter %s on Node %s with value %s", param, node_id, payload, ) @callback def async_add_node(self, service): """Enter inclusion mode on the controller.""" instance_id = service.data[const.ATTR_INSTANCE_ID] secure = service.data[const.ATTR_SECURE] instance = self._manager.get_instance(instance_id) if instance is None: raise ValueError(f"No OpenZWave Instance with ID {instance_id}") instance.add_node(secure) @callback def async_remove_node(self, service): """Enter exclusion mode on the controller.""" instance_id = service.data[const.ATTR_INSTANCE_ID] instance = self._manager.get_instance(instance_id) if instance is None: raise ValueError(f"No OpenZWave Instance with ID {instance_id}") instance.remove_node() @callback def async_cancel_command(self, service): """Tell the controller to cancel an add or remove command.""" instance_id = service.data[const.ATTR_INSTANCE_ID] instance = self._manager.get_instance(instance_id) if instance is None: raise ValueError(f"No OpenZWave Instance with ID {instance_id}") instance.cancel_controller_command()
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/ozw/services.py
"""Config flow utilities.""" from collections import OrderedDict from pyvesync import VeSync import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.core import callback from .const import DOMAIN class VeSyncFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Handle a config flow.""" VERSION = 1 def __init__(self): """Instantiate config flow.""" self._username = None self._password = None self.data_schema = OrderedDict() self.data_schema[vol.Required(CONF_USERNAME)] = str self.data_schema[vol.Required(CONF_PASSWORD)] = str @callback def _show_form(self, errors=None): """Show form to the user.""" return self.async_show_form( step_id="user", data_schema=vol.Schema(self.data_schema), errors=errors if errors else {}, ) async def async_step_import(self, import_config): """Handle external yaml configuration.""" return await self.async_step_user(import_config) async def async_step_user(self, user_input=None): """Handle a flow start.""" if self._async_current_entries(): return self.async_abort(reason="single_instance_allowed") if not user_input: return self._show_form() self._username = user_input[CONF_USERNAME] self._password = user_input[CONF_PASSWORD] manager = VeSync(self._username, self._password) login = await self.hass.async_add_executor_job(manager.login) if not login: return self._show_form(errors={"base": "invalid_auth"}) return self.async_create_entry( title=self._username, data={CONF_USERNAME: self._username, CONF_PASSWORD: self._password}, )
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/vesync/config_flow.py
"""Component to interface with cameras.""" from __future__ import annotations import asyncio import base64 import collections from collections.abc import Awaitable, Mapping from contextlib import suppress from datetime import datetime, timedelta import hashlib import logging import os from random import SystemRandom from typing import Callable, Final, cast, final from aiohttp import web import async_timeout import attr import voluptuous as vol from homeassistant.components import websocket_api from homeassistant.components.http import KEY_AUTHENTICATED, HomeAssistantView from homeassistant.components.media_player.const import ( ATTR_MEDIA_CONTENT_ID, ATTR_MEDIA_CONTENT_TYPE, ATTR_MEDIA_EXTRA, DOMAIN as DOMAIN_MP, SERVICE_PLAY_MEDIA, ) from homeassistant.components.stream import Stream, create_stream from homeassistant.components.stream.const import FORMAT_CONTENT_TYPE, OUTPUT_FORMATS from homeassistant.components.websocket_api import ActiveConnection from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( ATTR_ENTITY_ID, CONF_FILENAME, CONTENT_TYPE_MULTIPART, EVENT_HOMEASSISTANT_START, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.core import Event, HomeAssistant, ServiceCall, callback from homeassistant.exceptions import HomeAssistantError import homeassistant.helpers.config_validation as cv from homeassistant.helpers.config_validation import ( # noqa: F401 PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) from homeassistant.helpers.entity import Entity, entity_sources from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.network import get_url from homeassistant.helpers.typing import ConfigType from homeassistant.loader import bind_hass from .const import ( CAMERA_IMAGE_TIMEOUT, CAMERA_STREAM_SOURCE_TIMEOUT, CONF_DURATION, CONF_LOOKBACK, DATA_CAMERA_PREFS, DOMAIN, SERVICE_RECORD, ) from .prefs import CameraPreferences # mypy: allow-untyped-calls _LOGGER = logging.getLogger(__name__) SERVICE_ENABLE_MOTION: Final = "enable_motion_detection" SERVICE_DISABLE_MOTION: Final = "disable_motion_detection" SERVICE_SNAPSHOT: Final = "snapshot" SERVICE_PLAY_STREAM: Final = "play_stream" SCAN_INTERVAL: Final = timedelta(seconds=30) ENTITY_ID_FORMAT: Final = DOMAIN + ".{}" ATTR_FILENAME: Final = "filename" ATTR_MEDIA_PLAYER: Final = "media_player" ATTR_FORMAT: Final = "format" STATE_RECORDING: Final = "recording" STATE_STREAMING: Final = "streaming" STATE_IDLE: Final = "idle" # Bitfield of features supported by the camera entity SUPPORT_ON_OFF: Final = 1 SUPPORT_STREAM: Final = 2 DEFAULT_CONTENT_TYPE: Final = "image/jpeg" ENTITY_IMAGE_URL: Final = "/api/camera_proxy/{0}?token={1}" TOKEN_CHANGE_INTERVAL: Final = timedelta(minutes=5) _RND: Final = SystemRandom() MIN_STREAM_INTERVAL: Final = 0.5 # seconds CAMERA_SERVICE_SNAPSHOT: Final = {vol.Required(ATTR_FILENAME): cv.template} CAMERA_SERVICE_PLAY_STREAM: Final = { vol.Required(ATTR_MEDIA_PLAYER): cv.entities_domain(DOMAIN_MP), vol.Optional(ATTR_FORMAT, default="hls"): vol.In(OUTPUT_FORMATS), } CAMERA_SERVICE_RECORD: Final = { vol.Required(CONF_FILENAME): cv.template, vol.Optional(CONF_DURATION, default=30): vol.Coerce(int), vol.Optional(CONF_LOOKBACK, default=0): vol.Coerce(int), } WS_TYPE_CAMERA_THUMBNAIL: Final = "camera_thumbnail" SCHEMA_WS_CAMERA_THUMBNAIL: Final = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend( { vol.Required("type"): WS_TYPE_CAMERA_THUMBNAIL, vol.Required("entity_id"): cv.entity_id, } ) @attr.s class Image: """Represent an image.""" content_type: str = attr.ib() content: bytes = attr.ib() @bind_hass async def async_request_stream(hass: HomeAssistant, entity_id: str, fmt: str) -> str: """Request a stream for a camera entity.""" camera = _get_camera_from_entity_id(hass, entity_id) return await _async_stream_endpoint_url(hass, camera, fmt) @bind_hass async def async_get_image( hass: HomeAssistant, entity_id: str, timeout: int = 10 ) -> Image: """Fetch an image from a camera entity.""" camera = _get_camera_from_entity_id(hass, entity_id) with suppress(asyncio.CancelledError, asyncio.TimeoutError): async with async_timeout.timeout(timeout): image = await camera.async_camera_image() if image: return Image(camera.content_type, image) raise HomeAssistantError("Unable to get image") @bind_hass async def async_get_stream_source(hass: HomeAssistant, entity_id: str) -> str | None: """Fetch the stream source for a camera entity.""" camera = _get_camera_from_entity_id(hass, entity_id) return await camera.stream_source() @bind_hass async def async_get_mjpeg_stream( hass: HomeAssistant, request: web.Request, entity_id: str ) -> web.StreamResponse | None: """Fetch an mjpeg stream from a camera entity.""" camera = _get_camera_from_entity_id(hass, entity_id) return await camera.handle_async_mjpeg_stream(request) async def async_get_still_stream( request: web.Request, image_cb: Callable[[], Awaitable[bytes | None]], content_type: str, interval: float, ) -> web.StreamResponse: """Generate an HTTP MJPEG stream from camera images. This method must be run in the event loop. """ response = web.StreamResponse() response.content_type = CONTENT_TYPE_MULTIPART.format("--frameboundary") await response.prepare(request) async def write_to_mjpeg_stream(img_bytes: bytes) -> None: """Write image to stream.""" await response.write( bytes( "--frameboundary\r\n" "Content-Type: {}\r\n" "Content-Length: {}\r\n\r\n".format(content_type, len(img_bytes)), "utf-8", ) + img_bytes + b"\r\n" ) last_image = None while True: img_bytes = await image_cb() if not img_bytes: break if img_bytes != last_image: await write_to_mjpeg_stream(img_bytes) # Chrome seems to always ignore first picture, # print it twice. if last_image is None: await write_to_mjpeg_stream(img_bytes) last_image = img_bytes await asyncio.sleep(interval) return response def _get_camera_from_entity_id(hass: HomeAssistant, entity_id: str) -> Camera: """Get camera component from entity_id.""" component = hass.data.get(DOMAIN) if component is None: raise HomeAssistantError("Camera integration not set up") camera = component.get_entity(entity_id) if camera is None: raise HomeAssistantError("Camera not found") if not camera.is_on: raise HomeAssistantError("Camera is off") return cast(Camera, camera) async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the camera component.""" component = hass.data[DOMAIN] = EntityComponent( _LOGGER, DOMAIN, hass, SCAN_INTERVAL ) prefs = CameraPreferences(hass) await prefs.async_initialize() hass.data[DATA_CAMERA_PREFS] = prefs hass.http.register_view(CameraImageView(component)) hass.http.register_view(CameraMjpegStream(component)) hass.components.websocket_api.async_register_command( WS_TYPE_CAMERA_THUMBNAIL, websocket_camera_thumbnail, SCHEMA_WS_CAMERA_THUMBNAIL ) hass.components.websocket_api.async_register_command(ws_camera_stream) hass.components.websocket_api.async_register_command(websocket_get_prefs) hass.components.websocket_api.async_register_command(websocket_update_prefs) await component.async_setup(config) async def preload_stream(_event: Event) -> None: for camera in component.entities: camera = cast(Camera, camera) camera_prefs = prefs.get(camera.entity_id) if not camera_prefs.preload_stream: continue stream = await camera.create_stream() if not stream: continue stream.keepalive = True stream.add_provider("hls") stream.start() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, preload_stream) @callback def update_tokens(time: datetime) -> None: """Update tokens of the entities.""" for entity in component.entities: entity = cast(Camera, entity) entity.async_update_token() entity.async_write_ha_state() hass.helpers.event.async_track_time_interval(update_tokens, TOKEN_CHANGE_INTERVAL) component.async_register_entity_service( SERVICE_ENABLE_MOTION, {}, "async_enable_motion_detection" ) component.async_register_entity_service( SERVICE_DISABLE_MOTION, {}, "async_disable_motion_detection" ) component.async_register_entity_service(SERVICE_TURN_OFF, {}, "async_turn_off") component.async_register_entity_service(SERVICE_TURN_ON, {}, "async_turn_on") component.async_register_entity_service( SERVICE_SNAPSHOT, CAMERA_SERVICE_SNAPSHOT, async_handle_snapshot_service ) component.async_register_entity_service( SERVICE_PLAY_STREAM, CAMERA_SERVICE_PLAY_STREAM, async_handle_play_stream_service, ) component.async_register_entity_service( SERVICE_RECORD, CAMERA_SERVICE_RECORD, async_handle_record_service ) return True async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up a config entry.""" component: EntityComponent = hass.data[DOMAIN] return await component.async_setup_entry(entry) async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" component: EntityComponent = hass.data[DOMAIN] return await component.async_unload_entry(entry) class Camera(Entity): """The base class for camera entities.""" def __init__(self) -> None: """Initialize a camera.""" self.is_streaming: bool = False self.stream: Stream | None = None self.stream_options: dict[str, str] = {} self.content_type: str = DEFAULT_CONTENT_TYPE self.access_tokens: collections.deque = collections.deque([], 2) self.async_update_token() @property def should_poll(self) -> bool: """No need to poll cameras.""" return False @property def entity_picture(self) -> str: """Return a link to the camera feed as entity picture.""" return ENTITY_IMAGE_URL.format(self.entity_id, self.access_tokens[-1]) @property def supported_features(self) -> int: """Flag supported features.""" return 0 @property def is_recording(self) -> bool: """Return true if the device is recording.""" return False @property def brand(self) -> str | None: """Return the camera brand.""" return None @property def motion_detection_enabled(self) -> bool: """Return the camera motion detection status.""" return False @property def model(self) -> str | None: """Return the camera model.""" return None @property def frame_interval(self) -> float: """Return the interval between frames of the mjpeg stream.""" return MIN_STREAM_INTERVAL async def create_stream(self) -> Stream | None: """Create a Stream for stream_source.""" # There is at most one stream (a decode worker) per camera if not self.stream: async with async_timeout.timeout(CAMERA_STREAM_SOURCE_TIMEOUT): source = await self.stream_source() if not source: return None self.stream = create_stream(self.hass, source, options=self.stream_options) return self.stream async def stream_source(self) -> str | None: """Return the source of the stream.""" return None def camera_image(self) -> bytes | None: """Return bytes of camera image.""" raise NotImplementedError() async def async_camera_image(self) -> bytes | None: """Return bytes of camera image.""" return await self.hass.async_add_executor_job(self.camera_image) async def handle_async_still_stream( self, request: web.Request, interval: float ) -> web.StreamResponse: """Generate an HTTP MJPEG stream from camera images.""" return await async_get_still_stream( request, self.async_camera_image, self.content_type, interval ) async def handle_async_mjpeg_stream( self, request: web.Request ) -> web.StreamResponse | None: """Serve an HTTP MJPEG stream from the camera. This method can be overridden by camera platforms to proxy a direct stream from the camera. """ return await self.handle_async_still_stream(request, self.frame_interval) @property def state(self) -> str: """Return the camera state.""" if self.is_recording: return STATE_RECORDING if self.is_streaming: return STATE_STREAMING return STATE_IDLE @property def is_on(self) -> bool: """Return true if on.""" return True def turn_off(self) -> None: """Turn off camera.""" raise NotImplementedError() async def async_turn_off(self) -> None: """Turn off camera.""" await self.hass.async_add_executor_job(self.turn_off) def turn_on(self) -> None: """Turn off camera.""" raise NotImplementedError() async def async_turn_on(self) -> None: """Turn off camera.""" await self.hass.async_add_executor_job(self.turn_on) def enable_motion_detection(self) -> None: """Enable motion detection in the camera.""" raise NotImplementedError() async def async_enable_motion_detection(self) -> None: """Call the job and enable motion detection.""" await self.hass.async_add_executor_job(self.enable_motion_detection) def disable_motion_detection(self) -> None: """Disable motion detection in camera.""" raise NotImplementedError() async def async_disable_motion_detection(self) -> None: """Call the job and disable motion detection.""" await self.hass.async_add_executor_job(self.disable_motion_detection) @final @property def state_attributes(self) -> dict[str, str | None]: """Return the camera state attributes.""" attrs = {"access_token": self.access_tokens[-1]} if self.model: attrs["model_name"] = self.model if self.brand: attrs["brand"] = self.brand if self.motion_detection_enabled: attrs["motion_detection"] = self.motion_detection_enabled return attrs @callback def async_update_token(self) -> None: """Update the used token.""" self.access_tokens.append( hashlib.sha256(_RND.getrandbits(256).to_bytes(32, "little")).hexdigest() ) class CameraView(HomeAssistantView): """Base CameraView.""" requires_auth = False def __init__(self, component: EntityComponent) -> None: """Initialize a basic camera view.""" self.component = component async def get(self, request: web.Request, entity_id: str) -> web.StreamResponse: """Start a GET request.""" camera = self.component.get_entity(entity_id) if camera is None: raise web.HTTPNotFound() camera = cast(Camera, camera) authenticated = ( request[KEY_AUTHENTICATED] or request.query.get("token") in camera.access_tokens ) if not authenticated: raise web.HTTPUnauthorized() if not camera.is_on: _LOGGER.debug("Camera is off") raise web.HTTPServiceUnavailable() return await self.handle(request, camera) async def handle(self, request: web.Request, camera: Camera) -> web.StreamResponse: """Handle the camera request.""" raise NotImplementedError() class CameraImageView(CameraView): """Camera view to serve an image.""" url = "/api/camera_proxy/{entity_id}" name = "api:camera:image" async def handle(self, request: web.Request, camera: Camera) -> web.Response: """Serve camera image.""" with suppress(asyncio.CancelledError, asyncio.TimeoutError): async with async_timeout.timeout(CAMERA_IMAGE_TIMEOUT): image = await camera.async_camera_image() if image: return web.Response(body=image, content_type=camera.content_type) raise web.HTTPInternalServerError() class CameraMjpegStream(CameraView): """Camera View to serve an MJPEG stream.""" url = "/api/camera_proxy_stream/{entity_id}" name = "api:camera:stream" async def handle(self, request: web.Request, camera: Camera) -> web.StreamResponse: """Serve camera stream, possibly with interval.""" interval_str = request.query.get("interval") if interval_str is None: stream = await camera.handle_async_mjpeg_stream(request) if stream is None: raise web.HTTPBadGateway() return stream try: # Compose camera stream from stills interval = float(interval_str) if interval < MIN_STREAM_INTERVAL: raise ValueError(f"Stream interval must be be > {MIN_STREAM_INTERVAL}") return await camera.handle_async_still_stream(request, interval) except ValueError as err: raise web.HTTPBadRequest() from err @websocket_api.async_response async def websocket_camera_thumbnail( hass: HomeAssistant, connection: ActiveConnection, msg: dict ) -> None: """Handle get camera thumbnail websocket command. Async friendly. """ _LOGGER.warning("The websocket command 'camera_thumbnail' has been deprecated") try: image = await async_get_image(hass, msg["entity_id"]) await connection.send_big_result( msg["id"], { "content_type": image.content_type, "content": base64.b64encode(image.content).decode("utf-8"), }, ) except HomeAssistantError: connection.send_message( websocket_api.error_message( msg["id"], "image_fetch_failed", "Unable to fetch image" ) ) @websocket_api.websocket_command( { vol.Required("type"): "camera/stream", vol.Required("entity_id"): cv.entity_id, vol.Optional("format", default="hls"): vol.In(OUTPUT_FORMATS), } ) @websocket_api.async_response async def ws_camera_stream( hass: HomeAssistant, connection: ActiveConnection, msg: dict ) -> None: """Handle get camera stream websocket command. Async friendly. """ try: entity_id = msg["entity_id"] camera = _get_camera_from_entity_id(hass, entity_id) url = await _async_stream_endpoint_url(hass, camera, fmt=msg["format"]) connection.send_result(msg["id"], {"url": url}) except HomeAssistantError as ex: _LOGGER.error("Error requesting stream: %s", ex) connection.send_error(msg["id"], "start_stream_failed", str(ex)) except asyncio.TimeoutError: _LOGGER.error("Timeout getting stream source") connection.send_error( msg["id"], "start_stream_failed", "Timeout getting stream source" ) @websocket_api.websocket_command( {vol.Required("type"): "camera/get_prefs", vol.Required("entity_id"): cv.entity_id} ) @websocket_api.async_response async def websocket_get_prefs( hass: HomeAssistant, connection: ActiveConnection, msg: dict ) -> None: """Handle request for account info.""" prefs = hass.data[DATA_CAMERA_PREFS].get(msg["entity_id"]) connection.send_result(msg["id"], prefs.as_dict()) @websocket_api.websocket_command( { vol.Required("type"): "camera/update_prefs", vol.Required("entity_id"): cv.entity_id, vol.Optional("preload_stream"): bool, } ) @websocket_api.async_response async def websocket_update_prefs( hass: HomeAssistant, connection: ActiveConnection, msg: dict ) -> None: """Handle request for account info.""" prefs = hass.data[DATA_CAMERA_PREFS] changes = dict(msg) changes.pop("id") changes.pop("type") entity_id = changes.pop("entity_id") await prefs.async_update(entity_id, **changes) connection.send_result(msg["id"], prefs.get(entity_id).as_dict()) async def async_handle_snapshot_service( camera: Camera, service_call: ServiceCall ) -> None: """Handle snapshot services calls.""" hass = camera.hass filename = service_call.data[ATTR_FILENAME] filename.hass = hass snapshot_file = filename.async_render(variables={ATTR_ENTITY_ID: camera}) # check if we allow to access to that file if not hass.config.is_allowed_path(snapshot_file): _LOGGER.error("Can't write %s, no access to path!", snapshot_file) return image = await camera.async_camera_image() def _write_image(to_file: str, image_data: bytes | None) -> None: """Executor helper to write image.""" if image_data is None: return if not os.path.exists(os.path.dirname(to_file)): os.makedirs(os.path.dirname(to_file), exist_ok=True) with open(to_file, "wb") as img_file: img_file.write(image_data) try: await hass.async_add_executor_job(_write_image, snapshot_file, image) except OSError as err: _LOGGER.error("Can't write image to file: %s", err) async def async_handle_play_stream_service( camera: Camera, service_call: ServiceCall ) -> None: """Handle play stream services calls.""" fmt = service_call.data[ATTR_FORMAT] url = await _async_stream_endpoint_url(camera.hass, camera, fmt) hass = camera.hass data: Mapping[str, str] = { ATTR_MEDIA_CONTENT_ID: f"{get_url(hass)}{url}", ATTR_MEDIA_CONTENT_TYPE: FORMAT_CONTENT_TYPE[fmt], } # It is required to send a different payload for cast media players entity_ids = service_call.data[ATTR_MEDIA_PLAYER] sources = entity_sources(hass) cast_entity_ids = [ entity for entity in entity_ids # All entities should be in sources. This extra guard is to # avoid people writing to the state machine and breaking it. if entity in sources and sources[entity]["domain"] == "cast" ] other_entity_ids = list(set(entity_ids) - set(cast_entity_ids)) if cast_entity_ids: await hass.services.async_call( DOMAIN_MP, SERVICE_PLAY_MEDIA, { ATTR_ENTITY_ID: cast_entity_ids, **data, ATTR_MEDIA_EXTRA: { "stream_type": "LIVE", "media_info": { "hlsVideoSegmentFormat": "fmp4", }, }, }, blocking=True, context=service_call.context, ) if other_entity_ids: await hass.services.async_call( DOMAIN_MP, SERVICE_PLAY_MEDIA, { ATTR_ENTITY_ID: other_entity_ids, **data, }, blocking=True, context=service_call.context, ) async def _async_stream_endpoint_url( hass: HomeAssistant, camera: Camera, fmt: str ) -> str: stream = await camera.create_stream() if not stream: raise HomeAssistantError( f"{camera.entity_id} does not support play stream service" ) # Update keepalive setting which manages idle shutdown camera_prefs = hass.data[DATA_CAMERA_PREFS].get(camera.entity_id) stream.keepalive = camera_prefs.preload_stream stream.add_provider(fmt) stream.start() return stream.endpoint_url(fmt) async def async_handle_record_service( camera: Camera, service_call: ServiceCall ) -> None: """Handle stream recording service calls.""" stream = await camera.create_stream() if not stream: raise HomeAssistantError(f"{camera.entity_id} does not support record service") hass = camera.hass filename = service_call.data[CONF_FILENAME] filename.hass = hass video_path = filename.async_render(variables={ATTR_ENTITY_ID: camera}) await stream.async_record( video_path, duration=service_call.data[CONF_DURATION], lookback=service_call.data[CONF_LOOKBACK], )
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/camera/__init__.py
"""Constants for the devolo_home_control integration.""" import re DOMAIN = "devolo_home_control" DEFAULT_MYDEVOLO = "https://www.mydevolo.com" PLATFORMS = ["binary_sensor", "climate", "cover", "light", "sensor", "switch"] CONF_MYDEVOLO = "mydevolo_url" GATEWAY_SERIAL_PATTERN = re.compile(r"\d{16}") SUPPORTED_MODEL_TYPES = ["2600", "2601"]
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/devolo_home_control/const.py
"""Flock platform for notify component.""" import asyncio import logging import async_timeout import voluptuous as vol from homeassistant.components.notify import PLATFORM_SCHEMA, BaseNotificationService from homeassistant.const import CONF_ACCESS_TOKEN, HTTP_OK from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) _RESOURCE = "https://api.flock.com/hooks/sendMessage/" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({vol.Required(CONF_ACCESS_TOKEN): cv.string}) async def async_get_service(hass, config, discovery_info=None): """Get the Flock notification service.""" access_token = config.get(CONF_ACCESS_TOKEN) url = f"{_RESOURCE}{access_token}" session = async_get_clientsession(hass) return FlockNotificationService(url, session) class FlockNotificationService(BaseNotificationService): """Implement the notification service for Flock.""" def __init__(self, url, session): """Initialize the Flock notification service.""" self._url = url self._session = session async def async_send_message(self, message, **kwargs): """Send the message to the user.""" payload = {"text": message} _LOGGER.debug("Attempting to call Flock at %s", self._url) try: with async_timeout.timeout(10): response = await self._session.post(self._url, json=payload) result = await response.json() if response.status != HTTP_OK or "error" in result: _LOGGER.error( "Flock service returned HTTP status %d, response %s", response.status, result, ) except asyncio.TimeoutError: _LOGGER.error("Timeout accessing Flock at %s", self._url)
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/flock/notify.py
"""Support for the yandex speechkit tts service.""" import asyncio import logging import aiohttp import async_timeout import voluptuous as vol from homeassistant.components.tts import CONF_LANG, PLATFORM_SCHEMA, Provider from homeassistant.const import CONF_API_KEY, HTTP_OK from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) YANDEX_API_URL = "https://tts.voicetech.yandex.net/generate?" SUPPORT_LANGUAGES = ["ru-RU", "en-US", "tr-TR", "uk-UK"] SUPPORT_CODECS = ["mp3", "wav", "opus"] SUPPORT_VOICES = [ "jane", "oksana", "alyss", "omazh", "zahar", "ermil", "levitan", "ermilov", "silaerkan", "kolya", "kostya", "nastya", "sasha", "nick", "erkanyavas", "zhenya", "tanya", "anton_samokhvalov", "tatyana_abramova", "voicesearch", "ermil_with_tuning", "robot", "dude", "zombie", "smoky", ] SUPPORTED_EMOTION = ["good", "evil", "neutral"] MIN_SPEED = 0.1 MAX_SPEED = 3 CONF_CODEC = "codec" CONF_VOICE = "voice" CONF_EMOTION = "emotion" CONF_SPEED = "speed" DEFAULT_LANG = "en-US" DEFAULT_CODEC = "mp3" DEFAULT_VOICE = "zahar" DEFAULT_EMOTION = "neutral" DEFAULT_SPEED = 1 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_API_KEY): cv.string, vol.Optional(CONF_LANG, default=DEFAULT_LANG): vol.In(SUPPORT_LANGUAGES), vol.Optional(CONF_CODEC, default=DEFAULT_CODEC): vol.In(SUPPORT_CODECS), vol.Optional(CONF_VOICE, default=DEFAULT_VOICE): vol.In(SUPPORT_VOICES), vol.Optional(CONF_EMOTION, default=DEFAULT_EMOTION): vol.In(SUPPORTED_EMOTION), vol.Optional(CONF_SPEED, default=DEFAULT_SPEED): vol.Range( min=MIN_SPEED, max=MAX_SPEED ), } ) SUPPORTED_OPTIONS = [CONF_CODEC, CONF_VOICE, CONF_EMOTION, CONF_SPEED] async def async_get_engine(hass, config, discovery_info=None): """Set up VoiceRSS speech component.""" return YandexSpeechKitProvider(hass, config) class YandexSpeechKitProvider(Provider): """VoiceRSS speech api provider.""" def __init__(self, hass, conf): """Init VoiceRSS TTS service.""" self.hass = hass self._codec = conf.get(CONF_CODEC) self._key = conf.get(CONF_API_KEY) self._speaker = conf.get(CONF_VOICE) self._language = conf.get(CONF_LANG) self._emotion = conf.get(CONF_EMOTION) self._speed = str(conf.get(CONF_SPEED)) self.name = "YandexTTS" @property def default_language(self): """Return the default language.""" return self._language @property def supported_languages(self): """Return list of supported languages.""" return SUPPORT_LANGUAGES @property def supported_options(self): """Return list of supported options.""" return SUPPORTED_OPTIONS async def async_get_tts_audio(self, message, language, options=None): """Load TTS from yandex.""" websession = async_get_clientsession(self.hass) actual_language = language options = options or {} try: with async_timeout.timeout(10): url_param = { "text": message, "lang": actual_language, "key": self._key, "speaker": options.get(CONF_VOICE, self._speaker), "format": options.get(CONF_CODEC, self._codec), "emotion": options.get(CONF_EMOTION, self._emotion), "speed": options.get(CONF_SPEED, self._speed), } request = await websession.get(YANDEX_API_URL, params=url_param) if request.status != HTTP_OK: _LOGGER.error( "Error %d on load URL %s", request.status, request.url ) return (None, None) data = await request.read() except (asyncio.TimeoutError, aiohttp.ClientError): _LOGGER.error("Timeout for yandex speech kit API") return (None, None) return (self._codec, data)
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/yandextts/tts.py
"""Config flow for AlarmDecoder.""" import logging from adext import AdExt from alarmdecoder.devices import SerialDevice, SocketDevice from alarmdecoder.util import NoDeviceError import voluptuous as vol from homeassistant import config_entries from homeassistant.components.binary_sensor import DEVICE_CLASSES from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PROTOCOL from homeassistant.core import callback from .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_DEVICE_BAUD, DEFAULT_DEVICE_HOST, DEFAULT_DEVICE_PATH, DEFAULT_DEVICE_PORT, DEFAULT_ZONE_OPTIONS, DEFAULT_ZONE_TYPE, DOMAIN, OPTIONS_ARM, OPTIONS_ZONES, PROTOCOL_SERIAL, PROTOCOL_SOCKET, ) EDIT_KEY = "edit_selection" EDIT_ZONES = "Zones" EDIT_SETTINGS = "Arming Settings" _LOGGER = logging.getLogger(__name__) class AlarmDecoderFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Handle a AlarmDecoder config flow.""" VERSION = 1 def __init__(self): """Initialize AlarmDecoder ConfigFlow.""" self.protocol = None @staticmethod @callback def async_get_options_flow(config_entry): """Get the options flow for AlarmDecoder.""" return AlarmDecoderOptionsFlowHandler(config_entry) async def async_step_user(self, user_input=None): """Handle a flow initialized by the user.""" if user_input is not None: self.protocol = user_input[CONF_PROTOCOL] return await self.async_step_protocol() return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Required(CONF_PROTOCOL): vol.In( [PROTOCOL_SOCKET, PROTOCOL_SERIAL] ), } ), ) async def async_step_protocol(self, user_input=None): """Handle AlarmDecoder protocol setup.""" errors = {} if user_input is not None: if _device_already_added( self._async_current_entries(), user_input, self.protocol ): return self.async_abort(reason="already_configured") connection = {} baud = None if self.protocol == PROTOCOL_SOCKET: host = connection[CONF_HOST] = user_input[CONF_HOST] port = connection[CONF_PORT] = user_input[CONF_PORT] title = f"{host}:{port}" device = SocketDevice(interface=(host, port)) if self.protocol == PROTOCOL_SERIAL: path = connection[CONF_DEVICE_PATH] = user_input[CONF_DEVICE_PATH] baud = connection[CONF_DEVICE_BAUD] = user_input[CONF_DEVICE_BAUD] title = path device = SerialDevice(interface=path) controller = AdExt(device) def test_connection(): controller.open(baud) controller.close() try: await self.hass.async_add_executor_job(test_connection) return self.async_create_entry( title=title, data={CONF_PROTOCOL: self.protocol, **connection} ) except NoDeviceError: errors["base"] = "cannot_connect" except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception during AlarmDecoder setup") errors["base"] = "unknown" if self.protocol == PROTOCOL_SOCKET: schema = vol.Schema( { vol.Required(CONF_HOST, default=DEFAULT_DEVICE_HOST): str, vol.Required(CONF_PORT, default=DEFAULT_DEVICE_PORT): int, } ) if self.protocol == PROTOCOL_SERIAL: schema = vol.Schema( { vol.Required(CONF_DEVICE_PATH, default=DEFAULT_DEVICE_PATH): str, vol.Required(CONF_DEVICE_BAUD, default=DEFAULT_DEVICE_BAUD): int, } ) return self.async_show_form( step_id="protocol", data_schema=schema, errors=errors, ) class AlarmDecoderOptionsFlowHandler(config_entries.OptionsFlow): """Handle AlarmDecoder options.""" def __init__(self, config_entry: config_entries.ConfigEntry) -> None: """Initialize AlarmDecoder options flow.""" self.arm_options = config_entry.options.get(OPTIONS_ARM, DEFAULT_ARM_OPTIONS) self.zone_options = config_entry.options.get( OPTIONS_ZONES, DEFAULT_ZONE_OPTIONS ) self.selected_zone = None async def async_step_init(self, user_input=None): """Manage the options.""" if user_input is not None: if user_input[EDIT_KEY] == EDIT_SETTINGS: return await self.async_step_arm_settings() if user_input[EDIT_KEY] == EDIT_ZONES: return await self.async_step_zone_select() return self.async_show_form( step_id="init", data_schema=vol.Schema( { vol.Required(EDIT_KEY, default=EDIT_SETTINGS): vol.In( [EDIT_SETTINGS, EDIT_ZONES] ) }, ), ) async def async_step_arm_settings(self, user_input=None): """Arming options form.""" if user_input is not None: return self.async_create_entry( title="", data={OPTIONS_ARM: user_input, OPTIONS_ZONES: self.zone_options}, ) return self.async_show_form( step_id="arm_settings", data_schema=vol.Schema( { vol.Optional( CONF_ALT_NIGHT_MODE, default=self.arm_options[CONF_ALT_NIGHT_MODE], ): bool, vol.Optional( CONF_AUTO_BYPASS, default=self.arm_options[CONF_AUTO_BYPASS] ): bool, vol.Optional( CONF_CODE_ARM_REQUIRED, default=self.arm_options[CONF_CODE_ARM_REQUIRED], ): bool, }, ), ) async def async_step_zone_select(self, user_input=None): """Zone selection form.""" errors = _validate_zone_input(user_input) if user_input is not None and not errors: self.selected_zone = str( int(user_input[CONF_ZONE_NUMBER]) ) # remove leading zeros return await self.async_step_zone_details() return self.async_show_form( step_id="zone_select", data_schema=vol.Schema({vol.Required(CONF_ZONE_NUMBER): str}), errors=errors, ) async def async_step_zone_details(self, user_input=None): """Zone details form.""" errors = _validate_zone_input(user_input) if user_input is not None and not errors: zone_options = self.zone_options.copy() zone_id = self.selected_zone zone_options[zone_id] = _fix_input_types(user_input) # Delete zone entry if zone_name is omitted if CONF_ZONE_NAME not in zone_options[zone_id]: zone_options.pop(zone_id) return self.async_create_entry( title="", data={OPTIONS_ARM: self.arm_options, OPTIONS_ZONES: zone_options}, ) existing_zone_settings = self.zone_options.get(self.selected_zone, {}) return self.async_show_form( step_id="zone_details", description_placeholders={CONF_ZONE_NUMBER: self.selected_zone}, data_schema=vol.Schema( { vol.Optional( CONF_ZONE_NAME, description={ "suggested_value": existing_zone_settings.get( CONF_ZONE_NAME ) }, ): str, vol.Optional( CONF_ZONE_TYPE, default=existing_zone_settings.get( CONF_ZONE_TYPE, DEFAULT_ZONE_TYPE ), ): vol.In(DEVICE_CLASSES), vol.Optional( CONF_ZONE_RFID, description={ "suggested_value": existing_zone_settings.get( CONF_ZONE_RFID ) }, ): str, vol.Optional( CONF_ZONE_LOOP, description={ "suggested_value": existing_zone_settings.get( CONF_ZONE_LOOP ) }, ): str, vol.Optional( CONF_RELAY_ADDR, description={ "suggested_value": existing_zone_settings.get( CONF_RELAY_ADDR ) }, ): str, vol.Optional( CONF_RELAY_CHAN, description={ "suggested_value": existing_zone_settings.get( CONF_RELAY_CHAN ) }, ): str, } ), errors=errors, ) def _validate_zone_input(zone_input): if not zone_input: return {} errors = {} # CONF_RELAY_ADDR & CONF_RELAY_CHAN are inclusive if (CONF_RELAY_ADDR in zone_input and CONF_RELAY_CHAN not in zone_input) or ( CONF_RELAY_ADDR not in zone_input and CONF_RELAY_CHAN in zone_input ): errors["base"] = "relay_inclusive" # The following keys must be int for key in [CONF_ZONE_NUMBER, CONF_ZONE_LOOP, CONF_RELAY_ADDR, CONF_RELAY_CHAN]: if key in zone_input: try: int(zone_input[key]) except ValueError: errors[key] = "int" # CONF_ZONE_LOOP depends on CONF_ZONE_RFID if CONF_ZONE_LOOP in zone_input and CONF_ZONE_RFID not in zone_input: errors[CONF_ZONE_LOOP] = "loop_rfid" # CONF_ZONE_LOOP must be 1-4 if ( CONF_ZONE_LOOP in zone_input and zone_input[CONF_ZONE_LOOP].isdigit() and int(zone_input[CONF_ZONE_LOOP]) not in list(range(1, 5)) ): errors[CONF_ZONE_LOOP] = "loop_range" return errors def _fix_input_types(zone_input): """Convert necessary keys to int. Since ConfigFlow inputs of type int cannot default to an empty string, we collect the values below as strings and then convert them to ints. """ for key in [CONF_ZONE_LOOP, CONF_RELAY_ADDR, CONF_RELAY_CHAN]: if key in zone_input: zone_input[key] = int(zone_input[key]) return zone_input def _device_already_added(current_entries, user_input, protocol): """Determine if entry has already been added to HA.""" user_host = user_input.get(CONF_HOST) user_port = user_input.get(CONF_PORT) user_path = user_input.get(CONF_DEVICE_PATH) user_baud = user_input.get(CONF_DEVICE_BAUD) for entry in current_entries: entry_host = entry.data.get(CONF_HOST) entry_port = entry.data.get(CONF_PORT) entry_path = entry.data.get(CONF_DEVICE_PATH) entry_baud = entry.data.get(CONF_DEVICE_BAUD) if ( protocol == PROTOCOL_SOCKET and user_host == entry_host and user_port == entry_port ): return True if ( protocol == PROTOCOL_SERIAL and user_baud == entry_baud and user_path == entry_path ): return True return False
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/alarmdecoder/config_flow.py
"""Config flow for Litter-Robot integration.""" import logging from pylitterbot.exceptions import LitterRobotException, LitterRobotLoginException import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from .const import DOMAIN from .hub import LitterRobotHub _LOGGER = logging.getLogger(__name__) STEP_USER_DATA_SCHEMA = vol.Schema( {vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str} ) class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Handle a config flow for Litter-Robot.""" VERSION = 1 async def async_step_user(self, user_input=None): """Handle the initial step.""" errors = {} if user_input is not None: self._async_abort_entries_match({CONF_USERNAME: user_input[CONF_USERNAME]}) hub = LitterRobotHub(self.hass, user_input) try: await hub.login() except LitterRobotLoginException: errors["base"] = "invalid_auth" except LitterRobotException: errors["base"] = "cannot_connect" except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" if not errors: return self.async_create_entry( title=user_input[CONF_USERNAME], data=user_input ) return self.async_show_form( step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors )
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/litterrobot/config_flow.py
"""API for Honeywell Lyric bound to Home Assistant OAuth.""" import logging from typing import cast from aiohttp import BasicAuth, ClientSession from aiolyric.client import LyricClient from homeassistant.helpers import config_entry_oauth2_flow from homeassistant.helpers.aiohttp_client import async_get_clientsession _LOGGER = logging.getLogger(__name__) class ConfigEntryLyricClient(LyricClient): """Provide Honeywell Lyric authentication tied to an OAuth2 based config entry.""" def __init__( self, websession: ClientSession, oauth_session: config_entry_oauth2_flow.OAuth2Session, ) -> None: """Initialize Honeywell Lyric auth.""" super().__init__(websession) self._oauth_session = oauth_session async def async_get_access_token(self): """Return a valid access token.""" if not self._oauth_session.valid_token: await self._oauth_session.async_ensure_token_valid() return self._oauth_session.token["access_token"] class LyricLocalOAuth2Implementation( config_entry_oauth2_flow.LocalOAuth2Implementation ): """Lyric Local OAuth2 implementation.""" async def _token_request(self, data: dict) -> dict: """Make a token request.""" session = async_get_clientsession(self.hass) data["client_id"] = self.client_id if self.client_secret is not None: data["client_secret"] = self.client_secret headers = { "Authorization": BasicAuth(self.client_id, self.client_secret).encode(), "Content-Type": "application/x-www-form-urlencoded", } resp = await session.post(self.token_url, headers=headers, data=data) resp.raise_for_status() return cast(dict, await resp.json())
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/lyric/api.py
"""Support for Vera thermostats.""" from __future__ import annotations from typing import Any import pyvera as veraApi from homeassistant.components.climate import ( DOMAIN as PLATFORM_DOMAIN, ENTITY_ID_FORMAT, ClimateEntity, ) from homeassistant.components.climate.const import ( FAN_AUTO, FAN_ON, HVAC_MODE_COOL, HVAC_MODE_HEAT, HVAC_MODE_HEAT_COOL, HVAC_MODE_OFF, SUPPORT_FAN_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.util import convert from . import VeraDevice from .common import ControllerData, get_controller_data FAN_OPERATION_LIST = [FAN_ON, FAN_AUTO] SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_FAN_MODE SUPPORT_HVAC = [HVAC_MODE_COOL, HVAC_MODE_HEAT, HVAC_MODE_HEAT_COOL, HVAC_MODE_OFF] async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up the sensor config entry.""" controller_data = get_controller_data(hass, entry) async_add_entities( [ VeraThermostat(device, controller_data) for device in controller_data.devices.get(PLATFORM_DOMAIN) ], True, ) class VeraThermostat(VeraDevice[veraApi.VeraThermostat], ClimateEntity): """Representation of a Vera Thermostat.""" def __init__( self, vera_device: veraApi.VeraThermostat, controller_data: ControllerData ) -> None: """Initialize the Vera device.""" VeraDevice.__init__(self, vera_device, controller_data) self.entity_id = ENTITY_ID_FORMAT.format(self.vera_id) @property def supported_features(self) -> int | None: """Return the list of supported features.""" return SUPPORT_FLAGS @property def hvac_mode(self) -> str: """Return hvac operation ie. heat, cool mode. Need to be one of HVAC_MODE_*. """ mode = self.vera_device.get_hvac_mode() if mode == "HeatOn": return HVAC_MODE_HEAT if mode == "CoolOn": return HVAC_MODE_COOL if mode == "AutoChangeOver": return HVAC_MODE_HEAT_COOL return HVAC_MODE_OFF @property def hvac_modes(self) -> list[str]: """Return the list of available hvac operation modes. Need to be a subset of HVAC_MODES. """ return SUPPORT_HVAC @property def fan_mode(self) -> str | None: """Return the fan setting.""" mode = self.vera_device.get_fan_mode() if mode == "ContinuousOn": return FAN_ON return FAN_AUTO @property def fan_modes(self) -> list[str] | None: """Return a list of available fan modes.""" return FAN_OPERATION_LIST def set_fan_mode(self, fan_mode) -> None: """Set new target temperature.""" if fan_mode == FAN_ON: self.vera_device.fan_on() else: self.vera_device.fan_auto() self.schedule_update_ha_state() @property def current_power_w(self) -> float | None: """Return the current power usage in W.""" power = self.vera_device.power if power: return convert(power, float, 0.0) @property def temperature_unit(self) -> str: """Return the unit of measurement.""" vera_temp_units = self.vera_device.vera_controller.temperature_units if vera_temp_units == "F": return TEMP_FAHRENHEIT return TEMP_CELSIUS @property def current_temperature(self) -> float | None: """Return the current temperature.""" return self.vera_device.get_current_temperature() @property def operation(self) -> str: """Return current operation ie. heat, cool, idle.""" return self.vera_device.get_hvac_mode() @property def target_temperature(self) -> float | None: """Return the temperature we try to reach.""" return self.vera_device.get_current_goal_temperature() def set_temperature(self, **kwargs: Any) -> None: """Set new target temperatures.""" if kwargs.get(ATTR_TEMPERATURE) is not None: self.vera_device.set_temperature(kwargs.get(ATTR_TEMPERATURE)) self.schedule_update_ha_state() def set_hvac_mode(self, hvac_mode) -> None: """Set new target hvac mode.""" if hvac_mode == HVAC_MODE_OFF: self.vera_device.turn_off() elif hvac_mode == HVAC_MODE_HEAT_COOL: self.vera_device.turn_auto_on() elif hvac_mode == HVAC_MODE_COOL: self.vera_device.turn_cool_on() elif hvac_mode == HVAC_MODE_HEAT: self.vera_device.turn_heat_on() self.schedule_update_ha_state()
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/vera/climate.py
"""This component provides HA sensor support for Ring Door Bell/Chimes.""" from homeassistant.components.sensor import SensorEntity from homeassistant.const import ( DEVICE_CLASS_TIMESTAMP, PERCENTAGE, SIGNAL_STRENGTH_DECIBELS_MILLIWATT, ) from homeassistant.core import callback from homeassistant.helpers.icon import icon_for_battery_level from . import DOMAIN from .entity import RingEntityMixin async def async_setup_entry(hass, config_entry, async_add_entities): """Set up a sensor for a Ring device.""" devices = hass.data[DOMAIN][config_entry.entry_id]["devices"] sensors = [] for device_type in ("chimes", "doorbots", "authorized_doorbots", "stickup_cams"): for sensor_type in SENSOR_TYPES: if device_type not in SENSOR_TYPES[sensor_type][1]: continue for device in devices[device_type]: if device_type == "battery" and device.battery_life is None: continue sensors.append( SENSOR_TYPES[sensor_type][6]( config_entry.entry_id, device, sensor_type ) ) async_add_entities(sensors) class RingSensor(RingEntityMixin, SensorEntity): """A sensor implementation for Ring device.""" def __init__(self, config_entry_id, device, sensor_type): """Initialize a sensor for Ring device.""" super().__init__(config_entry_id, device) self._sensor_type = sensor_type self._extra = None self._icon = f"mdi:{SENSOR_TYPES.get(sensor_type)[3]}" self._kind = SENSOR_TYPES.get(sensor_type)[4] self._name = f"{self._device.name} {SENSOR_TYPES.get(sensor_type)[0]}" self._unique_id = f"{device.id}-{sensor_type}" @property def should_poll(self): """Return False, updates are controlled via the hub.""" return False @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" if self._sensor_type == "volume": return self._device.volume if self._sensor_type == "battery": return self._device.battery_life @property def unique_id(self): """Return a unique ID.""" return self._unique_id @property def device_class(self): """Return sensor device class.""" return SENSOR_TYPES[self._sensor_type][5] @property def icon(self): """Icon to use in the frontend, if any.""" if self._sensor_type == "battery" and self._device.battery_life is not None: return icon_for_battery_level( battery_level=self._device.battery_life, charging=False ) return self._icon @property def unit_of_measurement(self): """Return the units of measurement.""" return SENSOR_TYPES.get(self._sensor_type)[2] class HealthDataRingSensor(RingSensor): """Ring sensor that relies on health data.""" async def async_added_to_hass(self): """Register callbacks.""" await super().async_added_to_hass() await self.ring_objects["health_data"].async_track_device( self._device, self._health_update_callback ) async def async_will_remove_from_hass(self): """Disconnect callbacks.""" await super().async_will_remove_from_hass() self.ring_objects["health_data"].async_untrack_device( self._device, self._health_update_callback ) @callback def _health_update_callback(self, _health_data): """Call update method.""" self.async_write_ha_state() @property def entity_registry_enabled_default(self) -> bool: """Return if the entity should be enabled when first added to the entity registry.""" # These sensors are data hungry and not useful. Disable by default. return False @property def state(self): """Return the state of the sensor.""" if self._sensor_type == "wifi_signal_category": return self._device.wifi_signal_category if self._sensor_type == "wifi_signal_strength": return self._device.wifi_signal_strength class HistoryRingSensor(RingSensor): """Ring sensor that relies on history data.""" _latest_event = None async def async_added_to_hass(self): """Register callbacks.""" await super().async_added_to_hass() await self.ring_objects["history_data"].async_track_device( self._device, self._history_update_callback ) async def async_will_remove_from_hass(self): """Disconnect callbacks.""" await super().async_will_remove_from_hass() self.ring_objects["history_data"].async_untrack_device( self._device, self._history_update_callback ) @callback def _history_update_callback(self, history_data): """Call update method.""" if not history_data: return found = None if self._kind is None: found = history_data[0] else: for entry in history_data: if entry["kind"] == self._kind: found = entry break if not found: return self._latest_event = found self.async_write_ha_state() @property def state(self): """Return the state of the sensor.""" if self._latest_event is None: return None return self._latest_event["created_at"].isoformat() @property def extra_state_attributes(self): """Return the state attributes.""" attrs = super().extra_state_attributes if self._latest_event: attrs["created_at"] = self._latest_event["created_at"] attrs["answered"] = self._latest_event["answered"] attrs["recording_status"] = self._latest_event["recording"]["status"] attrs["category"] = self._latest_event["kind"] return attrs # Sensor types: Name, category, units, icon, kind, device_class, class SENSOR_TYPES = { "battery": [ "Battery", ["doorbots", "authorized_doorbots", "stickup_cams"], PERCENTAGE, None, None, "battery", RingSensor, ], "last_activity": [ "Last Activity", ["doorbots", "authorized_doorbots", "stickup_cams"], None, "history", None, DEVICE_CLASS_TIMESTAMP, HistoryRingSensor, ], "last_ding": [ "Last Ding", ["doorbots", "authorized_doorbots"], None, "history", "ding", DEVICE_CLASS_TIMESTAMP, HistoryRingSensor, ], "last_motion": [ "Last Motion", ["doorbots", "authorized_doorbots", "stickup_cams"], None, "history", "motion", DEVICE_CLASS_TIMESTAMP, HistoryRingSensor, ], "volume": [ "Volume", ["chimes", "doorbots", "authorized_doorbots", "stickup_cams"], None, "bell-ring", None, None, RingSensor, ], "wifi_signal_category": [ "WiFi Signal Category", ["chimes", "doorbots", "authorized_doorbots", "stickup_cams"], None, "wifi", None, None, HealthDataRingSensor, ], "wifi_signal_strength": [ "WiFi Signal Strength", ["chimes", "doorbots", "authorized_doorbots", "stickup_cams"], SIGNAL_STRENGTH_DECIBELS_MILLIWATT, "wifi", None, "signal_strength", HealthDataRingSensor, ], }
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/ring/sensor.py
"""Constants for the Huisbaasje integration.""" from huisbaasje.const import ( SOURCE_TYPE_ELECTRICITY, SOURCE_TYPE_ELECTRICITY_IN, SOURCE_TYPE_ELECTRICITY_IN_LOW, SOURCE_TYPE_ELECTRICITY_OUT, SOURCE_TYPE_ELECTRICITY_OUT_LOW, SOURCE_TYPE_GAS, ) from homeassistant.const import ( DEVICE_CLASS_ENERGY, DEVICE_CLASS_POWER, ENERGY_KILO_WATT_HOUR, TIME_HOURS, VOLUME_CUBIC_METERS, ) DATA_COORDINATOR = "coordinator" DOMAIN = "huisbaasje" FLOW_CUBIC_METERS_PER_HOUR = f"{VOLUME_CUBIC_METERS}/{TIME_HOURS}" """Interval in seconds between polls to huisbaasje.""" POLLING_INTERVAL = 20 """Timeout for fetching sensor data""" FETCH_TIMEOUT = 10 SENSOR_TYPE_RATE = "rate" SENSOR_TYPE_THIS_DAY = "thisDay" SENSOR_TYPE_THIS_WEEK = "thisWeek" SENSOR_TYPE_THIS_MONTH = "thisMonth" SENSOR_TYPE_THIS_YEAR = "thisYear" SOURCE_TYPES = [ SOURCE_TYPE_ELECTRICITY, SOURCE_TYPE_ELECTRICITY_IN, SOURCE_TYPE_ELECTRICITY_IN_LOW, SOURCE_TYPE_ELECTRICITY_OUT, SOURCE_TYPE_ELECTRICITY_OUT_LOW, SOURCE_TYPE_GAS, ] SENSORS_INFO = [ { "name": "Huisbaasje Current Power", "device_class": DEVICE_CLASS_POWER, "source_type": SOURCE_TYPE_ELECTRICITY, }, { "name": "Huisbaasje Current Power In", "device_class": DEVICE_CLASS_POWER, "source_type": SOURCE_TYPE_ELECTRICITY_IN, }, { "name": "Huisbaasje Current Power In Low", "device_class": DEVICE_CLASS_POWER, "source_type": SOURCE_TYPE_ELECTRICITY_IN_LOW, }, { "name": "Huisbaasje Current Power Out", "device_class": DEVICE_CLASS_POWER, "source_type": SOURCE_TYPE_ELECTRICITY_OUT, }, { "name": "Huisbaasje Current Power Out Low", "device_class": DEVICE_CLASS_POWER, "source_type": SOURCE_TYPE_ELECTRICITY_OUT_LOW, }, { "name": "Huisbaasje Energy Today", "device_class": DEVICE_CLASS_ENERGY, "unit_of_measurement": ENERGY_KILO_WATT_HOUR, "source_type": SOURCE_TYPE_ELECTRICITY, "sensor_type": SENSOR_TYPE_THIS_DAY, "precision": 1, }, { "name": "Huisbaasje Energy This Week", "device_class": DEVICE_CLASS_ENERGY, "unit_of_measurement": ENERGY_KILO_WATT_HOUR, "source_type": SOURCE_TYPE_ELECTRICITY, "sensor_type": SENSOR_TYPE_THIS_WEEK, "precision": 1, }, { "name": "Huisbaasje Energy This Month", "device_class": DEVICE_CLASS_ENERGY, "unit_of_measurement": ENERGY_KILO_WATT_HOUR, "source_type": SOURCE_TYPE_ELECTRICITY, "sensor_type": SENSOR_TYPE_THIS_MONTH, "precision": 1, }, { "name": "Huisbaasje Energy This Year", "device_class": DEVICE_CLASS_ENERGY, "unit_of_measurement": ENERGY_KILO_WATT_HOUR, "source_type": SOURCE_TYPE_ELECTRICITY, "sensor_type": SENSOR_TYPE_THIS_YEAR, "precision": 1, }, { "name": "Huisbaasje Current Gas", "unit_of_measurement": FLOW_CUBIC_METERS_PER_HOUR, "source_type": SOURCE_TYPE_GAS, "icon": "mdi:fire", "precision": 1, }, { "name": "Huisbaasje Gas Today", "unit_of_measurement": VOLUME_CUBIC_METERS, "source_type": SOURCE_TYPE_GAS, "sensor_type": SENSOR_TYPE_THIS_DAY, "icon": "mdi:counter", "precision": 1, }, { "name": "Huisbaasje Gas This Week", "unit_of_measurement": VOLUME_CUBIC_METERS, "source_type": SOURCE_TYPE_GAS, "sensor_type": SENSOR_TYPE_THIS_WEEK, "icon": "mdi:counter", "precision": 1, }, { "name": "Huisbaasje Gas This Month", "unit_of_measurement": VOLUME_CUBIC_METERS, "source_type": SOURCE_TYPE_GAS, "sensor_type": SENSOR_TYPE_THIS_MONTH, "icon": "mdi:counter", "precision": 1, }, { "name": "Huisbaasje Gas This Year", "unit_of_measurement": VOLUME_CUBIC_METERS, "source_type": SOURCE_TYPE_GAS, "sensor_type": SENSOR_TYPE_THIS_YEAR, "icon": "mdi:counter", "precision": 1, }, ]
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/huisbaasje/const.py
"""Classes to help gather user submissions.""" from __future__ import annotations import abc import asyncio from collections.abc import Mapping from types import MappingProxyType from typing import Any, TypedDict import uuid import voluptuous as vol from .core import HomeAssistant, callback from .exceptions import HomeAssistantError RESULT_TYPE_FORM = "form" RESULT_TYPE_CREATE_ENTRY = "create_entry" RESULT_TYPE_ABORT = "abort" RESULT_TYPE_EXTERNAL_STEP = "external" RESULT_TYPE_EXTERNAL_STEP_DONE = "external_done" RESULT_TYPE_SHOW_PROGRESS = "progress" RESULT_TYPE_SHOW_PROGRESS_DONE = "progress_done" # Event that is fired when a flow is progressed via external or progress source. EVENT_DATA_ENTRY_FLOW_PROGRESSED = "data_entry_flow_progressed" class FlowError(HomeAssistantError): """Error while configuring an account.""" class UnknownHandler(FlowError): """Unknown handler specified.""" class UnknownFlow(FlowError): """Unknown flow specified.""" class UnknownStep(FlowError): """Unknown step specified.""" class AbortFlow(FlowError): """Exception to indicate a flow needs to be aborted.""" def __init__( self, reason: str, description_placeholders: dict | None = None ) -> None: """Initialize an abort flow exception.""" super().__init__(f"Flow aborted: {reason}") self.reason = reason self.description_placeholders = description_placeholders class FlowResult(TypedDict, total=False): """Typed result dict.""" version: int type: str flow_id: str handler: str title: str data: Mapping[str, Any] step_id: str data_schema: vol.Schema extra: str required: bool errors: dict[str, str] | None description: str | None description_placeholders: dict[str, Any] | None progress_action: str url: str reason: str context: dict[str, Any] result: Any last_step: bool | None options: Mapping[str, Any] class FlowManager(abc.ABC): """Manage all the flows that are in progress.""" def __init__( self, hass: HomeAssistant, ) -> None: """Initialize the flow manager.""" self.hass = hass self._initializing: dict[str, list[asyncio.Future]] = {} self._initialize_tasks: dict[str, list[asyncio.Task]] = {} self._progress: dict[str, Any] = {} async def async_wait_init_flow_finish(self, handler: str) -> None: """Wait till all flows in progress are initialized.""" current = self._initializing.get(handler) if not current: return await asyncio.wait(current) @abc.abstractmethod async def async_create_flow( self, handler_key: Any, *, context: dict[str, Any] | None = None, data: dict[str, Any] | None = None, ) -> FlowHandler: """Create a flow for specified handler. Handler key is the domain of the component that we want to set up. """ @abc.abstractmethod async def async_finish_flow( self, flow: FlowHandler, result: FlowResult ) -> FlowResult: """Finish a config flow and add an entry.""" async def async_post_init(self, flow: FlowHandler, result: FlowResult) -> None: """Entry has finished executing its first step asynchronously.""" @callback def async_progress(self, include_uninitialized: bool = False) -> list[FlowResult]: """Return the flows in progress.""" return [ { "flow_id": flow.flow_id, "handler": flow.handler, "context": flow.context, "step_id": flow.cur_step["step_id"] if flow.cur_step else None, } for flow in self._progress.values() if include_uninitialized or flow.cur_step is not None ] async def async_init( self, handler: str, *, context: dict[str, Any] | None = None, data: Any = None ) -> FlowResult: """Start a configuration flow.""" if context is None: context = {} init_done: asyncio.Future = asyncio.Future() self._initializing.setdefault(handler, []).append(init_done) task = asyncio.create_task(self._async_init(init_done, handler, context, data)) self._initialize_tasks.setdefault(handler, []).append(task) try: flow, result = await task finally: self._initialize_tasks[handler].remove(task) self._initializing[handler].remove(init_done) if result["type"] != RESULT_TYPE_ABORT: await self.async_post_init(flow, result) return result async def _async_init( self, init_done: asyncio.Future, handler: str, context: dict, data: Any, ) -> tuple[FlowHandler, FlowResult]: """Run the init in a task to allow it to be canceled at shutdown.""" flow = await self.async_create_flow(handler, context=context, data=data) if not flow: raise UnknownFlow("Flow was not created") flow.hass = self.hass flow.handler = handler flow.flow_id = uuid.uuid4().hex flow.context = context self._progress[flow.flow_id] = flow result = await self._async_handle_step(flow, flow.init_step, data, init_done) return flow, result async def async_shutdown(self) -> None: """Cancel any initializing flows.""" for task_list in self._initialize_tasks.values(): for task in task_list: task.cancel() async def async_configure( self, flow_id: str, user_input: dict | None = None ) -> FlowResult: """Continue a configuration flow.""" flow = self._progress.get(flow_id) if flow is None: raise UnknownFlow cur_step = flow.cur_step if cur_step.get("data_schema") is not None and user_input is not None: user_input = cur_step["data_schema"](user_input) result = await self._async_handle_step(flow, cur_step["step_id"], user_input) if cur_step["type"] in (RESULT_TYPE_EXTERNAL_STEP, RESULT_TYPE_SHOW_PROGRESS): if cur_step["type"] == RESULT_TYPE_EXTERNAL_STEP and result["type"] not in ( RESULT_TYPE_EXTERNAL_STEP, RESULT_TYPE_EXTERNAL_STEP_DONE, ): raise ValueError( "External step can only transition to " "external step or external step done." ) if cur_step["type"] == RESULT_TYPE_SHOW_PROGRESS and result["type"] not in ( RESULT_TYPE_SHOW_PROGRESS, RESULT_TYPE_SHOW_PROGRESS_DONE, ): raise ValueError( "Show progress can only transition to show progress or show progress done." ) # If the result has changed from last result, fire event to update # the frontend. if ( cur_step["step_id"] != result.get("step_id") or result["type"] == RESULT_TYPE_SHOW_PROGRESS ): # Tell frontend to reload the flow state. self.hass.bus.async_fire( EVENT_DATA_ENTRY_FLOW_PROGRESSED, {"handler": flow.handler, "flow_id": flow_id, "refresh": True}, ) return result @callback def async_abort(self, flow_id: str) -> None: """Abort a flow.""" if self._progress.pop(flow_id, None) is None: raise UnknownFlow async def _async_handle_step( self, flow: Any, step_id: str, user_input: dict | None, step_done: asyncio.Future | None = None, ) -> FlowResult: """Handle a step of a flow.""" method = f"async_step_{step_id}" if not hasattr(flow, method): self._progress.pop(flow.flow_id) if step_done: step_done.set_result(None) raise UnknownStep( f"Handler {flow.__class__.__name__} doesn't support step {step_id}" ) try: result: FlowResult = await getattr(flow, method)(user_input) except AbortFlow as err: result = _create_abort_data( flow.flow_id, flow.handler, err.reason, err.description_placeholders ) # Mark the step as done. # We do this before calling async_finish_flow because config entries will hit a # circular dependency where async_finish_flow sets up new entry, which needs the # integration to be set up, which is waiting for init to be done. if step_done: step_done.set_result(None) if result["type"] not in ( RESULT_TYPE_FORM, RESULT_TYPE_EXTERNAL_STEP, RESULT_TYPE_CREATE_ENTRY, RESULT_TYPE_ABORT, RESULT_TYPE_EXTERNAL_STEP_DONE, RESULT_TYPE_SHOW_PROGRESS, RESULT_TYPE_SHOW_PROGRESS_DONE, ): raise ValueError(f"Handler returned incorrect type: {result['type']}") if result["type"] in ( RESULT_TYPE_FORM, RESULT_TYPE_EXTERNAL_STEP, RESULT_TYPE_EXTERNAL_STEP_DONE, RESULT_TYPE_SHOW_PROGRESS, RESULT_TYPE_SHOW_PROGRESS_DONE, ): flow.cur_step = result return result # We pass a copy of the result because we're mutating our version result = await self.async_finish_flow(flow, result.copy()) # _async_finish_flow may change result type, check it again if result["type"] == RESULT_TYPE_FORM: flow.cur_step = result return result # Abort and Success results both finish the flow self._progress.pop(flow.flow_id) return result class FlowHandler: """Handle the configuration flow of a component.""" # Set by flow manager cur_step: dict[str, str] | None = None # While not purely typed, it makes typehinting more useful for us # and removes the need for constant None checks or asserts. flow_id: str = None # type: ignore hass: HomeAssistant = None # type: ignore handler: str = None # type: ignore # Ensure the attribute has a subscriptable, but immutable, default value. context: dict[str, Any] = MappingProxyType({}) # type: ignore # Set by _async_create_flow callback init_step = "init" # Set by developer VERSION = 1 @property def source(self) -> str | None: """Source that initialized the flow.""" if not hasattr(self, "context"): return None return self.context.get("source", None) @property def show_advanced_options(self) -> bool: """If we should show advanced options.""" if not hasattr(self, "context"): return False return self.context.get("show_advanced_options", False) @callback def async_show_form( self, *, step_id: str, data_schema: vol.Schema = None, errors: dict[str, str] | None = None, description_placeholders: dict[str, Any] | None = None, last_step: bool | None = None, ) -> FlowResult: """Return the definition of a form to gather user input.""" return { "type": RESULT_TYPE_FORM, "flow_id": self.flow_id, "handler": self.handler, "step_id": step_id, "data_schema": data_schema, "errors": errors, "description_placeholders": description_placeholders, "last_step": last_step, # Display next or submit button in frontend } @callback def async_create_entry( self, *, title: str, data: Mapping[str, Any], description: str | None = None, description_placeholders: dict | None = None, ) -> FlowResult: """Finish config flow and create a config entry.""" return { "version": self.VERSION, "type": RESULT_TYPE_CREATE_ENTRY, "flow_id": self.flow_id, "handler": self.handler, "title": title, "data": data, "description": description, "description_placeholders": description_placeholders, } @callback def async_abort( self, *, reason: str, description_placeholders: dict | None = None ) -> FlowResult: """Abort the config flow.""" return _create_abort_data( self.flow_id, self.handler, reason, description_placeholders ) @callback def async_external_step( self, *, step_id: str, url: str, description_placeholders: dict | None = None ) -> FlowResult: """Return the definition of an external step for the user to take.""" return { "type": RESULT_TYPE_EXTERNAL_STEP, "flow_id": self.flow_id, "handler": self.handler, "step_id": step_id, "url": url, "description_placeholders": description_placeholders, } @callback def async_external_step_done(self, *, next_step_id: str) -> FlowResult: """Return the definition of an external step for the user to take.""" return { "type": RESULT_TYPE_EXTERNAL_STEP_DONE, "flow_id": self.flow_id, "handler": self.handler, "step_id": next_step_id, } @callback def async_show_progress( self, *, step_id: str, progress_action: str, description_placeholders: dict | None = None, ) -> FlowResult: """Show a progress message to the user, without user input allowed.""" return { "type": RESULT_TYPE_SHOW_PROGRESS, "flow_id": self.flow_id, "handler": self.handler, "step_id": step_id, "progress_action": progress_action, "description_placeholders": description_placeholders, } @callback def async_show_progress_done(self, *, next_step_id: str) -> FlowResult: """Mark the progress done.""" return { "type": RESULT_TYPE_SHOW_PROGRESS_DONE, "flow_id": self.flow_id, "handler": self.handler, "step_id": next_step_id, } @callback def _create_abort_data( flow_id: str, handler: str, reason: str, description_placeholders: dict | None = None, ) -> FlowResult: """Return the definition of an external step for the user to take.""" return { "type": RESULT_TYPE_ABORT, "flow_id": flow_id, "handler": handler, "reason": reason, "description_placeholders": description_placeholders, }
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/data_entry_flow.py
"""Support for GPSLogger.""" from aiohttp import web import voluptuous as vol from homeassistant.components.device_tracker import ( ATTR_BATTERY, DOMAIN as DEVICE_TRACKER, ) from homeassistant.const import ( ATTR_LATITUDE, ATTR_LONGITUDE, CONF_WEBHOOK_ID, HTTP_OK, HTTP_UNPROCESSABLE_ENTITY, ) from homeassistant.helpers import config_entry_flow import homeassistant.helpers.config_validation as cv from homeassistant.helpers.dispatcher import async_dispatcher_send from .const import ( ATTR_ACCURACY, ATTR_ACTIVITY, ATTR_ALTITUDE, ATTR_DEVICE, ATTR_DIRECTION, ATTR_PROVIDER, ATTR_SPEED, DOMAIN, ) PLATFORMS = [DEVICE_TRACKER] TRACKER_UPDATE = f"{DOMAIN}_tracker_update" DEFAULT_ACCURACY = 200 DEFAULT_BATTERY = -1 def _id(value: str) -> str: """Coerce id by removing '-'.""" return value.replace("-", "") WEBHOOK_SCHEMA = vol.Schema( { vol.Required(ATTR_DEVICE): _id, vol.Required(ATTR_LATITUDE): cv.latitude, vol.Required(ATTR_LONGITUDE): cv.longitude, vol.Optional(ATTR_ACCURACY, default=DEFAULT_ACCURACY): vol.Coerce(float), vol.Optional(ATTR_ACTIVITY): cv.string, vol.Optional(ATTR_ALTITUDE): vol.Coerce(float), vol.Optional(ATTR_BATTERY, default=DEFAULT_BATTERY): vol.Coerce(float), vol.Optional(ATTR_DIRECTION): vol.Coerce(float), vol.Optional(ATTR_PROVIDER): cv.string, vol.Optional(ATTR_SPEED): vol.Coerce(float), } ) async def async_setup(hass, hass_config): """Set up the GPSLogger component.""" hass.data[DOMAIN] = {"devices": set(), "unsub_device_tracker": {}} return True async def handle_webhook(hass, webhook_id, request): """Handle incoming webhook with GPSLogger request.""" try: data = WEBHOOK_SCHEMA(dict(await request.post())) except vol.MultipleInvalid as error: return web.Response(text=error.error_message, status=HTTP_UNPROCESSABLE_ENTITY) attrs = { ATTR_SPEED: data.get(ATTR_SPEED), ATTR_DIRECTION: data.get(ATTR_DIRECTION), ATTR_ALTITUDE: data.get(ATTR_ALTITUDE), ATTR_PROVIDER: data.get(ATTR_PROVIDER), ATTR_ACTIVITY: data.get(ATTR_ACTIVITY), } device = data[ATTR_DEVICE] async_dispatcher_send( hass, TRACKER_UPDATE, device, (data[ATTR_LATITUDE], data[ATTR_LONGITUDE]), data[ATTR_BATTERY], data[ATTR_ACCURACY], attrs, ) return web.Response(text=f"Setting location for {device}", status=HTTP_OK) async def async_setup_entry(hass, entry): """Configure based on config entry.""" hass.components.webhook.async_register( DOMAIN, "GPSLogger", entry.data[CONF_WEBHOOK_ID], handle_webhook ) hass.config_entries.async_setup_platforms(entry, PLATFORMS) 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[DOMAIN]["unsub_device_tracker"].pop(entry.entry_id)() return await hass.config_entries.async_unload_platforms(entry, PLATFORMS) async_remove_entry = config_entry_flow.webhook_async_remove_entry
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/gpslogger/__init__.py
"""Twilio Call platform for notify component.""" import logging import urllib from twilio.base.exceptions import TwilioRestException import voluptuous as vol from homeassistant.components.notify import ( ATTR_TARGET, PLATFORM_SCHEMA, BaseNotificationService, ) from homeassistant.components.twilio import DATA_TWILIO import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_FROM_NUMBER = "from_number" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_FROM_NUMBER): vol.All( cv.string, vol.Match(r"^\+?[1-9]\d{1,14}$") ) } ) def get_service(hass, config, discovery_info=None): """Get the Twilio Call notification service.""" return TwilioCallNotificationService( hass.data[DATA_TWILIO], config[CONF_FROM_NUMBER] ) class TwilioCallNotificationService(BaseNotificationService): """Implement the notification service for the Twilio Call service.""" def __init__(self, twilio_client, from_number): """Initialize the service.""" self.client = twilio_client self.from_number = from_number def send_message(self, message="", **kwargs): """Call to specified target users.""" targets = kwargs.get(ATTR_TARGET) if not targets: _LOGGER.info("At least 1 target is required") return if message.startswith(("http://", "https://")): twimlet_url = message else: twimlet_url = "http://twimlets.com/message?Message=" twimlet_url += urllib.parse.quote(message, safe="") for target in targets: try: self.client.calls.create( to=target, url=twimlet_url, from_=self.from_number ) except TwilioRestException as exc: _LOGGER.error(exc)
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/twilio_call/notify.py
"""Support for Coinbase sensors.""" from homeassistant.components.sensor import SensorEntity from homeassistant.const import ATTR_ATTRIBUTION ATTR_NATIVE_BALANCE = "Balance in native currency" CURRENCY_ICONS = { "BTC": "mdi:currency-btc", "ETH": "mdi:currency-eth", "EUR": "mdi:currency-eur", "LTC": "mdi:litecoin", "USD": "mdi:currency-usd", } DEFAULT_COIN_ICON = "mdi:currency-usd-circle" ATTRIBUTION = "Data provided by coinbase.com" DATA_COINBASE = "coinbase_cache" def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Coinbase sensors.""" if discovery_info is None: return if "account" in discovery_info: account = discovery_info["account"] sensor = AccountSensor( hass.data[DATA_COINBASE], account["name"], account["balance"]["currency"] ) if "exchange_currency" in discovery_info: sensor = ExchangeRateSensor( hass.data[DATA_COINBASE], discovery_info["exchange_currency"], discovery_info["native_currency"], ) add_entities([sensor], True) class AccountSensor(SensorEntity): """Representation of a Coinbase.com sensor.""" def __init__(self, coinbase_data, name, currency): """Initialize the sensor.""" self._coinbase_data = coinbase_data self._name = f"Coinbase {name}" self._state = None self._unit_of_measurement = currency self._native_balance = None self._native_currency = None @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 unit_of_measurement(self): """Return the unit of measurement this sensor expresses itself in.""" return self._unit_of_measurement @property def icon(self): """Return the icon to use in the frontend, if any.""" return CURRENCY_ICONS.get(self._unit_of_measurement, DEFAULT_COIN_ICON) @property def extra_state_attributes(self): """Return the state attributes of the sensor.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, ATTR_NATIVE_BALANCE: f"{self._native_balance} {self._native_currency}", } def update(self): """Get the latest state of the sensor.""" self._coinbase_data.update() for account in self._coinbase_data.accounts: if self._name == f"Coinbase {account['name']}": self._state = account["balance"]["amount"] self._native_balance = account["native_balance"]["amount"] self._native_currency = account["native_balance"]["currency"] class ExchangeRateSensor(SensorEntity): """Representation of a Coinbase.com sensor.""" def __init__(self, coinbase_data, exchange_currency, native_currency): """Initialize the sensor.""" self._coinbase_data = coinbase_data self.currency = exchange_currency self._name = f"{exchange_currency} Exchange Rate" self._state = None self._unit_of_measurement = native_currency @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 unit_of_measurement(self): """Return the unit of measurement this sensor expresses itself in.""" return self._unit_of_measurement @property def icon(self): """Return the icon to use in the frontend, if any.""" return CURRENCY_ICONS.get(self.currency, DEFAULT_COIN_ICON) @property def extra_state_attributes(self): """Return the state attributes of the sensor.""" return {ATTR_ATTRIBUTION: ATTRIBUTION} def update(self): """Get the latest state of the sensor.""" self._coinbase_data.update() rate = self._coinbase_data.exchange_rates.rates[self.currency] self._state = round(1 / float(rate), 2)
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/coinbase/sensor.py
"""Config flow for Mikrotik.""" import voluptuous as vol from homeassistant import config_entries from homeassistant.const import ( CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_PORT, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import callback from .const import ( CONF_ARP_PING, CONF_DETECTION_TIME, CONF_FORCE_DHCP, DEFAULT_API_PORT, DEFAULT_DETECTION_TIME, DEFAULT_NAME, DOMAIN, ) from .errors import CannotConnect, LoginError from .hub import get_api class MikrotikFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Handle a Mikrotik config flow.""" VERSION = 1 @staticmethod @callback def async_get_options_flow(config_entry): """Get the options flow for this handler.""" return MikrotikOptionsFlowHandler(config_entry) async def async_step_user(self, user_input=None): """Handle a flow initialized by the user.""" errors = {} if user_input is not None: for entry in self._async_current_entries(): if entry.data[CONF_HOST] == user_input[CONF_HOST]: return self.async_abort(reason="already_configured") if entry.data[CONF_NAME] == user_input[CONF_NAME]: errors[CONF_NAME] = "name_exists" break try: await self.hass.async_add_executor_job(get_api, self.hass, user_input) except CannotConnect: errors["base"] = "cannot_connect" except LoginError: errors[CONF_USERNAME] = "invalid_auth" errors[CONF_PASSWORD] = "invalid_auth" if not errors: return self.async_create_entry( title=user_input[CONF_NAME], data=user_input ) return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Required(CONF_NAME, default=DEFAULT_NAME): str, vol.Required(CONF_HOST): str, vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str, vol.Optional(CONF_PORT, default=DEFAULT_API_PORT): int, vol.Optional(CONF_VERIFY_SSL, default=False): bool, } ), errors=errors, ) async def async_step_import(self, import_config): """Import Miktortik from config.""" import_config[CONF_DETECTION_TIME] = import_config[ CONF_DETECTION_TIME ].total_seconds() return await self.async_step_user(user_input=import_config) class MikrotikOptionsFlowHandler(config_entries.OptionsFlow): """Handle Mikrotik options.""" def __init__(self, config_entry): """Initialize Mikrotik options flow.""" self.config_entry = config_entry async def async_step_init(self, user_input=None): """Manage the Mikrotik options.""" return await self.async_step_device_tracker() async def async_step_device_tracker(self, user_input=None): """Manage the device tracker options.""" if user_input is not None: return self.async_create_entry(title="", data=user_input) options = { vol.Optional( CONF_FORCE_DHCP, default=self.config_entry.options.get(CONF_FORCE_DHCP, False), ): bool, vol.Optional( CONF_ARP_PING, default=self.config_entry.options.get(CONF_ARP_PING, False), ): bool, vol.Optional( CONF_DETECTION_TIME, default=self.config_entry.options.get( CONF_DETECTION_TIME, DEFAULT_DETECTION_TIME ), ): int, } return self.async_show_form( step_id="device_tracker", data_schema=vol.Schema(options) )
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/mikrotik/config_flow.py
"""Support for the PRT Heatmiser themostats using the V3 protocol.""" from __future__ import annotations import logging from heatmiserV3 import connection, heatmiser import voluptuous as vol from homeassistant.components.climate import ( HVAC_MODE_HEAT, HVAC_MODE_OFF, PLATFORM_SCHEMA, ClimateEntity, ) from homeassistant.components.climate.const import SUPPORT_TARGET_TEMPERATURE from homeassistant.const import ( ATTR_TEMPERATURE, CONF_HOST, CONF_ID, CONF_NAME, CONF_PORT, TEMP_CELSIUS, TEMP_FAHRENHEIT, ) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) CONF_THERMOSTATS = "tstats" TSTATS_SCHEMA = vol.Schema( vol.All( cv.ensure_list, [{vol.Required(CONF_ID): cv.positive_int, vol.Required(CONF_NAME): cv.string}], ) ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PORT): cv.string, vol.Optional(CONF_THERMOSTATS, default=[]): TSTATS_SCHEMA, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the heatmiser thermostat.""" heatmiser_v3_thermostat = heatmiser.HeatmiserThermostat host = config[CONF_HOST] port = config[CONF_PORT] thermostats = config[CONF_THERMOSTATS] uh1_hub = connection.HeatmiserUH1(host, port) add_entities( [ HeatmiserV3Thermostat(heatmiser_v3_thermostat, thermostat, uh1_hub) for thermostat in thermostats ], True, ) class HeatmiserV3Thermostat(ClimateEntity): """Representation of a HeatmiserV3 thermostat.""" def __init__(self, therm, device, uh1): """Initialize the thermostat.""" self.therm = therm(device[CONF_ID], "prt", uh1) self.uh1 = uh1 self._name = device[CONF_NAME] self._current_temperature = None self._target_temperature = None self._id = device self.dcb = None self._hvac_mode = HVAC_MODE_HEAT self._temperature_unit = None @property def supported_features(self): """Return the list of supported features.""" return SUPPORT_TARGET_TEMPERATURE @property def name(self): """Return the name of the thermostat, if any.""" return self._name @property def temperature_unit(self): """Return the unit of measurement which this thermostat uses.""" return self._temperature_unit @property def hvac_mode(self) -> str: """Return hvac operation ie. heat, cool mode. Need to be one of HVAC_MODE_*. """ return self._hvac_mode @property def hvac_modes(self) -> list[str]: """Return the list of available hvac operation modes. Need to be a subset of HVAC_MODES. """ return [HVAC_MODE_HEAT, HVAC_MODE_OFF] @property def current_temperature(self): """Return the current temperature.""" return self._current_temperature @property def target_temperature(self): """Return the temperature we try to reach.""" return self._target_temperature def set_temperature(self, **kwargs): """Set new target temperature.""" temperature = kwargs.get(ATTR_TEMPERATURE) self._target_temperature = int(temperature) self.therm.set_target_temp(self._target_temperature) def update(self): """Get the latest data.""" self.uh1.reopen() if not self.uh1.status: _LOGGER.error("Failed to update device %s", self._name) return self.dcb = self.therm.read_dcb() self._temperature_unit = ( TEMP_CELSIUS if (self.therm.get_temperature_format() == "C") else TEMP_FAHRENHEIT ) self._current_temperature = int(self.therm.get_floor_temp()) self._target_temperature = int(self.therm.get_target_temp()) self._hvac_mode = ( HVAC_MODE_OFF if (int(self.therm.get_current_state()) == 0) else HVAC_MODE_HEAT )
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/heatmiser/climate.py
"""Support for Ecovacs Deebot vacuums.""" import logging import random import string from sucks import EcoVacsAPI, VacBot import voluptuous as vol from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, EVENT_HOMEASSISTANT_STOP from homeassistant.helpers import discovery import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) DOMAIN = "ecovacs" CONF_COUNTRY = "country" CONF_CONTINENT = "continent" CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_COUNTRY): vol.All(vol.Lower, cv.string), vol.Required(CONF_CONTINENT): vol.All(vol.Lower, cv.string), } ) }, extra=vol.ALLOW_EXTRA, ) ECOVACS_DEVICES = "ecovacs_devices" # Generate a random device ID on each bootup ECOVACS_API_DEVICEID = "".join( random.choice(string.ascii_uppercase + string.digits) for _ in range(8) ) def setup(hass, config): """Set up the Ecovacs component.""" _LOGGER.debug("Creating new Ecovacs component") hass.data[ECOVACS_DEVICES] = [] ecovacs_api = EcoVacsAPI( ECOVACS_API_DEVICEID, config[DOMAIN].get(CONF_USERNAME), EcoVacsAPI.md5(config[DOMAIN].get(CONF_PASSWORD)), config[DOMAIN].get(CONF_COUNTRY), config[DOMAIN].get(CONF_CONTINENT), ) devices = ecovacs_api.devices() _LOGGER.debug("Ecobot devices: %s", devices) for device in devices: _LOGGER.info( "Discovered Ecovacs device on account: %s with nickname %s", device["did"], device["nick"], ) vacbot = VacBot( ecovacs_api.uid, ecovacs_api.REALM, ecovacs_api.resource, ecovacs_api.user_access_token, device, config[DOMAIN].get(CONF_CONTINENT).lower(), monitor=True, ) hass.data[ECOVACS_DEVICES].append(vacbot) def stop(event: object) -> None: """Shut down open connections to Ecovacs XMPP server.""" for device in hass.data[ECOVACS_DEVICES]: _LOGGER.info( "Shutting down connection to Ecovacs device %s", device.vacuum["did"] ) device.disconnect() # Listen for HA stop to disconnect. hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop) if hass.data[ECOVACS_DEVICES]: _LOGGER.debug("Starting vacuum components") discovery.load_platform(hass, "vacuum", DOMAIN, {}, config) return True
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/ecovacs/__init__.py
"""The Ruckus Unleashed integration.""" from pyruckus import Ruckus from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers import device_registry from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC from .const import ( API_AP, API_DEVICE_NAME, API_ID, API_MAC, API_MODEL, API_SYSTEM_OVERVIEW, API_VERSION, COORDINATOR, DOMAIN, MANUFACTURER, PLATFORMS, UNDO_UPDATE_LISTENERS, ) from .coordinator import RuckusUnleashedDataUpdateCoordinator async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Ruckus Unleashed from a config entry.""" try: ruckus = await hass.async_add_executor_job( Ruckus, entry.data[CONF_HOST], entry.data[CONF_USERNAME], entry.data[CONF_PASSWORD], ) except ConnectionError as error: raise ConfigEntryNotReady from error coordinator = RuckusUnleashedDataUpdateCoordinator(hass, ruckus=ruckus) await coordinator.async_config_entry_first_refresh() system_info = await hass.async_add_executor_job(ruckus.system_info) registry = await device_registry.async_get_registry(hass) ap_info = await hass.async_add_executor_job(ruckus.ap_info) for device in ap_info[API_AP][API_ID].values(): registry.async_get_or_create( config_entry_id=entry.entry_id, connections={(CONNECTION_NETWORK_MAC, device[API_MAC])}, identifiers={(CONNECTION_NETWORK_MAC, device[API_MAC])}, manufacturer=MANUFACTURER, name=device[API_DEVICE_NAME], model=device[API_MODEL], sw_version=system_info[API_SYSTEM_OVERVIEW][API_VERSION], ) hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = { COORDINATOR: coordinator, UNDO_UPDATE_LISTENERS: [], } hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) if unload_ok: for listener in hass.data[DOMAIN][entry.entry_id][UNDO_UPDATE_LISTENERS]: listener() hass.data[DOMAIN].pop(entry.entry_id) return unload_ok
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/ruckus_unleashed/__init__.py
"""Support for Neato Connected Vacuums.""" from datetime import timedelta import logging from pybotvac.exceptions import NeatoRobotException import voluptuous as vol from homeassistant.components.vacuum import ( ATTR_STATUS, STATE_CLEANING, STATE_DOCKED, STATE_ERROR, STATE_IDLE, STATE_PAUSED, STATE_RETURNING, SUPPORT_BATTERY, SUPPORT_CLEAN_SPOT, SUPPORT_LOCATE, SUPPORT_MAP, SUPPORT_PAUSE, SUPPORT_RETURN_HOME, SUPPORT_START, SUPPORT_STATE, SUPPORT_STOP, StateVacuumEntity, ) from homeassistant.const import ATTR_MODE from homeassistant.helpers import config_validation as cv, entity_platform from .const import ( ACTION, ALERTS, ERRORS, MODE, NEATO_DOMAIN, NEATO_LOGIN, NEATO_MAP_DATA, NEATO_PERSISTENT_MAPS, NEATO_ROBOTS, SCAN_INTERVAL_MINUTES, ) _LOGGER = logging.getLogger(__name__) SCAN_INTERVAL = timedelta(minutes=SCAN_INTERVAL_MINUTES) SUPPORT_NEATO = ( SUPPORT_BATTERY | SUPPORT_PAUSE | SUPPORT_RETURN_HOME | SUPPORT_STOP | SUPPORT_START | SUPPORT_CLEAN_SPOT | SUPPORT_STATE | SUPPORT_MAP | SUPPORT_LOCATE ) ATTR_CLEAN_START = "clean_start" ATTR_CLEAN_STOP = "clean_stop" ATTR_CLEAN_AREA = "clean_area" ATTR_CLEAN_BATTERY_START = "battery_level_at_clean_start" ATTR_CLEAN_BATTERY_END = "battery_level_at_clean_end" ATTR_CLEAN_SUSP_COUNT = "clean_suspension_count" ATTR_CLEAN_SUSP_TIME = "clean_suspension_time" ATTR_CLEAN_PAUSE_TIME = "clean_pause_time" ATTR_CLEAN_ERROR_TIME = "clean_error_time" ATTR_LAUNCHED_FROM = "launched_from" ATTR_NAVIGATION = "navigation" ATTR_CATEGORY = "category" ATTR_ZONE = "zone" async def async_setup_entry(hass, entry, async_add_entities): """Set up Neato vacuum with config entry.""" dev = [] neato = hass.data.get(NEATO_LOGIN) mapdata = hass.data.get(NEATO_MAP_DATA) persistent_maps = hass.data.get(NEATO_PERSISTENT_MAPS) for robot in hass.data[NEATO_ROBOTS]: dev.append(NeatoConnectedVacuum(neato, robot, mapdata, persistent_maps)) if not dev: return _LOGGER.debug("Adding vacuums %s", dev) async_add_entities(dev, True) platform = entity_platform.async_get_current_platform() assert platform is not None platform.async_register_entity_service( "custom_cleaning", { vol.Optional(ATTR_MODE, default=2): cv.positive_int, vol.Optional(ATTR_NAVIGATION, default=1): cv.positive_int, vol.Optional(ATTR_CATEGORY, default=4): cv.positive_int, vol.Optional(ATTR_ZONE): cv.string, }, "neato_custom_cleaning", ) class NeatoConnectedVacuum(StateVacuumEntity): """Representation of a Neato Connected Vacuum.""" def __init__(self, neato, robot, mapdata, persistent_maps): """Initialize the Neato Connected Vacuum.""" self.robot = robot self._available = neato is not None self._mapdata = mapdata self._name = f"{self.robot.name}" self._robot_has_map = self.robot.has_persistent_maps self._robot_maps = persistent_maps self._robot_serial = self.robot.serial self._status_state = None self._clean_state = None self._state = None self._clean_time_start = None self._clean_time_stop = None self._clean_area = None self._clean_battery_start = None self._clean_battery_end = None self._clean_susp_charge_count = None self._clean_susp_time = None self._clean_pause_time = None self._clean_error_time = None self._launched_from = None self._battery_level = None self._robot_boundaries = [] self._robot_stats = None def update(self): """Update the states of Neato Vacuums.""" _LOGGER.debug("Running Neato Vacuums update for '%s'", self.entity_id) try: if self._robot_stats is None: self._robot_stats = self.robot.get_general_info().json().get("data") except NeatoRobotException: _LOGGER.warning("Couldn't fetch robot information of %s", self.entity_id) try: self._state = self.robot.state except NeatoRobotException as ex: if self._available: # print only once when available _LOGGER.error( "Neato vacuum connection error for '%s': %s", self.entity_id, ex ) self._state = None self._available = False return self._available = True _LOGGER.debug("self._state=%s", self._state) if "alert" in self._state: robot_alert = ALERTS.get(self._state["alert"]) else: robot_alert = None if self._state["state"] == 1: if self._state["details"]["isCharging"]: self._clean_state = STATE_DOCKED self._status_state = "Charging" elif ( self._state["details"]["isDocked"] and not self._state["details"]["isCharging"] ): self._clean_state = STATE_DOCKED self._status_state = "Docked" else: self._clean_state = STATE_IDLE self._status_state = "Stopped" if robot_alert is not None: self._status_state = robot_alert elif self._state["state"] == 2: if robot_alert is None: self._clean_state = STATE_CLEANING self._status_state = ( f"{MODE.get(self._state['cleaning']['mode'])} " f"{ACTION.get(self._state['action'])}" ) if ( "boundary" in self._state["cleaning"] and "name" in self._state["cleaning"]["boundary"] ): self._status_state += ( f" {self._state['cleaning']['boundary']['name']}" ) else: self._status_state = robot_alert elif self._state["state"] == 3: self._clean_state = STATE_PAUSED self._status_state = "Paused" elif self._state["state"] == 4: self._clean_state = STATE_ERROR self._status_state = ERRORS.get(self._state["error"]) self._battery_level = self._state["details"]["charge"] if not self._mapdata.get(self._robot_serial, {}).get("maps", []): return mapdata = self._mapdata[self._robot_serial]["maps"][0] self._clean_time_start = mapdata["start_at"] self._clean_time_stop = mapdata["end_at"] self._clean_area = mapdata["cleaned_area"] self._clean_susp_charge_count = mapdata["suspended_cleaning_charging_count"] self._clean_susp_time = mapdata["time_in_suspended_cleaning"] self._clean_pause_time = mapdata["time_in_pause"] self._clean_error_time = mapdata["time_in_error"] self._clean_battery_start = mapdata["run_charge_at_start"] self._clean_battery_end = mapdata["run_charge_at_end"] self._launched_from = mapdata["launched_from"] if ( self._robot_has_map and self._state["availableServices"]["maps"] != "basic-1" and self._robot_maps[self._robot_serial] ): allmaps = self._robot_maps[self._robot_serial] _LOGGER.debug( "Found the following maps for '%s': %s", self.entity_id, allmaps ) self._robot_boundaries = [] # Reset boundaries before refreshing boundaries for maps in allmaps: try: robot_boundaries = self.robot.get_map_boundaries(maps["id"]).json() except NeatoRobotException as ex: _LOGGER.error( "Could not fetch map boundaries for '%s': %s", self.entity_id, ex, ) return _LOGGER.debug( "Boundaries for robot '%s' in map '%s': %s", self.entity_id, maps["name"], robot_boundaries, ) if "boundaries" in robot_boundaries["data"]: self._robot_boundaries += robot_boundaries["data"]["boundaries"] _LOGGER.debug( "List of boundaries for '%s': %s", self.entity_id, self._robot_boundaries, ) @property def name(self): """Return the name of the device.""" return self._name @property def supported_features(self): """Flag vacuum cleaner robot features that are supported.""" return SUPPORT_NEATO @property def battery_level(self): """Return the battery level of the vacuum cleaner.""" return self._battery_level @property def available(self): """Return if the robot is available.""" return self._available @property def icon(self): """Return neato specific icon.""" return "mdi:robot-vacuum-variant" @property def state(self): """Return the status of the vacuum cleaner.""" return self._clean_state @property def unique_id(self): """Return a unique ID.""" return self._robot_serial @property def extra_state_attributes(self): """Return the state attributes of the vacuum cleaner.""" data = {} if self._status_state is not None: data[ATTR_STATUS] = self._status_state if self._clean_time_start is not None: data[ATTR_CLEAN_START] = self._clean_time_start if self._clean_time_stop is not None: data[ATTR_CLEAN_STOP] = self._clean_time_stop if self._clean_area is not None: data[ATTR_CLEAN_AREA] = self._clean_area if self._clean_susp_charge_count is not None: data[ATTR_CLEAN_SUSP_COUNT] = self._clean_susp_charge_count if self._clean_susp_time is not None: data[ATTR_CLEAN_SUSP_TIME] = self._clean_susp_time if self._clean_pause_time is not None: data[ATTR_CLEAN_PAUSE_TIME] = self._clean_pause_time if self._clean_error_time is not None: data[ATTR_CLEAN_ERROR_TIME] = self._clean_error_time if self._clean_battery_start is not None: data[ATTR_CLEAN_BATTERY_START] = self._clean_battery_start if self._clean_battery_end is not None: data[ATTR_CLEAN_BATTERY_END] = self._clean_battery_end if self._launched_from is not None: data[ATTR_LAUNCHED_FROM] = self._launched_from return data @property def device_info(self): """Device info for neato robot.""" info = {"identifiers": {(NEATO_DOMAIN, self._robot_serial)}, "name": self._name} if self._robot_stats: info["manufacturer"] = self._robot_stats["battery"]["vendor"] info["model"] = self._robot_stats["model"] info["sw_version"] = self._robot_stats["firmware"] return info def start(self): """Start cleaning or resume cleaning.""" try: if self._state["state"] == 1: self.robot.start_cleaning() elif self._state["state"] == 3: self.robot.resume_cleaning() except NeatoRobotException as ex: _LOGGER.error( "Neato vacuum connection error for '%s': %s", self.entity_id, ex ) def pause(self): """Pause the vacuum.""" try: self.robot.pause_cleaning() except NeatoRobotException as ex: _LOGGER.error( "Neato vacuum connection error for '%s': %s", self.entity_id, ex ) def return_to_base(self, **kwargs): """Set the vacuum cleaner to return to the dock.""" try: if self._clean_state == STATE_CLEANING: self.robot.pause_cleaning() self._clean_state = STATE_RETURNING self.robot.send_to_base() except NeatoRobotException as ex: _LOGGER.error( "Neato vacuum connection error for '%s': %s", self.entity_id, ex ) def stop(self, **kwargs): """Stop the vacuum cleaner.""" try: self.robot.stop_cleaning() except NeatoRobotException as ex: _LOGGER.error( "Neato vacuum connection error for '%s': %s", self.entity_id, ex ) def locate(self, **kwargs): """Locate the robot by making it emit a sound.""" try: self.robot.locate() except NeatoRobotException as ex: _LOGGER.error( "Neato vacuum connection error for '%s': %s", self.entity_id, ex ) def clean_spot(self, **kwargs): """Run a spot cleaning starting from the base.""" try: self.robot.start_spot_cleaning() except NeatoRobotException as ex: _LOGGER.error( "Neato vacuum connection error for '%s': %s", self.entity_id, ex ) def neato_custom_cleaning(self, mode, navigation, category, zone=None): """Zone cleaning service call.""" boundary_id = None if zone is not None: for boundary in self._robot_boundaries: if zone in boundary["name"]: boundary_id = boundary["id"] if boundary_id is None: _LOGGER.error( "Zone '%s' was not found for the robot '%s'", zone, self.entity_id ) return _LOGGER.info("Start cleaning zone '%s' with robot %s", zone, self.entity_id) self._clean_state = STATE_CLEANING try: self.robot.start_cleaning(mode, navigation, category, boundary_id) except NeatoRobotException as ex: _LOGGER.error( "Neato vacuum connection error for '%s': %s", self.entity_id, ex )
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/neato/vacuum.py
"""Support for Netgear LTE modems.""" import asyncio from datetime import timedelta import logging import aiohttp import attr import eternalegypt import voluptuous as vol from homeassistant.components.binary_sensor import DOMAIN as BINARY_SENSOR_DOMAIN from homeassistant.components.notify import DOMAIN as NOTIFY_DOMAIN from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.const import ( CONF_HOST, CONF_MONITORED_CONDITIONS, CONF_NAME, CONF_PASSWORD, CONF_RECIPIENT, EVENT_HOMEASSISTANT_STOP, ) from homeassistant.core import callback from homeassistant.helpers import config_validation as cv, discovery from homeassistant.helpers.aiohttp_client import async_create_clientsession from homeassistant.helpers.dispatcher import ( async_dispatcher_connect, async_dispatcher_send, ) from homeassistant.helpers.entity import Entity from homeassistant.helpers.event import async_track_time_interval from . import sensor_types _LOGGER = logging.getLogger(__name__) SCAN_INTERVAL = timedelta(seconds=10) DISPATCHER_NETGEAR_LTE = "netgear_lte_update" DOMAIN = "netgear_lte" DATA_KEY = "netgear_lte" EVENT_SMS = "netgear_lte_sms" SERVICE_DELETE_SMS = "delete_sms" SERVICE_SET_OPTION = "set_option" SERVICE_CONNECT_LTE = "connect_lte" SERVICE_DISCONNECT_LTE = "disconnect_lte" ATTR_HOST = "host" ATTR_SMS_ID = "sms_id" ATTR_FROM = "from" ATTR_MESSAGE = "message" ATTR_FAILOVER = "failover" ATTR_AUTOCONNECT = "autoconnect" FAILOVER_MODES = ["auto", "wire", "mobile"] AUTOCONNECT_MODES = ["never", "home", "always"] NOTIFY_SCHEMA = vol.Schema( { vol.Optional(CONF_NAME, default=DOMAIN): cv.string, vol.Optional(CONF_RECIPIENT, default=[]): vol.All(cv.ensure_list, [cv.string]), } ) SENSOR_SCHEMA = vol.Schema( { vol.Optional( CONF_MONITORED_CONDITIONS, default=sensor_types.DEFAULT_SENSORS ): vol.All(cv.ensure_list, [vol.In(sensor_types.ALL_SENSORS)]) } ) BINARY_SENSOR_SCHEMA = vol.Schema( { vol.Optional( CONF_MONITORED_CONDITIONS, default=sensor_types.DEFAULT_BINARY_SENSORS ): vol.All(cv.ensure_list, [vol.In(sensor_types.ALL_BINARY_SENSORS)]) } ) CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.All( cv.ensure_list, [ vol.Schema( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(NOTIFY_DOMAIN, default={}): vol.All( cv.ensure_list, [NOTIFY_SCHEMA] ), vol.Optional(SENSOR_DOMAIN, default={}): SENSOR_SCHEMA, vol.Optional( BINARY_SENSOR_DOMAIN, default={} ): BINARY_SENSOR_SCHEMA, } ) ], ) }, extra=vol.ALLOW_EXTRA, ) DELETE_SMS_SCHEMA = vol.Schema( { vol.Optional(ATTR_HOST): cv.string, vol.Required(ATTR_SMS_ID): vol.All(cv.ensure_list, [cv.positive_int]), } ) SET_OPTION_SCHEMA = vol.Schema( vol.All( cv.has_at_least_one_key(ATTR_FAILOVER, ATTR_AUTOCONNECT), { vol.Optional(ATTR_HOST): cv.string, vol.Optional(ATTR_FAILOVER): vol.In(FAILOVER_MODES), vol.Optional(ATTR_AUTOCONNECT): vol.In(AUTOCONNECT_MODES), }, ) ) CONNECT_LTE_SCHEMA = vol.Schema({vol.Optional(ATTR_HOST): cv.string}) DISCONNECT_LTE_SCHEMA = vol.Schema({vol.Optional(ATTR_HOST): cv.string}) @attr.s class ModemData: """Class for modem state.""" hass = attr.ib() host = attr.ib() modem = attr.ib() data = attr.ib(init=False, default=None) connected = attr.ib(init=False, default=True) async def async_update(self): """Call the API to update the data.""" try: self.data = await self.modem.information() if not self.connected: _LOGGER.warning("Connected to %s", self.host) self.connected = True except eternalegypt.Error: if self.connected: _LOGGER.warning("Lost connection to %s", self.host) self.connected = False self.data = None async_dispatcher_send(self.hass, DISPATCHER_NETGEAR_LTE) @attr.s class LTEData: """Shared state.""" websession = attr.ib() modem_data = attr.ib(init=False, factory=dict) def get_modem_data(self, config): """Get modem_data for the host in config.""" if config[CONF_HOST] is not None: return self.modem_data.get(config[CONF_HOST]) if len(self.modem_data) != 1: return None return next(iter(self.modem_data.values())) async def async_setup(hass, config): """Set up Netgear LTE component.""" if DATA_KEY not in hass.data: websession = async_create_clientsession( hass, cookie_jar=aiohttp.CookieJar(unsafe=True) ) hass.data[DATA_KEY] = LTEData(websession) async def service_handler(service): """Apply a service.""" host = service.data.get(ATTR_HOST) conf = {CONF_HOST: host} modem_data = hass.data[DATA_KEY].get_modem_data(conf) if not modem_data: _LOGGER.error("%s: host %s unavailable", service.service, host) return if service.service == SERVICE_DELETE_SMS: for sms_id in service.data[ATTR_SMS_ID]: await modem_data.modem.delete_sms(sms_id) elif service.service == SERVICE_SET_OPTION: failover = service.data.get(ATTR_FAILOVER) if failover: await modem_data.modem.set_failover_mode(failover) autoconnect = service.data.get(ATTR_AUTOCONNECT) if autoconnect: await modem_data.modem.set_autoconnect_mode(autoconnect) elif service.service == SERVICE_CONNECT_LTE: await modem_data.modem.connect_lte() elif service.service == SERVICE_DISCONNECT_LTE: await modem_data.modem.disconnect_lte() service_schemas = { SERVICE_DELETE_SMS: DELETE_SMS_SCHEMA, SERVICE_SET_OPTION: SET_OPTION_SCHEMA, SERVICE_CONNECT_LTE: CONNECT_LTE_SCHEMA, SERVICE_DISCONNECT_LTE: DISCONNECT_LTE_SCHEMA, } for service, schema in service_schemas.items(): hass.services.async_register( DOMAIN, service, service_handler, schema=schema ) netgear_lte_config = config[DOMAIN] # Set up each modem tasks = [_setup_lte(hass, lte_conf) for lte_conf in netgear_lte_config] await asyncio.wait(tasks) # Load platforms for each modem for lte_conf in netgear_lte_config: # Notify for notify_conf in lte_conf[NOTIFY_DOMAIN]: discovery_info = { CONF_HOST: lte_conf[CONF_HOST], CONF_NAME: notify_conf.get(CONF_NAME), NOTIFY_DOMAIN: notify_conf, } hass.async_create_task( discovery.async_load_platform( hass, NOTIFY_DOMAIN, DOMAIN, discovery_info, config ) ) # Sensor sensor_conf = lte_conf.get(SENSOR_DOMAIN) discovery_info = {CONF_HOST: lte_conf[CONF_HOST], SENSOR_DOMAIN: sensor_conf} hass.async_create_task( discovery.async_load_platform( hass, SENSOR_DOMAIN, DOMAIN, discovery_info, config ) ) # Binary Sensor binary_sensor_conf = lte_conf.get(BINARY_SENSOR_DOMAIN) discovery_info = { CONF_HOST: lte_conf[CONF_HOST], BINARY_SENSOR_DOMAIN: binary_sensor_conf, } hass.async_create_task( discovery.async_load_platform( hass, BINARY_SENSOR_DOMAIN, DOMAIN, discovery_info, config ) ) return True async def _setup_lte(hass, lte_config): """Set up a Netgear LTE modem.""" host = lte_config[CONF_HOST] password = lte_config[CONF_PASSWORD] websession = hass.data[DATA_KEY].websession modem = eternalegypt.Modem(hostname=host, websession=websession) modem_data = ModemData(hass, host, modem) try: await _login(hass, modem_data, password) except eternalegypt.Error: retry_task = hass.loop.create_task(_retry_login(hass, modem_data, password)) @callback def cleanup_retry(event): """Clean up retry task resources.""" if not retry_task.done(): retry_task.cancel() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, cleanup_retry) async def _login(hass, modem_data, password): """Log in and complete setup.""" await modem_data.modem.login(password=password) def fire_sms_event(sms): """Send an SMS event.""" data = { ATTR_HOST: modem_data.host, ATTR_SMS_ID: sms.id, ATTR_FROM: sms.sender, ATTR_MESSAGE: sms.message, } hass.bus.async_fire(EVENT_SMS, data) await modem_data.modem.add_sms_listener(fire_sms_event) await modem_data.async_update() hass.data[DATA_KEY].modem_data[modem_data.host] = modem_data async def _update(now): """Periodic update.""" await modem_data.async_update() update_unsub = async_track_time_interval(hass, _update, SCAN_INTERVAL) async def cleanup(event): """Clean up resources.""" update_unsub() await modem_data.modem.logout() del hass.data[DATA_KEY].modem_data[modem_data.host] hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, cleanup) async def _retry_login(hass, modem_data, password): """Sleep and retry setup.""" _LOGGER.warning("Could not connect to %s. Will keep trying", modem_data.host) modem_data.connected = False delay = 15 while not modem_data.connected: await asyncio.sleep(delay) try: await _login(hass, modem_data, password) except eternalegypt.Error: delay = min(2 * delay, 300) @attr.s class LTEEntity(Entity): """Base LTE entity.""" modem_data = attr.ib() sensor_type = attr.ib() _unique_id = attr.ib(init=False) @_unique_id.default def _init_unique_id(self): """Register unique_id while we know data is valid.""" return f"{self.sensor_type}_{self.modem_data.data.serial_number}" async def async_added_to_hass(self): """Register callback.""" self.async_on_remove( async_dispatcher_connect( self.hass, DISPATCHER_NETGEAR_LTE, self.async_write_ha_state ) ) async def async_update(self): """Force update of state.""" await self.modem_data.async_update() @property def should_poll(self): """Return that the sensor should not be polled.""" return False @property def available(self): """Return the availability of the sensor.""" return self.modem_data.data is not None @property def unique_id(self): """Return a unique ID like 'usage_5TG365AB0078V'.""" return self._unique_id @property def name(self): """Return the name of the sensor.""" return f"Netgear LTE {self.sensor_type}"
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/netgear_lte/__init__.py
"""Support for monitoring the Syncthing instance.""" import logging import aiosyncthing from homeassistant.components.sensor import SensorEntity from homeassistant.core import callback from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.event import async_track_time_interval from .const import ( DOMAIN, FOLDER_PAUSED_RECEIVED, FOLDER_SENSOR_ALERT_ICON, FOLDER_SENSOR_DEFAULT_ICON, FOLDER_SENSOR_ICONS, FOLDER_SUMMARY_RECEIVED, SCAN_INTERVAL, SERVER_AVAILABLE, SERVER_UNAVAILABLE, STATE_CHANGED_RECEIVED, ) _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Syncthing sensors.""" syncthing = hass.data[DOMAIN][config_entry.entry_id] try: config = await syncthing.system.config() version = await syncthing.system.version() except aiosyncthing.exceptions.SyncthingError as exception: raise PlatformNotReady from exception server_id = syncthing.server_id entities = [ FolderSensor( syncthing, server_id, folder["id"], folder["label"], version["version"], ) for folder in config["folders"] ] async_add_entities(entities) class FolderSensor(SensorEntity): """A Syncthing folder sensor.""" STATE_ATTRIBUTES = { "errors": "errors", "globalBytes": "global_bytes", "globalDeleted": "global_deleted", "globalDirectories": "global_directories", "globalFiles": "global_files", "globalSymlinks": "global_symlinks", "globalTotalItems": "global_total_items", "ignorePatterns": "ignore_patterns", "inSyncBytes": "in_sync_bytes", "inSyncFiles": "in_sync_files", "invalid": "invalid", "localBytes": "local_bytes", "localDeleted": "local_deleted", "localDirectories": "local_directories", "localFiles": "local_files", "localSymlinks": "local_symlinks", "localTotalItems": "local_total_items", "needBytes": "need_bytes", "needDeletes": "need_deletes", "needDirectories": "need_directories", "needFiles": "need_files", "needSymlinks": "need_symlinks", "needTotalItems": "need_total_items", "pullErrors": "pull_errors", "state": "state", } def __init__(self, syncthing, server_id, folder_id, folder_label, version): """Initialize the sensor.""" self._syncthing = syncthing self._server_id = server_id self._folder_id = folder_id self._folder_label = folder_label self._state = None self._unsub_timer = None self._version = version self._short_server_id = server_id.split("-")[0] @property def name(self): """Return the name of the sensor.""" return f"{self._short_server_id} {self._folder_id} {self._folder_label}" @property def unique_id(self): """Return the unique id of the entity.""" return f"{self._short_server_id}-{self._folder_id}" @property def state(self): """Return the state of the sensor.""" return self._state["state"] @property def available(self): """Could the device be accessed during the last update call.""" return self._state is not None @property def icon(self): """Return the icon for this sensor.""" if self._state is None: return FOLDER_SENSOR_DEFAULT_ICON if self.state in FOLDER_SENSOR_ICONS: return FOLDER_SENSOR_ICONS[self.state] return FOLDER_SENSOR_ALERT_ICON @property def extra_state_attributes(self): """Return the state attributes.""" return self._state @property def should_poll(self): """Return the polling requirement for this sensor.""" return False @property def device_info(self): """Return device information.""" return { "identifiers": {(DOMAIN, self._server_id)}, "name": f"Syncthing ({self._syncthing.url})", "manufacturer": "Syncthing Team", "sw_version": self._version, "entry_type": "service", } async def async_update_status(self): """Request folder status and update state.""" try: state = await self._syncthing.database.status(self._folder_id) except aiosyncthing.exceptions.SyncthingError: self._state = None else: self._state = self._filter_state(state) self.async_write_ha_state() def subscribe(self): """Start polling syncthing folder status.""" if self._unsub_timer is None: async def refresh(event_time): """Get the latest data from Syncthing.""" await self.async_update_status() self._unsub_timer = async_track_time_interval( self.hass, refresh, SCAN_INTERVAL ) @callback def unsubscribe(self): """Stop polling syncthing folder status.""" if self._unsub_timer is not None: self._unsub_timer() self._unsub_timer = None async def async_added_to_hass(self): """Handle entity which will be added.""" @callback def handle_folder_summary(event): if self._state is not None: self._state = self._filter_state(event["data"]["summary"]) self.async_write_ha_state() self.async_on_remove( async_dispatcher_connect( self.hass, f"{FOLDER_SUMMARY_RECEIVED}-{self._server_id}-{self._folder_id}", handle_folder_summary, ) ) @callback def handle_state_changed(event): if self._state is not None: self._state["state"] = event["data"]["to"] self.async_write_ha_state() self.async_on_remove( async_dispatcher_connect( self.hass, f"{STATE_CHANGED_RECEIVED}-{self._server_id}-{self._folder_id}", handle_state_changed, ) ) @callback def handle_folder_paused(event): if self._state is not None: self._state["state"] = "paused" self.async_write_ha_state() self.async_on_remove( async_dispatcher_connect( self.hass, f"{FOLDER_PAUSED_RECEIVED}-{self._server_id}-{self._folder_id}", handle_folder_paused, ) ) @callback def handle_server_unavailable(): self._state = None self.unsubscribe() self.async_write_ha_state() self.async_on_remove( async_dispatcher_connect( self.hass, f"{SERVER_UNAVAILABLE}-{self._server_id}", handle_server_unavailable, ) ) async def handle_server_available(): self.subscribe() await self.async_update_status() self.async_on_remove( async_dispatcher_connect( self.hass, f"{SERVER_AVAILABLE}-{self._server_id}", handle_server_available, ) ) self.subscribe() self.async_on_remove(self.unsubscribe) await self.async_update_status() def _filter_state(self, state): # Select only needed state attributes and map their names state = { self.STATE_ATTRIBUTES[key]: value for key, value in state.items() if key in self.STATE_ATTRIBUTES } # A workaround, for some reason, state of paused folders is an empty string if state["state"] == "": state["state"] = "paused" # Add some useful attributes state["id"] = self._folder_id state["label"] = self._folder_label return state
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/syncthing/sensor.py
"""The Compensation integration.""" import logging import warnings import numpy as np import voluptuous as vol from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.const import ( CONF_ATTRIBUTE, CONF_SOURCE, CONF_UNIQUE_ID, CONF_UNIT_OF_MEASUREMENT, ) from homeassistant.helpers import config_validation as cv from homeassistant.helpers.discovery import async_load_platform from .const import ( CONF_COMPENSATION, CONF_DATAPOINTS, CONF_DEGREE, CONF_POLYNOMIAL, CONF_PRECISION, DATA_COMPENSATION, DEFAULT_DEGREE, DEFAULT_PRECISION, DOMAIN, ) _LOGGER = logging.getLogger(__name__) def datapoints_greater_than_degree(value: dict) -> dict: """Validate data point list is greater than polynomial degrees.""" if len(value[CONF_DATAPOINTS]) <= value[CONF_DEGREE]: raise vol.Invalid( f"{CONF_DATAPOINTS} must have at least {value[CONF_DEGREE]+1} {CONF_DATAPOINTS}" ) return value COMPENSATION_SCHEMA = vol.Schema( { vol.Required(CONF_SOURCE): cv.entity_id, vol.Required(CONF_DATAPOINTS): [ vol.ExactSequence([vol.Coerce(float), vol.Coerce(float)]) ], vol.Optional(CONF_UNIQUE_ID): cv.string, vol.Optional(CONF_ATTRIBUTE): cv.string, vol.Optional(CONF_PRECISION, default=DEFAULT_PRECISION): cv.positive_int, vol.Optional(CONF_DEGREE, default=DEFAULT_DEGREE): vol.All( vol.Coerce(int), vol.Range(min=1, max=7), ), vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string, } ) CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( {cv.slug: vol.All(COMPENSATION_SCHEMA, datapoints_greater_than_degree)} ) }, extra=vol.ALLOW_EXTRA, ) async def async_setup(hass, config): """Set up the Compensation sensor.""" hass.data[DATA_COMPENSATION] = {} for compensation, conf in config.get(DOMAIN).items(): _LOGGER.debug("Setup %s.%s", DOMAIN, compensation) degree = conf[CONF_DEGREE] # get x values and y values from the x,y point pairs x_values, y_values = zip(*conf[CONF_DATAPOINTS]) # try to get valid coefficients for a polynomial coefficients = None with np.errstate(all="raise"): with warnings.catch_warnings(record=True) as all_warnings: warnings.simplefilter("always") try: coefficients = np.polyfit(x_values, y_values, degree) except FloatingPointError as error: _LOGGER.error( "Setup of %s encountered an error, %s", compensation, error, ) for warning in all_warnings: _LOGGER.warning( "Setup of %s encountered a warning, %s", compensation, str(warning.message).lower(), ) if coefficients is not None: data = { k: v for k, v in conf.items() if k not in [CONF_DEGREE, CONF_DATAPOINTS] } data[CONF_POLYNOMIAL] = np.poly1d(coefficients) hass.data[DATA_COMPENSATION][compensation] = data hass.async_create_task( async_load_platform( hass, SENSOR_DOMAIN, DOMAIN, {CONF_COMPENSATION: compensation}, config, ) ) return True
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/compensation/__init__.py
"""Support for Tado sensors for each zone.""" import logging from homeassistant.components.sensor import SensorEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, PERCENTAGE, TEMP_CELSIUS, ) from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from .const import ( CONDITIONS_MAP, DATA, DOMAIN, SIGNAL_TADO_UPDATE_RECEIVED, TYPE_AIR_CONDITIONING, TYPE_HEATING, TYPE_HOT_WATER, ) from .entity import TadoHomeEntity, TadoZoneEntity _LOGGER = logging.getLogger(__name__) HOME_SENSORS = { "outdoor temperature", "solar percentage", "weather condition", } ZONE_SENSORS = { TYPE_HEATING: [ "temperature", "humidity", "heating", "tado mode", ], TYPE_AIR_CONDITIONING: [ "temperature", "humidity", "ac", "tado mode", ], TYPE_HOT_WATER: ["tado mode"], } def format_condition(condition: str) -> str: """Return condition from dict CONDITIONS_MAP.""" for key, value in CONDITIONS_MAP.items(): if condition in value: return key return condition async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ): """Set up the Tado sensor platform.""" tado = hass.data[DOMAIN][entry.entry_id][DATA] zones = tado.zones entities = [] # Create home sensors entities.extend([TadoHomeSensor(tado, variable) for variable in HOME_SENSORS]) # Create zone sensors for zone in zones: zone_type = zone["type"] if zone_type not in ZONE_SENSORS: _LOGGER.warning("Unknown zone type skipped: %s", zone_type) continue entities.extend( [ TadoZoneSensor(tado, zone["name"], zone["id"], variable) for variable in ZONE_SENSORS[zone_type] ] ) if entities: async_add_entities(entities, True) class TadoHomeSensor(TadoHomeEntity, SensorEntity): """Representation of a Tado Sensor.""" def __init__(self, tado, home_variable): """Initialize of the Tado Sensor.""" super().__init__(tado) self._tado = tado self.home_variable = home_variable self._unique_id = f"{home_variable} {tado.home_id}" self._state = None self._state_attributes = None self._tado_weather_data = self._tado.data["weather"] async def async_added_to_hass(self): """Register for sensor updates.""" self.async_on_remove( async_dispatcher_connect( self.hass, SIGNAL_TADO_UPDATE_RECEIVED.format( self._tado.home_id, "weather", "data" ), self._async_update_callback, ) ) self._async_update_home_data() @property def unique_id(self): """Return the unique id.""" return self._unique_id @property def name(self): """Return the name of the sensor.""" return f"{self._tado.home_name} {self.home_variable}" @property def state(self): """Return the state of the sensor.""" return self._state @property def extra_state_attributes(self): """Return the state attributes.""" return self._state_attributes @property def unit_of_measurement(self): """Return the unit of measurement.""" if self.home_variable == "temperature": return TEMP_CELSIUS if self.home_variable == "solar percentage": return PERCENTAGE if self.home_variable == "weather condition": return None @property def device_class(self): """Return the device class.""" if self.home_variable == "outdoor temperature": return DEVICE_CLASS_TEMPERATURE return None @callback def _async_update_callback(self): """Update and write state.""" self._async_update_home_data() self.async_write_ha_state() @callback def _async_update_home_data(self): """Handle update callbacks.""" try: self._tado_weather_data = self._tado.data["weather"] except KeyError: return if self.home_variable == "outdoor temperature": self._state = self.hass.config.units.temperature( self._tado_weather_data["outsideTemperature"]["celsius"], TEMP_CELSIUS, ) self._state_attributes = { "time": self._tado_weather_data["outsideTemperature"]["timestamp"], } elif self.home_variable == "solar percentage": self._state = self._tado_weather_data["solarIntensity"]["percentage"] self._state_attributes = { "time": self._tado_weather_data["solarIntensity"]["timestamp"], } elif self.home_variable == "weather condition": self._state = format_condition( self._tado_weather_data["weatherState"]["value"] ) self._state_attributes = { "time": self._tado_weather_data["weatherState"]["timestamp"] } class TadoZoneSensor(TadoZoneEntity, SensorEntity): """Representation of a tado Sensor.""" def __init__(self, tado, zone_name, zone_id, zone_variable): """Initialize of the Tado Sensor.""" self._tado = tado super().__init__(zone_name, tado.home_id, zone_id) self.zone_variable = zone_variable self._unique_id = f"{zone_variable} {zone_id} {tado.home_id}" self._state = None self._state_attributes = None self._tado_zone_data = None async def async_added_to_hass(self): """Register for sensor updates.""" self.async_on_remove( async_dispatcher_connect( self.hass, SIGNAL_TADO_UPDATE_RECEIVED.format( self._tado.home_id, "zone", self.zone_id ), self._async_update_callback, ) ) self._async_update_zone_data() @property def unique_id(self): """Return the unique id.""" return self._unique_id @property def name(self): """Return the name of the sensor.""" return f"{self.zone_name} {self.zone_variable}" @property def state(self): """Return the state of the sensor.""" return self._state @property def extra_state_attributes(self): """Return the state attributes.""" return self._state_attributes @property def unit_of_measurement(self): """Return the unit of measurement.""" if self.zone_variable == "temperature": return self.hass.config.units.temperature_unit if self.zone_variable == "humidity": return PERCENTAGE if self.zone_variable == "heating": return PERCENTAGE if self.zone_variable == "ac": return None @property def device_class(self): """Return the device class.""" if self.zone_variable == "humidity": return DEVICE_CLASS_HUMIDITY if self.zone_variable == "temperature": return DEVICE_CLASS_TEMPERATURE return None @callback def _async_update_callback(self): """Update and write state.""" self._async_update_zone_data() self.async_write_ha_state() @callback def _async_update_zone_data(self): """Handle update callbacks.""" try: self._tado_zone_data = self._tado.data["zone"][self.zone_id] except KeyError: return if self.zone_variable == "temperature": self._state = self.hass.config.units.temperature( self._tado_zone_data.current_temp, TEMP_CELSIUS ) self._state_attributes = { "time": self._tado_zone_data.current_temp_timestamp, "setting": 0, # setting is used in climate device } elif self.zone_variable == "humidity": self._state = self._tado_zone_data.current_humidity self._state_attributes = { "time": self._tado_zone_data.current_humidity_timestamp } elif self.zone_variable == "heating": self._state = self._tado_zone_data.heating_power_percentage self._state_attributes = { "time": self._tado_zone_data.heating_power_timestamp } elif self.zone_variable == "ac": self._state = self._tado_zone_data.ac_power self._state_attributes = {"time": self._tado_zone_data.ac_power_timestamp} elif self.zone_variable == "tado mode": self._state = self._tado_zone_data.tado_mode
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/tado/sensor.py
"""The JuiceNet integration.""" from datetime import timedelta import logging import aiohttp from pyjuicenet import Api, TokenError import voluptuous as vol from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import CONF_ACCESS_TOKEN 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.update_coordinator import DataUpdateCoordinator from .const import DOMAIN, JUICENET_API, JUICENET_COORDINATOR from .device import JuiceNetApi _LOGGER = logging.getLogger(__name__) PLATFORMS = ["sensor", "switch"] CONFIG_SCHEMA = vol.Schema( vol.All( cv.deprecated(DOMAIN), {DOMAIN: vol.Schema({vol.Required(CONF_ACCESS_TOKEN): cv.string})}, ), extra=vol.ALLOW_EXTRA, ) async def async_setup(hass: HomeAssistant, config: dict): """Set up the JuiceNet component.""" conf = config.get(DOMAIN) hass.data.setdefault(DOMAIN, {}) if not conf: return True hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=conf ) ) return True async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up JuiceNet from a config entry.""" config = entry.data session = async_get_clientsession(hass) access_token = config[CONF_ACCESS_TOKEN] api = Api(access_token, session) juicenet = JuiceNetApi(api) try: await juicenet.setup() except TokenError as error: _LOGGER.error("JuiceNet Error %s", error) return False except aiohttp.ClientError as error: _LOGGER.error("Could not reach the JuiceNet API %s", error) raise ConfigEntryNotReady from error if not juicenet.devices: _LOGGER.error("No JuiceNet devices found for this account") return False _LOGGER.info("%d JuiceNet device(s) found", len(juicenet.devices)) async def async_update_data(): """Update all device states from the JuiceNet API.""" for device in juicenet.devices: await device.update_state(True) return True coordinator = DataUpdateCoordinator( hass, _LOGGER, name="JuiceNet", update_method=async_update_data, update_interval=timedelta(seconds=30), ) hass.data[DOMAIN][entry.entry_id] = { JUICENET_API: juicenet, JUICENET_COORDINATOR: coordinator, } await coordinator.async_config_entry_first_refresh() hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry): """Unload a config entry.""" unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) return unload_ok
"""Test component/platform setup.""" # pylint: disable=protected-access import asyncio import datetime import os import threading from unittest.mock import AsyncMock, Mock, patch import pytest import voluptuous as vol from homeassistant import config_entries, setup import homeassistant.config as config_util from homeassistant.const import EVENT_COMPONENT_LOADED, EVENT_HOMEASSISTANT_START from homeassistant.core import callback from homeassistant.helpers import discovery from homeassistant.helpers.config_validation import ( PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE, ) import homeassistant.util.dt as dt_util from tests.common import ( MockConfigEntry, MockModule, MockPlatform, assert_setup_component, get_test_config_dir, get_test_home_assistant, mock_entity_platform, mock_integration, ) ORIG_TIMEZONE = dt_util.DEFAULT_TIME_ZONE VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE) @pytest.fixture(autouse=True) def mock_handlers(): """Mock config flows.""" class MockFlowHandler(config_entries.ConfigFlow): """Define a mock flow handler.""" VERSION = 1 with patch.dict(config_entries.HANDLERS, {"comp": MockFlowHandler}): yield class TestSetup: """Test the bootstrap utils.""" hass = None backup_cache = None # pylint: disable=invalid-name, no-self-use def setup_method(self, method): """Set up the test.""" self.hass = get_test_home_assistant() def teardown_method(self, method): """Clean up.""" self.hass.stop() def test_validate_component_config(self): """Test validating component configuration.""" config_schema = vol.Schema({"comp_conf": {"hello": str}}, required=True) mock_integration( self.hass, MockModule("comp_conf", config_schema=config_schema) ) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": None} ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component(self.hass, "comp_conf", {"comp_conf": {}}) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(0): assert not setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world", "invalid": "extra"}}, ) self.hass.data.pop(setup.DATA_SETUP) with assert_setup_component(1): assert setup.setup_component( self.hass, "comp_conf", {"comp_conf": {"hello": "world"}} ) def test_validate_platform_config(self, caplog): """Test validating platform configuration.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({}) mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=platform_schema_base), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(0): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "not_existing", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {"platform": "whatever", "hello": "world"}}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": [{"platform": "whatever", "hello": "world"}]}, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") # Any falsey platform config will be ignored (None, {}, etc) with assert_setup_component(0) as config: assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": None} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty assert setup.setup_component( self.hass, "platform_conf", {"platform_conf": {}} ) assert "platform_conf" in self.hass.config.components assert not config["platform_conf"] # empty def test_validate_platform_config_2(self, caplog): """Test component PLATFORM_SCHEMA_BASE prio over PLATFORM_SCHEMA.""" platform_schema = PLATFORM_SCHEMA.extend({"hello": str}) platform_schema_base = PLATFORM_SCHEMA_BASE.extend({"hello": "world"}) mock_integration( self.hass, MockModule( "platform_conf", platform_schema=platform_schema, platform_schema_base=platform_schema_base, ), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema_base "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_3(self, caplog): """Test fallback to component PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE.extend({"hello": str}) platform_schema = PLATFORM_SCHEMA.extend({"cheers": str, "hello": "world"}) mock_integration( self.hass, MockModule("platform_conf", platform_schema=component_schema) ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform("whatever", platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { # pass "platform_conf": {"platform": "whatever", "hello": "world"}, # fail: key hello violates component platform_schema "platform_conf 2": {"platform": "whatever", "hello": "there"}, }, ) def test_validate_platform_config_4(self): """Test entity_namespace in PLATFORM_SCHEMA.""" component_schema = PLATFORM_SCHEMA_BASE platform_schema = PLATFORM_SCHEMA mock_integration( self.hass, MockModule("platform_conf", platform_schema_base=component_schema), ) mock_entity_platform( self.hass, "platform_conf.whatever", MockPlatform(platform_schema=platform_schema), ) with assert_setup_component(1): assert setup.setup_component( self.hass, "platform_conf", { "platform_conf": { # pass: entity_namespace accepted by PLATFORM_SCHEMA "platform": "whatever", "entity_namespace": "yummy", } }, ) self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("platform_conf") def test_component_not_found(self): """setup_component should not crash if component doesn't exist.""" assert setup.setup_component(self.hass, "non_existing", {}) is False def test_component_not_double_initialized(self): """Test we do not set up a component twice.""" mock_setup = Mock(return_value=True) mock_integration(self.hass, MockModule("comp", setup=mock_setup)) assert setup.setup_component(self.hass, "comp", {}) assert mock_setup.called mock_setup.reset_mock() assert setup.setup_component(self.hass, "comp", {}) assert not mock_setup.called @patch("homeassistant.util.package.install_package", return_value=False) def test_component_not_installed_if_requirement_fails(self, mock_install): """Component setup should fail if requirement can't install.""" self.hass.config.skip_pip = False mock_integration(self.hass, MockModule("comp", requirements=["package==0.0.1"])) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_not_setup_twice_if_loaded_during_other_setup(self): """Test component setup while waiting for lock is not set up twice.""" result = [] async def async_setup(hass, config): """Tracking Setup.""" result.append(1) mock_integration(self.hass, MockModule("comp", async_setup=async_setup)) def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {}) thread = threading.Thread(target=setup_component) thread.start() setup.setup_component(self.hass, "comp", {}) thread.join() assert len(result) == 1 def test_component_not_setup_missing_dependencies(self): """Test we do not set up a component if not all dependencies loaded.""" deps = ["maybe_existing"] mock_integration(self.hass, MockModule("comp", dependencies=deps)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration(self.hass, MockModule("comp2", dependencies=deps)) mock_integration(self.hass, MockModule("maybe_existing")) assert setup.setup_component(self.hass, "comp2", {}) def test_component_failing_setup(self): """Test component that fails setup.""" mock_integration( self.hass, MockModule("comp", setup=lambda hass, config: False) ) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_exception_setup(self): """Test component that raises exception during setup.""" def exception_setup(hass, config): """Raise exception.""" raise Exception("fail!") mock_integration(self.hass, MockModule("comp", setup=exception_setup)) assert not setup.setup_component(self.hass, "comp", {}) assert "comp" not in self.hass.config.components def test_component_setup_with_validation_and_dependency(self): """Test all config is passed to dependencies.""" def config_check_setup(hass, config): """Test that config is passed in.""" if config.get("comp_a", {}).get("valid", False): return True raise Exception(f"Config not passed in: {config}") platform = MockPlatform() mock_integration(self.hass, MockModule("comp_a", setup=config_check_setup)) mock_integration( self.hass, MockModule("platform_a", setup=config_check_setup, dependencies=["comp_a"]), ) mock_entity_platform(self.hass, "switch.platform_a", platform) setup.setup_component( self.hass, "switch", {"comp_a": {"valid": True}, "switch": {"platform": "platform_a"}}, ) self.hass.block_till_done() assert "comp_a" in self.hass.config.components def test_platform_specific_config_validation(self): """Test platform that specifies config.""" platform_schema = PLATFORM_SCHEMA.extend( {"valid": True}, extra=vol.PREVENT_EXTRA ) mock_setup = Mock(spec_set=True) mock_entity_platform( self.hass, "switch.platform_a", MockPlatform(platform_schema=platform_schema, setup_platform=mock_setup), ) with assert_setup_component(0, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "invalid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(0): assert setup.setup_component( self.hass, "switch", { "switch": { "platform": "platform_a", "valid": True, "invalid_extra": True, } }, ) self.hass.block_till_done() assert mock_setup.call_count == 0 self.hass.data.pop(setup.DATA_SETUP) self.hass.config.components.remove("switch") with assert_setup_component(1, "switch"): assert setup.setup_component( self.hass, "switch", {"switch": {"platform": "platform_a", "valid": True}}, ) self.hass.block_till_done() assert mock_setup.call_count == 1 def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: None) ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: False), ) assert not setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) mock_integration( self.hass, MockModule("disabled_component", setup=lambda hass, config: True) ) assert setup.setup_component(self.hass, "disabled_component", {}) assert "disabled_component" in self.hass.config.components def test_all_work_done_before_start(self): """Test all init work done till start.""" call_order = [] async def component1_setup(hass, config): """Set up mock component.""" await discovery.async_discover( hass, "test_component2", {}, "test_component2", {} ) await discovery.async_discover( hass, "test_component3", {}, "test_component3", {} ) return True def component_track_setup(hass, config): """Set up mock component.""" call_order.append(1) return True mock_integration( self.hass, MockModule("test_component1", async_setup=component1_setup) ) mock_integration( self.hass, MockModule("test_component2", setup=component_track_setup) ) mock_integration( self.hass, MockModule("test_component3", setup=component_track_setup) ) @callback def track_start(event): """Track start event.""" call_order.append(2) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, track_start) self.hass.add_job(setup.async_setup_component(self.hass, "test_component1", {})) self.hass.block_till_done() self.hass.start() assert call_order == [1, 1, 2] async def test_component_warn_slow_setup(hass): """Warn we log when a component setup takes a long time.""" mock_integration(hass, MockModule("test_component1")) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert mock_call.called assert len(mock_call.mock_calls) == 3 timeout, logger_method = mock_call.mock_calls[0][1][:2] assert timeout == setup.SLOW_SETUP_WARNING assert logger_method == setup._LOGGER.warning assert mock_call().cancel.called async def test_platform_no_warn_slow(hass): """Do not warn for long entity setup time.""" mock_integration( hass, MockModule("test_component1", platform_schema=PLATFORM_SCHEMA) ) with patch.object(hass.loop, "call_later") as mock_call: result = await setup.async_setup_component(hass, "test_component1", {}) assert result assert len(mock_call.mock_calls) == 0 async def test_platform_error_slow_setup(hass, caplog): """Don't block startup more than SLOW_SETUP_MAX_WAIT.""" with patch.object(setup, "SLOW_SETUP_MAX_WAIT", 1): called = [] async def async_setup(*args): """Tracking Setup.""" called.append(1) await asyncio.sleep(2) mock_integration(hass, MockModule("test_component1", async_setup=async_setup)) result = await setup.async_setup_component(hass, "test_component1", {}) assert len(called) == 1 assert not result assert "test_component1 is taking longer than 1 seconds" in caplog.text async def test_when_setup_already_loaded(hass): """Test when setup.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] async def test_async_when_setup_or_start_already_loaded(hass): """Test when setup or start.""" calls = [] async def mock_callback(hass, component): """Mock callback.""" calls.append(component) setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == [] hass.config.components.add("test") hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Event listener should be gone hass.bus.async_fire(EVENT_COMPONENT_LOADED, {"component": "test"}) await hass.async_block_till_done() assert calls == ["test"] # Should be called right away setup.async_when_setup_or_start(hass, "test", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] setup.async_when_setup_or_start(hass, "not_loaded", mock_callback) await hass.async_block_till_done() assert calls == ["test", "test"] hass.bus.async_fire(EVENT_HOMEASSISTANT_START) await hass.async_block_till_done() assert calls == ["test", "test", "not_loaded"] async def test_setup_import_blows_up(hass): """Test that we handle it correctly when importing integration blows up.""" with patch( "homeassistant.loader.Integration.get_component", side_effect=ValueError ): assert not await setup.async_setup_component(hass, "sun", {}) async def test_parallel_entry_setup(hass): """Test config entries are set up in parallel.""" MockConfigEntry(domain="comp", data={"value": 1}).add_to_hass(hass) MockConfigEntry(domain="comp", data={"value": 2}).add_to_hass(hass) calls = [] async def mock_async_setup_entry(hass, entry): """Mock setting up an entry.""" calls.append(entry.data["value"]) await asyncio.sleep(0) calls.append(entry.data["value"]) return True mock_integration( hass, MockModule( "comp", async_setup_entry=mock_async_setup_entry, ), ) mock_entity_platform(hass, "config_flow.comp", None) await setup.async_setup_component(hass, "comp", {}) assert calls == [1, 2, 1, 2] async def test_integration_disabled(hass, caplog): """Test we can disable an integration.""" disabled_reason = "Dependency contains code that breaks Home Assistant" mock_integration( hass, MockModule("test_component1", partial_manifest={"disabled": disabled_reason}), ) result = await setup.async_setup_component(hass, "test_component1", {}) assert not result assert disabled_reason in caplog.text async def test_async_get_loaded_integrations(hass): """Test we can enumerate loaded integations.""" hass.config.components.add("notbase") hass.config.components.add("switch") hass.config.components.add("notbase.switch") hass.config.components.add("myintegration") hass.config.components.add("device_tracker") hass.config.components.add("device_tracker.other") hass.config.components.add("myintegration.light") assert setup.async_get_loaded_integrations(hass) == { "other", "switch", "notbase", "myintegration", "device_tracker", } async def test_integration_no_setup(hass, caplog): """Test we fail integration setup without setup functions.""" mock_integration( hass, MockModule("test_integration_without_setup", setup=False), ) result = await setup.async_setup_component( hass, "test_integration_without_setup", {} ) assert not result assert "No setup or config entry setup function defined" in caplog.text async def test_integration_only_setup_entry(hass): """Test we have an integration with only a setup entry method.""" mock_integration( hass, MockModule( "test_integration_only_entry", setup=False, async_setup_entry=AsyncMock(return_value=True), ), ) assert await setup.async_setup_component(hass, "test_integration_only_entry", {}) async def test_async_start_setup(hass): """Test setup started context manager keeps track of setup times.""" with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august"], datetime.datetime ) with setup.async_start_setup(hass, ["august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["august_2"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "august_2" not in hass.data[setup.DATA_SETUP_TIME] async def test_async_start_setup_platforms(hass): """Test setup started context manager keeps track of setup times for platforms.""" with setup.async_start_setup(hass, ["sensor.august"]): assert isinstance( hass.data[setup.DATA_SETUP_STARTED]["sensor.august"], datetime.datetime ) assert "august" not in hass.data[setup.DATA_SETUP_STARTED] assert isinstance(hass.data[setup.DATA_SETUP_TIME]["august"], datetime.timedelta) assert "sensor" not in hass.data[setup.DATA_SETUP_TIME]
home-assistant/home-assistant
tests/test_setup.py
homeassistant/components/juicenet/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ cookiecutter.main ----------------- Main entry point for the `cookiecutter` command. The code in this module is also a good example of how to use Cookiecutter as a library rather than a script. """ from __future__ import unicode_literals import logging import os from .config import get_user_config from .prompt import prompt_for_config from .generate import generate_context, generate_files from .vcs import clone logger = logging.getLogger(__name__) builtin_abbreviations = { 'gh': 'https://github.com/{0}.git', 'bb': 'https://bitbucket.org/{0}', } def expand_abbreviations(template, config_dict): """ Expand abbreviations in a template name. :param template: The project template name. :param config_dict: The user config, which will contain abbreviation definitions. """ abbreviations = builtin_abbreviations.copy() abbreviations.update(config_dict.get('abbreviations', {})) if template in abbreviations: return abbreviations[template] # Split on colon. If there is no colon, rest will be empty # and prefix will be the whole template prefix, sep, rest = template.partition(':') if prefix in abbreviations: return abbreviations[prefix].format(rest) return template def cookiecutter(template, checkout=None, no_input=False, extra_context=None): """ API equivalent to using Cookiecutter at the command line. :param template: A directory containing a project template directory, or a URL to a git repository. :param checkout: The branch, tag or commit ID to checkout after clone. :param no_input: Prompt the user at command line for manual configuration? :param extra_context: A dictionary of context that overrides default and user configuration. """ # Get user config from ~/.cookiecutterrc or equivalent # If no config file, sensible defaults from config.DEFAULT_CONFIG are used config_dict = get_user_config() template = expand_abbreviations(template, config_dict) # TODO: find a better way to tell if it's a repo URL if 'git@' in template or 'https://' in template: repo_dir = clone( repo_url=template, checkout=checkout, clone_to_dir=config_dict['cookiecutters_dir'], no_input=no_input ) else: # If it's a local repo, no need to clone or copy to your # cookiecutters_dir repo_dir = template context_file = os.path.join(repo_dir, 'cookiecutter.json') logging.debug('context_file is {0}'.format(context_file)) context = generate_context( context_file=context_file, default_context=config_dict['default_context'], extra_context=extra_context, ) # prompt the user to manually configure at the command line. # except when 'no-input' flag is set context['cookiecutter'] = prompt_for_config(context, no_input) # Create project from local context and project template. generate_files( repo_dir=repo_dir, context=context )
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_generate_hooks ------------------- Tests formerly known from a unittest residing in test_generate.py named TestHooks.test_ignore_hooks_dirs TestHooks.test_run_python_hooks TestHooks.test_run_python_hooks_cwd TestHooks.test_run_shell_hooks """ from __future__ import unicode_literals import os import sys import stat import pytest from cookiecutter import generate from cookiecutter import utils @pytest.fixture(scope='function') def remove_additional_folders(request): """ Remove some special folders which are created by the tests. """ def fin_remove_additional_folders(): if os.path.exists('tests/test-pyhooks/inputpyhooks'): utils.rmtree('tests/test-pyhooks/inputpyhooks') if os.path.exists('inputpyhooks'): utils.rmtree('inputpyhooks') if os.path.exists('tests/test-shellhooks'): utils.rmtree('tests/test-shellhooks') request.addfinalizer(fin_remove_additional_folders) @pytest.mark.usefixtures('clean_system', 'remove_additional_folders') def test_ignore_hooks_dirs(): generate.generate_files( context={ 'cookiecutter': {'pyhooks': 'pyhooks'} }, repo_dir='tests/test-pyhooks/', output_dir='tests/test-pyhooks/' ) assert not os.path.exists('tests/test-pyhooks/inputpyhooks/hooks') @pytest.mark.usefixtures('clean_system', 'remove_additional_folders') def test_run_python_hooks(): generate.generate_files( context={ 'cookiecutter': {'pyhooks': 'pyhooks'} }, repo_dir='tests/test-pyhooks/'.replace("/", os.sep), output_dir='tests/test-pyhooks/'.replace("/", os.sep) ) assert os.path.exists('tests/test-pyhooks/inputpyhooks/python_pre.txt') assert os.path.exists('tests/test-pyhooks/inputpyhooks/python_post.txt') @pytest.mark.usefixtures('clean_system', 'remove_additional_folders') def test_run_python_hooks_cwd(): generate.generate_files( context={ 'cookiecutter': {'pyhooks': 'pyhooks'} }, repo_dir='tests/test-pyhooks/' ) assert os.path.exists('inputpyhooks/python_pre.txt') assert os.path.exists('inputpyhooks/python_post.txt') def make_test_repo(name): hooks = os.path.join(name, 'hooks') template = os.path.join(name, 'input{{cookiecutter.shellhooks}}') os.mkdir(name) os.mkdir(hooks) os.mkdir(template) with open(os.path.join(template, 'README.rst'), 'w') as f: f.write("foo\n===\n\nbar\n") if sys.platform.startswith('win'): filename = os.path.join(hooks, 'pre_gen_project.bat') with open(filename, 'w') as f: f.write("@echo off\n") f.write("\n") f.write("echo pre generation hook\n") f.write("echo. >shell_pre.txt\n") filename = os.path.join(hooks, 'post_gen_project.bat') with open(filename, 'w') as f: f.write("@echo off\n") f.write("\n") f.write("echo post generation hook\n") f.write("echo. >shell_post.txt\n") else: filename = os.path.join(hooks, 'pre_gen_project.sh') with open(filename, 'w') as f: f.write("#!/bin/bash\n") f.write("\n") f.write("echo 'pre generation hook';\n") f.write("touch 'shell_pre.txt'\n") # Set the execute bit os.chmod(filename, os.stat(filename).st_mode | stat.S_IXUSR) filename = os.path.join(hooks, 'post_gen_project.sh') with open(filename, 'w') as f: f.write("#!/bin/bash\n") f.write("\n") f.write("echo 'post generation hook';\n") f.write("touch 'shell_post.txt'\n") # Set the execute bit os.chmod(filename, os.stat(filename).st_mode | stat.S_IXUSR) @pytest.mark.usefixtures('clean_system', 'remove_additional_folders') def test_run_shell_hooks(): make_test_repo('tests/test-shellhooks') generate.generate_files( context={ 'cookiecutter': {'shellhooks': 'shellhooks'} }, repo_dir='tests/test-shellhooks/', output_dir='tests/test-shellhooks/' ) shell_pre_file = 'tests/test-shellhooks/inputshellhooks/shell_pre.txt' shell_post_file = 'tests/test-shellhooks/inputshellhooks/shell_post.txt' assert os.path.exists(shell_pre_file) assert os.path.exists(shell_post_file)
janusnic/cookiecutter
tests/test_generate_hooks.py
cookiecutter/main.py
from __future__ import unicode_literals import json from threading import Event from functools import wraps from collections import defaultdict from six.moves.urllib_parse import quote import jinja2 import cherrypy import sideboard.lib from sideboard.lib import log, config, serializer auth_registry = {} _startup_registry = defaultdict(list) _shutdown_registry = defaultdict(list) def _on_startup(func, priority): _startup_registry[priority].append(func) return func def _on_shutdown(func, priority): _shutdown_registry[priority].append(func) return func def on_startup(func=None, priority=50): """ Register a function to be called when Sideboard starts. Startup functions have a priority, and the functions are invoked in priority order, where low-priority-numbered functions are invoked before higher numbers. Startup functions may be registered in one of three ways: 1) A function can be passed directly, e.g. on_startup(callback_function) on_startup(callback_function, priority=25) 2) This function can be used as a decorator, e.g. @on_startup def callback_function(): ... 3) This function can be used as a decorator with a priority value, e.g. @on_startup(priority=25) def callback_function(): ... """ if func: return _on_startup(func, priority) else: return lambda func: _on_startup(func, priority) def on_shutdown(func=None, priority=50): """ Register a function to be called when Sideboard exits. See the on_startup function above for how this is used. """ if func: return _on_shutdown(func, priority) else: return lambda func: _on_shutdown(func, priority) def _run_startup(): for priority, functions in sorted(_startup_registry.items()): for func in functions: func() def _run_shutdown(): for priority, functions in sorted(_shutdown_registry.items()): for func in functions: try: func() except Exception: log.warn('Ignored exception during shutdown', exc_info=True) stopped = Event() on_startup(stopped.clear, priority=0) on_shutdown(stopped.set, priority=0) cherrypy.engine.subscribe('start', _run_startup, priority=98) cherrypy.engine.subscribe('stop', _run_shutdown, priority=98) def mainloop(): """ This function exists for Sideboard plugins which do not run CherryPy. It runs all of the functions registered with sideboard.lib.on_startup and then waits for shutdown, at which point it runs all functions registered with sideboard.lib.on_shutdown. """ _run_startup() try: while not stopped.is_set(): try: stopped.wait(config['thread_wait_interval']) except KeyboardInterrupt: break finally: _run_shutdown() def ajax(method): """ Decorator for CherryPy page handler methods which sets the Content-Type to application/json and serializes your function's return value to json. """ @wraps(method) def to_json(self, *args, **kwargs): cherrypy.response.headers['Content-Type'] = 'application/json' return json.dumps(method(self, *args, **kwargs), cls=sideboard.lib.serializer) return to_json def restricted(x): """ Decorator for CherryPy page handler methods. This can either be called to provide an authenticator ident or called directly as a decorator, e.g. @restricted def some_page(self): ... is equivalent to @restricted(sideboard.lib.config['default_authenticator']) def some_page(self): ... """ def make_decorator(ident): def decorator(func): @cherrypy.expose @wraps(func) def with_checking(*args, **kwargs): if not auth_registry[ident]['check'](): raise cherrypy.HTTPRedirect(auth_registry[ident]['login_path']) else: return func(*args, **kwargs) return with_checking return decorator if hasattr(x, '__call__'): return make_decorator(config['default_authenticator'])(x) else: return make_decorator(x) def renders_template(method): """ Decorator for CherryPy page handler methods implementing default behaviors: - if your page handler returns a string, return that un-modified - if your page handler returns a non-jsonrpc dictionary, render a template with that dictionary; the function my_page will render my_page.html """ @cherrypy.expose @wraps(method) def renderer(self, *args, **kwargs): output = method(self, *args, **kwargs) if isinstance(output, dict) and output.get('jsonrpc') != '2.0': return self.env.get_template(method.__name__ + '.html').render(**output) else: return output return renderer # Lifted from Jinja2 docs. See http://jinja.pocoo.org/docs/api/#autoescaping def _guess_autoescape(template_name): if template_name is None or '.' not in template_name: return False ext = template_name.rsplit('.', 1)[1] return ext in ('html', 'htm', 'xml') class render_with_templates(object): """ Class decorator for CherryPy application objects which causes all of your page handler methods which return dictionaries to render Jinja templates found in this directory using those dictionaries. So if you have a page handler called my_page which returns a dictionary, the template my_page.html in the template_dir directory will be rendered with that dictionary. An "env" attribute gets added to the class which is a Jinja environment. For convenience, if the optional "restricted" parameter is passed, this class is also passed through the @all_restricted class decorator. """ def __init__(self, template_dir, restricted=False): self.template_dir, self.restricted = template_dir, restricted def __call__(self, klass): klass.env = jinja2.Environment(autoescape=_guess_autoescape, loader=jinja2.FileSystemLoader(self.template_dir)) klass.env.filters['jsonify'] = lambda x: klass.env.filters['safe'](json.dumps(x, cls=serializer)) if self.restricted: all_restricted(self.restricted)(klass) for name, func in list(klass.__dict__.items()): if hasattr(func, '__call__'): setattr(klass, name, renders_template(func)) return klass class all_restricted(object): """Invokes the @restricted decorator on all methods of a class.""" def __init__(self, ident): self.ident = ident assert ident in auth_registry, '{!r} is not a recognized authenticator'.format(ident) def __call__(self, klass): for name, func in list(klass.__dict__.items()): if hasattr(func, '__call__'): setattr(klass, name, restricted(self.ident)(func)) return klass def register_authenticator(ident, login_path, checker): """ Register a new authenticator, which consists of three things: - A string ident, used to identify the authenticator in @restricted calls. - The path to the login page we should redirect to when not authenticated. - A function callable with no parameters which returns a truthy value if the user is logged in and a falsey value if they are not. """ assert ident not in auth_registry, '{} is already a registered authenticator'.format(ident) auth_registry[ident] = { 'check': checker, 'login_path': login_path } register_authenticator('default', '/login', lambda: 'username' in cherrypy.session)
from __future__ import unicode_literals import sys import pytest from mock import Mock from sideboard import sep from sideboard.lib import entry_point from sideboard.lib._utils import _entry_points from sideboard.sep import run_plugin_entry_point class FakeExit(Exception): pass class TestSep(object): @pytest.yield_fixture(autouse=True) def automocks(self, monkeypatch): monkeypatch.setattr(sep, 'exit', Mock(side_effect=FakeExit), raising=False) prev_argv, prev_points = sys.argv[:], _entry_points.copy() yield sys.argv[:] = prev_argv _entry_points.clear() _entry_points.update(prev_points) def test_no_command(self): sys.argv[:] = ['sep'] pytest.raises(FakeExit, run_plugin_entry_point) sep.exit.assert_called_with(1) def test_help(self): for flag in ['-h', '--help']: sys.argv[:] = ['sep', flag] pytest.raises(FakeExit, run_plugin_entry_point) sep.exit.assert_called_with(0) sep.exit.reset_mock() def test_invalid(self): sys.argv[:] = ['sep', 'nonexistent_entry_point'] pytest.raises(FakeExit, run_plugin_entry_point) sep.exit.assert_called_with(2) def test_valid_entry_point(self): action = Mock() @entry_point def foobar(): action(sys.argv) sys.argv[:] = ['sep', 'foobar', 'baz', '--baf'] run_plugin_entry_point() action.assert_called_with(['foobar', 'baz', '--baf'])
RobRuana/sideboard
sideboard/tests/test_sep.py
sideboard/lib/_cp.py
# Copyright (c) 2008-2010 Aldo Cortesi # Copyright (c) 2011 Florian Mounier # Copyright (c) 2011 Kenji_Takahashi # Copyright (c) 2011 Paul Colomiets # Copyright (c) 2012 roger # Copyright (c) 2012 Craig Barnes # Copyright (c) 2012-2015 Tycho Andersen # Copyright (c) 2013 dequis # Copyright (c) 2013 David R. Andersen # Copyright (c) 2013 Tao Sauvage # Copyright (c) 2014-2015 Sean Vig # Copyright (c) 2014 Justin Bronder # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import asyncio import subprocess from typing import Any, List, Tuple from libqtile import bar, configurable, confreader from libqtile.command.base import CommandError, CommandObject, ItemT from libqtile.log_utils import logger # Each widget class must define which bar orientation(s) it supports by setting # these bits in an 'orientations' class attribute. Simply having the attribute # inherited by superclasses is discouraged, because if a superclass that was # only supporting one orientation, adds support for the other, its subclasses # will have to be adapted too, in general. ORIENTATION_NONE is only added for # completeness' sake. # +------------------------+--------------------+--------------------+ # | Widget bits | Horizontal bar | Vertical bar | # +========================+====================+====================+ # | ORIENTATION_NONE | ConfigError raised | ConfigError raised | # +------------------------+--------------------+--------------------+ # | ORIENTATION_HORIZONTAL | Widget displayed | ConfigError raised | # | | horizontally | | # +------------------------+--------------------+--------------------+ # | ORIENTATION_VERTICAL | ConfigError raised | Widget displayed | # | | | vertically | # +------------------------+--------------------+--------------------+ # | ORIENTATION_BOTH | Widget displayed | Widget displayed | # | | horizontally | vertically | # +------------------------+--------------------+--------------------+ class _Orientations(int): def __new__(cls, value, doc): return super().__new__(cls, value) def __init__(self, value, doc): self.doc = doc def __str__(self): return self.doc def __repr__(self): return self.doc ORIENTATION_NONE = _Orientations(0, 'none') ORIENTATION_HORIZONTAL = _Orientations(1, 'horizontal only') ORIENTATION_VERTICAL = _Orientations(2, 'vertical only') ORIENTATION_BOTH = _Orientations(3, 'horizontal and vertical') class _Widget(CommandObject, configurable.Configurable): """Base Widget class If length is set to the special value `bar.STRETCH`, the bar itself will set the length to the maximum remaining space, after all other widgets have been configured. In horizontal bars, 'length' corresponds to the width of the widget; in vertical bars, it corresponds to the widget's height. The offsetx and offsety attributes are set by the Bar after all widgets have been configured. Callback functions can be assigned to button presses by passing a dict to the 'callbacks' kwarg. No arguments are passed to the callback function so, if you need access to the qtile object, it needs to be imported into your code. For example: .. code-block:: python from libqtile import qtile def open_calendar(): qtile.cmd_spawn('gsimplecal next_month') clock = widget.Clock(mouse_callbacks={'Button1': open_calendar}) When the clock widget receives a click with button 1, the ``open_calendar`` function will be executed. Callbacks can be assigned to other buttons by adding more entries to the passed dictionary. """ orientations = ORIENTATION_BOTH offsetx: int = 0 offsety: int = 0 defaults = [ ("background", None, "Widget background color"), ("mouse_callbacks", {}, "Dict of mouse button press callback functions."), ] # type: List[Tuple[str, Any, str]] def __init__(self, length, **config): """ length: bar.STRETCH, bar.CALCULATED, or a specified length. """ CommandObject.__init__(self) self.name = self.__class__.__name__.lower() if "name" in config: self.name = config["name"] configurable.Configurable.__init__(self, **config) self.add_defaults(_Widget.defaults) if length in (bar.CALCULATED, bar.STRETCH): self.length_type = length self.length = 0 else: assert isinstance(length, int) self.length_type = bar.STATIC self.length = length self.configured = False @property def length(self): if self.length_type == bar.CALCULATED: return int(self.calculate_length()) return self._length @length.setter def length(self, value): self._length = value @property def width(self): if self.bar.horizontal: return self.length return self.bar.size @property def height(self): if self.bar.horizontal: return self.bar.size return self.length @property def offset(self): if self.bar.horizontal: return self.offsetx return self.offsety # Do not start the name with "test", or nosetests will try to test it # directly (prepend an underscore instead) def _test_orientation_compatibility(self, horizontal): if horizontal: if not self.orientations & ORIENTATION_HORIZONTAL: raise confreader.ConfigError( self.__class__.__name__ + " is not compatible with the orientation of the bar." ) elif not self.orientations & ORIENTATION_VERTICAL: raise confreader.ConfigError( self.__class__.__name__ + " is not compatible with the orientation of the bar." ) def timer_setup(self): """ This is called exactly once, after the widget has been configured and timers are available to be set up. """ pass def _configure(self, qtile, bar): self.qtile = qtile self.bar = bar self.drawer = bar.window.create_drawer(self.bar.width, self.bar.height) if not self.configured: self.qtile.call_soon(self.timer_setup) self.qtile.call_soon(asyncio.create_task, self._config_async()) async def _config_async(self): """ This is called once when the main eventloop has started. this happens after _configure has been run. Widgets that need to use asyncio coroutines after this point may wish to initialise the relevant code (e.g. connections to dbus using dbus_next) here. """ pass def finalize(self): if hasattr(self, 'layout') and self.layout: self.layout.finalize() self.drawer.finalize() def clear(self): self.drawer.set_source_rgb(self.bar.background) self.drawer.fillrect(self.offsetx, self.offsety, self.width, self.height) def info(self): return dict( name=self.name, offset=self.offset, length=self.length, width=self.width, height=self.height, ) def add_callbacks(self, defaults): """Add default callbacks with a lower priority than user-specified callbacks.""" defaults.update(self.mouse_callbacks) self.mouse_callbacks = defaults def button_press(self, x, y, button): name = 'Button{0}'.format(button) if name in self.mouse_callbacks: self.mouse_callbacks[name]() def button_release(self, x, y, button): pass def get(self, q, name): """ Utility function for quick retrieval of a widget by name. """ w = q.widgets_map.get(name) if not w: raise CommandError("No such widget: %s" % name) return w def _items(self, name: str) -> ItemT: if name == "bar": return True, [] return None def _select(self, name, sel): if name == "bar": return self.bar def cmd_info(self): """ Info for this object. """ return self.info() def draw(self): """ Method that draws the widget. You may call this explicitly to redraw the widget, but only if the length of the widget hasn't changed. If it has, you must call bar.draw instead. """ raise NotImplementedError def calculate_length(self): """ Must be implemented if the widget can take CALCULATED for length. It must return the width of the widget if it's installed in a horizontal bar; it must return the height of the widget if it's installed in a vertical bar. Usually you will test the orientation of the bar with 'self.bar.horizontal'. """ raise NotImplementedError def timeout_add(self, seconds, method, method_args=()): """ This method calls either ``.call_later`` with given arguments. """ return self.qtile.call_later(seconds, self._wrapper, method, *method_args) def call_process(self, command, **kwargs): """ This method uses `subprocess.check_output` to run the given command and return the string from stdout, which is decoded when using Python 3. """ output = subprocess.check_output(command, **kwargs) output = output.decode() return output def _wrapper(self, method, *method_args): try: method(*method_args) except: # noqa: E722 logger.exception('got exception from widget timer') def create_mirror(self): return Mirror(self) def mouse_enter(self, x, y): pass def mouse_leave(self, x, y): pass UNSPECIFIED = bar.Obj("UNSPECIFIED") class _TextBox(_Widget): """ Base class for widgets that are just boxes containing text. """ orientations = ORIENTATION_HORIZONTAL defaults = [ ("font", "sans", "Default font"), ("fontsize", None, "Font size. Calculated if None."), ("padding", None, "Padding. Calculated if None."), ("foreground", "ffffff", "Foreground colour"), ( "fontshadow", None, "font shadow color, default is None(no shadow)" ), ("markup", True, "Whether or not to use pango markup"), ("fmt", "{}", "How to format the text"), ('max_chars', 0, 'Maximum number of characters to display in widget.'), ] # type: List[Tuple[str, Any, str]] def __init__(self, text=" ", width=bar.CALCULATED, **config): self.layout = None _Widget.__init__(self, width, **config) self._text = text self.add_defaults(_TextBox.defaults) @property def text(self): return self._text @text.setter def text(self, value): if len(value) > self.max_chars > 0: value = value[:self.max_chars] + "…" self._text = value if self.layout: self.layout.text = self.formatted_text @property def formatted_text(self): return self.fmt.format(self._text) @property def foreground(self): return self._foreground @foreground.setter def foreground(self, fg): self._foreground = fg if self.layout: self.layout.colour = fg @property def font(self): return self._font @font.setter def font(self, value): self._font = value if self.layout: self.layout.font = value @property def fontshadow(self): return self._fontshadow @fontshadow.setter def fontshadow(self, value): self._fontshadow = value if self.layout: self.layout.font_shadow = value @property def actual_padding(self): if self.padding is None: return self.fontsize / 2 else: return self.padding def _configure(self, qtile, bar): _Widget._configure(self, qtile, bar) if self.fontsize is None: self.fontsize = self.bar.height - self.bar.height / 5 self.layout = self.drawer.textlayout( self.formatted_text, self.foreground, self.font, self.fontsize, self.fontshadow, markup=self.markup, ) def calculate_length(self): if self.text: return min( self.layout.width, self.bar.width ) + self.actual_padding * 2 else: return 0 def can_draw(self): can_draw = self.layout is not None \ and not self.layout.finalized() \ and self.offsetx is not None # if the bar hasn't placed us yet return can_draw def draw(self): if not self.can_draw(): return self.drawer.clear(self.background or self.bar.background) self.layout.draw( self.actual_padding or 0, int(self.bar.height / 2.0 - self.layout.height / 2.0) + 1 ) self.drawer.draw(offsetx=self.offsetx, width=self.width) def cmd_set_font(self, font=UNSPECIFIED, fontsize=UNSPECIFIED, fontshadow=UNSPECIFIED): """ Change the font used by this widget. If font is None, the current font is used. """ if font is not UNSPECIFIED: self.font = font if fontsize is not UNSPECIFIED: self.fontsize = fontsize if fontshadow is not UNSPECIFIED: self.fontshadow = fontshadow self.bar.draw() def info(self): d = _Widget.info(self) d['foreground'] = self.foreground d['text'] = self.formatted_text return d def update(self, text): if self.text == text: return if text is None: text = "" old_width = self.layout.width self.text = text # If our width hasn't changed, we just draw ourselves. Otherwise, # we draw the whole bar. if self.layout.width == old_width: self.draw() else: self.bar.draw() class InLoopPollText(_TextBox): """ A common interface for polling some 'fast' information, munging it, and rendering the result in a text box. You probably want to use ThreadPoolText instead. ('fast' here means that this runs /in/ the event loop, so don't block! If you want to run something nontrivial, use ThreadedPollWidget.) """ defaults = [ ("update_interval", 600, "Update interval in seconds, if none, the " "widget updates whenever the event loop is idle."), ] # type: List[Tuple[str, Any, str]] def __init__(self, default_text="N/A", width=bar.CALCULATED, **config): _TextBox.__init__(self, default_text, width, **config) self.add_defaults(InLoopPollText.defaults) def timer_setup(self): update_interval = self.tick() # If self.update_interval is defined and .tick() returns None, re-call # after self.update_interval if update_interval is None and self.update_interval is not None: self.timeout_add(self.update_interval, self.timer_setup) # We can change the update interval by returning something from .tick() elif update_interval: self.timeout_add(update_interval, self.timer_setup) # If update_interval is False, we won't re-call def _configure(self, qtile, bar): should_tick = self.configured _TextBox._configure(self, qtile, bar) # Update when we are being re-configured. if should_tick: self.tick() def button_press(self, x, y, button): self.tick() _TextBox.button_press(self, x, y, button) def poll(self): return 'N/A' def tick(self): text = self.poll() self.update(text) class ThreadPoolText(_TextBox): """ A common interface for wrapping blocking events which when triggered will update a textbox. The poll method is intended to wrap a blocking function which may take quite a while to return anything. It will be executed as a future and should return updated text when completed. It may also return None to disable any further updates. param: text - Initial text to display. """ defaults = [ ("update_interval", 600, "Update interval in seconds, if none, the " "widget updates whenever it's done'."), ] # type: List[Tuple[str, Any, str]] def __init__(self, text, **config): super().__init__(text, width=bar.CALCULATED, **config) self.add_defaults(ThreadPoolText.defaults) def timer_setup(self): def on_done(future): try: result = future.result() except Exception: result = None logger.exception('poll() raised exceptions, not rescheduling') if result is not None: try: self.update(result) if self.update_interval is not None: self.timeout_add(self.update_interval, self.timer_setup) else: self.timer_setup() except Exception: logger.exception('Failed to reschedule.') else: logger.warning('poll() returned None, not rescheduling') future = self.qtile.run_in_executor(self.poll) future.add_done_callback(on_done) def poll(self): pass # these two classes below look SUSPICIOUSLY similar class PaddingMixin(configurable.Configurable): """Mixin that provides padding(_x|_y|) To use it, subclass and add this to __init__: self.add_defaults(base.PaddingMixin.defaults) """ defaults = [ ("padding", 3, "Padding inside the box"), ("padding_x", None, "X Padding. Overrides 'padding' if set"), ("padding_y", None, "Y Padding. Overrides 'padding' if set"), ] # type: List[Tuple[str, Any, str]] padding_x = configurable.ExtraFallback('padding_x', 'padding') padding_y = configurable.ExtraFallback('padding_y', 'padding') class MarginMixin(configurable.Configurable): """Mixin that provides margin(_x|_y|) To use it, subclass and add this to __init__: self.add_defaults(base.MarginMixin.defaults) """ defaults = [ ("margin", 3, "Margin inside the box"), ("margin_x", None, "X Margin. Overrides 'margin' if set"), ("margin_y", None, "Y Margin. Overrides 'margin' if set"), ] # type: List[Tuple[str, Any, str]] margin_x = configurable.ExtraFallback('margin_x', 'margin') margin_y = configurable.ExtraFallback('margin_y', 'margin') class Mirror(_Widget): """ A widget for showing the same widget content in more than one place, for instance, on bars across multiple screens. You don't need to use it directly; instead, just instantiate your widget once and hand it in to multiple bars. For instance:: cpu = widget.CPUGraph() clock = widget.Clock() screens = [ Screen(top=bar.Bar([widget.GroupBox(), cpu, clock])), Screen(top=bar.Bar([widget.GroupBox(), cpu, clock])), ] Widgets can be passed to more than one bar, so that there don't need to be any duplicates executing the same code all the time, and they'll always be visually identical. This works for all widgets that use `drawers` (and nothing else) to display their contents. Currently, this is all widgets except for `Systray`. """ def __init__(self, reflection): _Widget.__init__(self, reflection.length) reflection.draw = self.hook(reflection.draw) self.reflects = reflection self._length = 0 @property def length(self): return self.reflects.length @length.setter def length(self, value): self._length = value def hook(self, draw): def _(): draw() self.draw() return _ def draw(self): if self._length != self.reflects.length: self._length = self.length self.bar.draw() else: self.reflects.drawer.paint_to(self.drawer) self.drawer.draw(offsetx=self.offset, width=self.width) def button_press(self, x, y, button): self.reflects.button_press(x, y, button)
# Copyright (c) 2020 Guangwang Huang # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import os import re import subprocess import pytest import libqtile.bar import libqtile.config import libqtile.layout import libqtile.widget from libqtile.confreader import Config from libqtile.lazy import lazy class ServerConfig(Config): auto_fullscreen = True keys = [ libqtile.config.Key(['mod4'], 'Return', lazy.spawn('xterm')), libqtile.config.Key(['mod4'], 't', lazy.spawn('xterm'), desc='dummy description'), libqtile.config.Key([], 'y', desc='noop'), libqtile.config.KeyChord(['mod4'], 'q', [ libqtile.config.KeyChord([], 'q', [ libqtile.config.Key([], 'a', lazy.togroup('a')), ]), # unnamed libqtile.config.Key([], 'b', lazy.togroup('b')), ], mode='named') ] mouse = [] groups = [ libqtile.config.Group("a"), libqtile.config.Group("b"), libqtile.config.Group("c"), ] layouts = [ libqtile.layout.Stack(num_stacks=1), libqtile.layout.Stack(num_stacks=2), libqtile.layout.Stack(num_stacks=3), ] floating_layout = libqtile.resources.default_config.floating_layout screens = [ libqtile.config.Screen( bottom=libqtile.bar.Bar( [ libqtile.widget.TextBox(name="one"), ], 20 ), ), libqtile.config.Screen( bottom=libqtile.bar.Bar( [ libqtile.widget.TextBox(name="two"), ], 20 ), ) ] server_config = pytest.mark.parametrize("manager", [ServerConfig], indirect=True) def run_qtile_cmd(args): cmd = os.path.join(os.path.dirname(__file__), '..', 'bin', 'qtile') argv = [cmd, "cmd-obj"] argv.extend(args.split()) pipe = subprocess.Popen(argv, stdout=subprocess.PIPE) output, _ = pipe.communicate() return eval(output.decode()) # as returned by pprint.pprint @server_config def test_qtile_cmd(manager): manager.test_window("foo") wid = manager.c.window.info()["id"] for obj in ["window", "group", "screen"]: assert run_qtile_cmd('-s {} -o {} -f info'.format(manager.sockfile, obj)) layout = run_qtile_cmd('-s {} -o layout -f info'.format(manager.sockfile)) assert layout['name'] == 'stack' assert layout['group'] == 'a' window = run_qtile_cmd('-s {} -o window {} -f info'.format(manager.sockfile, wid)) assert window['id'] == wid assert window['name'] == 'foo' assert window['group'] == 'a' group = run_qtile_cmd('-s {} -o group {} -f info'.format(manager.sockfile, 'a')) assert group['name'] == 'a' assert group['screen'] == 0 assert group['layouts'] == ['stack', 'stack', 'stack'] assert group['focus'] == 'foo' assert run_qtile_cmd('-s {} -o screen {} -f info'.format(manager.sockfile, 0)) == \ {'height': 600, 'index': 0, 'width': 800, 'x': 0, 'y': 0} bar = run_qtile_cmd('-s {} -o bar {} -f info'.format(manager.sockfile, 'bottom')) assert bar['height'] == 20 assert bar['width'] == 800 assert bar['size'] == 20 assert bar['position'] == 'bottom' @server_config def test_display_kb(manager): from pprint import pprint cmd = '-s {} -o cmd -f display_kb'.format(manager.sockfile) table = run_qtile_cmd(cmd) print(table) pprint(table) assert table.count('\n') >= 2 assert re.match(r"(?m)^Mode\s{3,}KeySym\s{3,}Mod\s{3,}Command\s{3,}Desc\s*$", table) assert re.search(r"(?m)^<root>\s{3,}Return\s{3,}mod4\s{3,}spawn\('xterm'\)\s*$", table) assert re.search(r"(?m)^<root>\s{3,}t\s{3,}mod4\s{3,}spawn\('xterm'\)\s{3,}dummy description\s*$", table) assert re.search(r"(?m)^<root>\s{3,}q\s{3,}mod4\s{13,}Enter named mode\s*$", table) assert re.search(r"(?m)^named\s{3,}q\s{13,}Enter <unnamed> mode\s*$", table) assert re.search(r"(?m)^named\s{3,}b\s{9,}togroup\('b'\)\s*$", table) assert re.search(r"(?m)^named>_\s{3,}a\s{9,}togroup\('a'\)\s*$", table) assert re.search(r"(?m)^<root>\s{3,}y\s{9,}\s*$", table) is None
ramnes/qtile
test/test_qtile_cmd.py
libqtile/widget/base.py
# -*- coding: utf-8 -*- """Some utility functions.""" # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD (3-clause) from collections.abc import Iterable import os import os.path as op import logging import tempfile from threading import Thread import time import numpy as np from .check import _check_option from .config import get_config from ._logging import logger class ProgressBar(object): """Generate a command-line progressbar. Parameters ---------- iterable : iterable | int | None The iterable to use. Can also be an int for backward compatibility (acts like ``max_value``). initial_value : int Initial value of process, useful when resuming process from a specific value, defaults to 0. mesg : str Message to include at end of progress bar. max_total_width : int | str Maximum total message width. Can use "auto" (default) to try to set a sane value based on the current terminal width. max_value : int | None The max value. If None, the length of ``iterable`` will be used. **kwargs : dict Additional keyword arguments for tqdm. """ def __init__(self, iterable=None, initial_value=0, mesg=None, max_total_width='auto', max_value=None, **kwargs): # noqa: D102 # The following mimics this, but with configurable module to use # from ..externals.tqdm import auto from ..externals import tqdm which_tqdm = get_config('MNE_TQDM', 'tqdm.auto') _check_option('MNE_TQDM', which_tqdm[:5], ('tqdm', 'tqdm.', 'off'), extra='beginning') logger.debug(f'Using ProgressBar with {which_tqdm}') if which_tqdm not in ('tqdm', 'off'): tqdm = getattr(tqdm, which_tqdm.split('.', 1)[1]) tqdm = tqdm.tqdm defaults = dict( leave=True, mininterval=0.016, miniters=1, smoothing=0.05, bar_format='{percentage:3.0f}%|{bar}| {desc} : {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt:>11}{postfix}]', # noqa: E501 ) for key, val in defaults.items(): if key not in kwargs: kwargs.update({key: val}) if isinstance(iterable, Iterable): self.iterable = iterable if max_value is None: self.max_value = len(iterable) else: self.max_value = max_value else: # ignore max_value then self.max_value = int(iterable) self.iterable = None if max_total_width == 'auto': max_total_width = None # tqdm's auto with tempfile.NamedTemporaryFile('wb', prefix='tmp_mne_prog') as tf: self._mmap_fname = tf.name del tf # should remove the file self._mmap = None disable = logger.level > logging.INFO or which_tqdm == 'off' self._tqdm = tqdm( iterable=self.iterable, desc=mesg, total=self.max_value, initial=initial_value, ncols=max_total_width, disable=disable, **kwargs) def update(self, cur_value): """Update progressbar with current value of process. Parameters ---------- cur_value : number Current value of process. Should be <= max_value (but this is not enforced). The percent of the progressbar will be computed as ``(cur_value / max_value) * 100``. """ self.update_with_increment_value(cur_value - self._tqdm.n) def update_with_increment_value(self, increment_value): """Update progressbar with an increment. Parameters ---------- increment_value : int Value of the increment of process. The percent of the progressbar will be computed as ``(self.cur_value + increment_value / max_value) * 100``. """ self._tqdm.update(increment_value) def __iter__(self): """Iterate to auto-increment the pbar with 1.""" for x in self._tqdm: yield x def subset(self, idx): """Make a joblib-friendly index subset updater. Parameters ---------- idx : ndarray List of indices for this subset. Returns ------- updater : instance of PBSubsetUpdater Class with a ``.update(ii)`` method. """ return _PBSubsetUpdater(self, idx) def __enter__(self): # noqa: D105 # This should only be used with pb.subset and parallelization if op.isfile(self._mmap_fname): os.remove(self._mmap_fname) # prevent corner cases where self.max_value == 0 self._mmap = np.memmap(self._mmap_fname, bool, 'w+', shape=max(self.max_value, 1)) self.update(0) # must be zero as we just created the memmap # We need to control how the pickled bars exit: remove print statements self._thread = _UpdateThread(self) self._thread.start() return self def __exit__(self, type_, value, traceback): # noqa: D105 # Restore exit behavior for our one from the main thread self.update(self._mmap.sum()) self._tqdm.close() self._thread._mne_run = False self._thread.join() self._mmap = None if op.isfile(self._mmap_fname): os.remove(self._mmap_fname) def __del__(self): """Ensure output completes.""" if getattr(self, '_tqdm', None) is not None: self._tqdm.close() class _UpdateThread(Thread): def __init__(self, pb): super(_UpdateThread, self).__init__(daemon=True) self._mne_run = True self._mne_pb = pb def run(self): while self._mne_run: self._mne_pb.update(self._mne_pb._mmap.sum()) time.sleep(1. / 30.) # 30 Hz refresh is plenty class _PBSubsetUpdater(object): def __init__(self, pb, idx): self.mmap = pb._mmap self.idx = idx def update(self, ii): self.mmap[self.idx[ii - 1]] = True
# Authors: Eric Larson <larson.eric.d@gmail.com> # Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD (3-clause) from functools import partial import os import numpy as np from scipy import sparse, linalg, stats from numpy.testing import (assert_equal, assert_array_equal, assert_array_almost_equal, assert_allclose) import pytest from mne import (SourceEstimate, VolSourceEstimate, MixedSourceEstimate, SourceSpaces) from mne.parallel import _force_serial from mne.stats import ttest_ind_no_p, combine_adjacency from mne.stats.cluster_level import (permutation_cluster_test, f_oneway, permutation_cluster_1samp_test, spatio_temporal_cluster_test, spatio_temporal_cluster_1samp_test, ttest_1samp_no_p, summarize_clusters_stc) from mne.utils import catch_logging, check_version, requires_sklearn n_space = 50 def _get_conditions(): noise_level = 20 n_time_1 = 20 n_time_2 = 13 normfactor = np.hanning(20).sum() rng = np.random.RandomState(42) condition1_1d = rng.randn(n_time_1, n_space) * noise_level for c in condition1_1d: c[:] = np.convolve(c, np.hanning(20), mode="same") / normfactor condition2_1d = rng.randn(n_time_2, n_space) * noise_level for c in condition2_1d: c[:] = np.convolve(c, np.hanning(20), mode="same") / normfactor pseudoekp = 10 * np.hanning(25)[None, :] condition1_1d[:, 25:] += pseudoekp condition2_1d[:, 25:] -= pseudoekp condition1_2d = condition1_1d[:, :, np.newaxis] condition2_2d = condition2_1d[:, :, np.newaxis] return condition1_1d, condition2_1d, condition1_2d, condition2_2d def test_thresholds(numba_conditional): """Test automatic threshold calculations.""" # within subjects rng = np.random.RandomState(0) X = rng.randn(10, 1, 1) + 0.08 want_thresh = -stats.t.ppf(0.025, len(X) - 1) assert 0.03 < stats.ttest_1samp(X[:, 0, 0], 0)[1] < 0.05 my_fun = partial(ttest_1samp_no_p) with catch_logging() as log: with pytest.warns(RuntimeWarning, match='threshold is only valid'): out = permutation_cluster_1samp_test( X, stat_fun=my_fun, seed=0, verbose=True, out_type='mask') log = log.getvalue() assert str(want_thresh)[:6] in log assert len(out[1]) == 1 # 1 cluster assert_allclose(out[2], 0.033203, atol=1e-6) # between subjects Y = rng.randn(10, 1, 1) Z = rng.randn(10, 1, 1) - 0.7 X = [X, Y, Z] want_thresh = stats.f.ppf(1. - 0.05, 2, sum(len(a) for a in X) - len(X)) p = stats.f_oneway(*X)[1] assert 0.03 < p < 0.05 my_fun = partial(f_oneway) # just to make the check fail with catch_logging() as log: with pytest.warns(RuntimeWarning, match='threshold is only valid'): out = permutation_cluster_test(X, tail=1, stat_fun=my_fun, seed=0, verbose=True, out_type='mask') log = log.getvalue() assert str(want_thresh)[:6] in log assert len(out[1]) == 1 # 1 cluster assert_allclose(out[2], 0.041992, atol=1e-6) with pytest.warns(RuntimeWarning, match='Ignoring argument "tail"'): permutation_cluster_test(X, tail=0, out_type='mask') # nan handling in TFCE X = np.repeat(X[0], 2, axis=1) X[:, 1] = 0 with pytest.warns(RuntimeWarning, match='invalid value'): # NumPy out = permutation_cluster_1samp_test( X, seed=0, threshold=dict(start=0, step=0.1), out_type='mask') assert (out[2] < 0.05).any() assert not (out[2] < 0.05).all() X[:, 0] = 0 with pytest.raises(RuntimeError, match='finite'): with np.errstate(invalid='ignore'): permutation_cluster_1samp_test( X, seed=0, threshold=dict(start=0, step=0.1), buffer_size=None, out_type='mask') def test_cache_dir(tmpdir, numba_conditional): """Test use of cache dir.""" tempdir = str(tmpdir) orig_dir = os.getenv('MNE_CACHE_DIR', None) orig_size = os.getenv('MNE_MEMMAP_MIN_SIZE', None) rng = np.random.RandomState(0) X = rng.randn(9, 2, 10) try: os.environ['MNE_MEMMAP_MIN_SIZE'] = '1K' os.environ['MNE_CACHE_DIR'] = tempdir # Fix error for #1507: in-place when memmapping with catch_logging() as log_file: permutation_cluster_1samp_test( X, buffer_size=None, n_jobs=2, n_permutations=1, seed=0, stat_fun=ttest_1samp_no_p, verbose=False, out_type='mask') assert 'independently' not in log_file.getvalue() # ensure that non-independence yields warning stat_fun = partial(ttest_1samp_no_p, sigma=1e-3) if check_version('numpy', '1.17'): random_state = np.random.default_rng(0) else: random_state = 0 with pytest.warns(RuntimeWarning, match='independently'): permutation_cluster_1samp_test( X, buffer_size=10, n_jobs=2, n_permutations=1, seed=random_state, stat_fun=stat_fun, verbose=False, out_type='mask') finally: if orig_dir is not None: os.environ['MNE_CACHE_DIR'] = orig_dir else: del os.environ['MNE_CACHE_DIR'] if orig_size is not None: os.environ['MNE_MEMMAP_MIN_SIZE'] = orig_size else: del os.environ['MNE_MEMMAP_MIN_SIZE'] def test_permutation_large_n_samples(numba_conditional): """Test that non-replacement works with large N.""" X = np.random.RandomState(0).randn(72, 1) + 1 for n_samples in (11, 72): tails = (0, 1) if n_samples <= 20 else (0,) for tail in tails: H0 = permutation_cluster_1samp_test( X[:n_samples], threshold=1e-4, tail=tail, out_type='mask')[-1] assert H0.shape == (1024,) assert len(np.unique(H0)) >= 1024 - (H0 == 0).sum() def test_permutation_step_down_p(numba_conditional): """Test cluster level permutations with step_down_p.""" rng = np.random.RandomState(0) # subjects, time points, spatial points X = rng.randn(9, 2, 10) # add some significant points X[:, 0:2, 0:2] += 2 # span two time points and two spatial points X[:, 1, 5:9] += 0.5 # span four time points with 4x smaller amplitude thresh = 2 # make sure it works when we use ALL points in step-down t, clusters, p, H0 = \ permutation_cluster_1samp_test(X, threshold=thresh, step_down_p=1.0, out_type='mask') # make sure using step-down will actually yield improvements sometimes t, clusters, p_old, H0 = \ permutation_cluster_1samp_test(X, threshold=thresh, step_down_p=0.0, out_type='mask') assert_equal(np.sum(p_old < 0.05), 1) # just spatial cluster p_min = np.min(p_old) assert_allclose(p_min, 0.003906, atol=1e-6) t, clusters, p_new, H0 = \ permutation_cluster_1samp_test(X, threshold=thresh, step_down_p=0.05, out_type='mask') assert_equal(np.sum(p_new < 0.05), 2) # time one rescued assert np.all(p_old >= p_new) p_next = p_new[(p_new > 0.004) & (p_new < 0.05)][0] assert_allclose(p_next, 0.015625, atol=1e-6) def test_cluster_permutation_test(numba_conditional): """Test cluster level permutations tests.""" condition1_1d, condition2_1d, condition1_2d, condition2_2d = \ _get_conditions() for condition1, condition2 in zip((condition1_1d, condition1_2d), (condition2_1d, condition2_2d)): T_obs, clusters, cluster_p_values, hist = permutation_cluster_test( [condition1, condition2], n_permutations=100, tail=1, seed=1, buffer_size=None, out_type='mask') p_min = np.min(cluster_p_values) assert_equal(np.sum(cluster_p_values < 0.05), 1) assert_allclose(p_min, 0.01, atol=1e-6) # test with 2 jobs and buffer_size enabled buffer_size = condition1.shape[1] // 10 T_obs, clusters, cluster_p_values_buff, hist =\ permutation_cluster_test([condition1, condition2], n_permutations=100, tail=1, seed=1, n_jobs=2, buffer_size=buffer_size, out_type='mask') assert_array_equal(cluster_p_values, cluster_p_values_buff) def stat_fun(X, Y): return stats.f_oneway(X, Y)[0] with pytest.warns(RuntimeWarning, match='is only valid'): permutation_cluster_test([condition1, condition2], n_permutations=1, stat_fun=stat_fun, out_type='mask') @pytest.mark.parametrize('stat_fun', [ ttest_1samp_no_p, partial(ttest_1samp_no_p, sigma=1e-1) ]) def test_cluster_permutation_t_test(numba_conditional, stat_fun): """Test cluster level permutations T-test.""" condition1_1d, condition2_1d, condition1_2d, condition2_2d = \ _get_conditions() # use a very large sigma to make sure Ts are not independent for condition1, p in ((condition1_1d, 0.01), (condition1_2d, 0.01)): # these are so significant we can get away with fewer perms T_obs, clusters, cluster_p_values, hist =\ permutation_cluster_1samp_test(condition1, n_permutations=100, tail=0, seed=1, out_type='mask', buffer_size=None) assert_equal(np.sum(cluster_p_values < 0.05), 1) p_min = np.min(cluster_p_values) assert_allclose(p_min, p, atol=1e-6) T_obs_pos, c_1, cluster_p_values_pos, _ =\ permutation_cluster_1samp_test(condition1, n_permutations=100, tail=1, threshold=1.67, seed=1, stat_fun=stat_fun, out_type='mask', buffer_size=None) T_obs_neg, _, cluster_p_values_neg, _ =\ permutation_cluster_1samp_test(-condition1, n_permutations=100, tail=-1, threshold=-1.67, seed=1, stat_fun=stat_fun, buffer_size=None, out_type='mask') assert_array_equal(T_obs_pos, -T_obs_neg) assert_array_equal(cluster_p_values_pos < 0.05, cluster_p_values_neg < 0.05) # test with 2 jobs and buffer_size enabled buffer_size = condition1.shape[1] // 10 with pytest.warns(None): # sometimes "independently" T_obs_neg_buff, _, cluster_p_values_neg_buff, _ = \ permutation_cluster_1samp_test( -condition1, n_permutations=100, tail=-1, out_type='mask', threshold=-1.67, seed=1, n_jobs=2, stat_fun=stat_fun, buffer_size=buffer_size) assert_array_equal(T_obs_neg, T_obs_neg_buff) assert_array_equal(cluster_p_values_neg, cluster_p_values_neg_buff) # Bad stat_fun with pytest.raises(TypeError, match='must be .* ndarray'): permutation_cluster_1samp_test( condition1, threshold=1, stat_fun=lambda x: None, out_type='mask') with pytest.raises(ValueError, match='not compatible'): permutation_cluster_1samp_test( condition1, threshold=1, stat_fun=lambda x: stat_fun(x)[:-1], out_type='mask') @requires_sklearn def test_cluster_permutation_with_adjacency(numba_conditional): """Test cluster level permutations with adjacency matrix.""" from sklearn.feature_extraction.image import grid_to_graph condition1_1d, condition2_1d, condition1_2d, condition2_2d = \ _get_conditions() n_pts = condition1_1d.shape[1] # we don't care about p-values in any of these, so do fewer permutations args = dict(seed=None, max_step=1, exclude=None, out_type='mask', step_down_p=0, t_power=1, threshold=1.67, check_disjoint=False, n_permutations=50) did_warn = False for X1d, X2d, func, spatio_temporal_func in \ [(condition1_1d, condition1_2d, permutation_cluster_1samp_test, spatio_temporal_cluster_1samp_test), ([condition1_1d, condition2_1d], [condition1_2d, condition2_2d], permutation_cluster_test, spatio_temporal_cluster_test)]: out = func(X1d, **args) adjacency = grid_to_graph(1, n_pts) out_adjacency = func(X1d, adjacency=adjacency, **args) assert_array_equal(out[0], out_adjacency[0]) for a, b in zip(out_adjacency[1], out[1]): assert_array_equal(out[0][a], out[0][b]) assert np.all(a[b]) # test spatio-temporal w/o time adjacency (repeat spatial pattern) adjacency_2 = sparse.coo_matrix( linalg.block_diag(adjacency.asfptype().todense(), adjacency.asfptype().todense())) # nesting here is time then space: adjacency_2a = combine_adjacency(np.eye(2), adjacency) assert_array_equal(adjacency_2.toarray().astype(bool), adjacency_2a.toarray().astype(bool)) if isinstance(X1d, list): X1d_2 = [np.concatenate((x, x), axis=1) for x in X1d] else: X1d_2 = np.concatenate((X1d, X1d), axis=1) out_adjacency_2 = func(X1d_2, adjacency=adjacency_2, **args) # make sure we were operating on the same values split = len(out[0]) assert_array_equal(out[0], out_adjacency_2[0][:split]) assert_array_equal(out[0], out_adjacency_2[0][split:]) # make sure we really got 2x the number of original clusters n_clust_orig = len(out[1]) assert len(out_adjacency_2[1]) == 2 * n_clust_orig # Make sure that we got the old ones back data_1 = {np.sum(out[0][b[:n_pts]]) for b in out[1]} data_2 = {np.sum(out_adjacency_2[0][a]) for a in out_adjacency_2[1][:]} assert len(data_1.intersection(data_2)) == len(data_1) # now use the other algorithm if isinstance(X1d, list): X1d_3 = [np.reshape(x, (-1, 2, n_space)) for x in X1d_2] else: X1d_3 = np.reshape(X1d_2, (-1, 2, n_space)) out_adjacency_3 = spatio_temporal_func( X1d_3, n_permutations=50, adjacency=adjacency, max_step=0, threshold=1.67, check_disjoint=True) # make sure we were operating on the same values split = len(out[0]) assert_array_equal(out[0], out_adjacency_3[0][0]) assert_array_equal(out[0], out_adjacency_3[0][1]) # make sure we really got 2x the number of original clusters assert len(out_adjacency_3[1]) == 2 * n_clust_orig # Make sure that we got the old ones back data_1 = {np.sum(out[0][b[:n_pts]]) for b in out[1]} data_2 = {np.sum(out_adjacency_3[0][a[0], a[1]]) for a in out_adjacency_3[1]} assert len(data_1.intersection(data_2)) == len(data_1) # test new versus old method out_adjacency_4 = spatio_temporal_func( X1d_3, n_permutations=50, adjacency=adjacency, max_step=2, threshold=1.67) out_adjacency_5 = spatio_temporal_func( X1d_3, n_permutations=50, adjacency=adjacency, max_step=1, threshold=1.67) # clusters could be in a different order sums_4 = [np.sum(out_adjacency_4[0][a]) for a in out_adjacency_4[1]] sums_5 = [np.sum(out_adjacency_4[0][a]) for a in out_adjacency_5[1]] sums_4 = np.sort(sums_4) sums_5 = np.sort(sums_5) assert_array_almost_equal(sums_4, sums_5) if not _force_serial: pytest.raises(ValueError, spatio_temporal_func, X1d_3, n_permutations=1, adjacency=adjacency, max_step=1, threshold=1.67, n_jobs=-1000) # not enough TFCE params with pytest.raises(KeyError, match='threshold, if dict, must have'): spatio_temporal_func( X1d_3, adjacency=adjacency, threshold=dict(me='hello')) # too extreme a start threshold with pytest.warns(None) as w: spatio_temporal_func(X1d_3, adjacency=adjacency, threshold=dict(start=10, step=1)) if not did_warn: assert len(w) == 1 did_warn = True with pytest.raises(ValueError, match='threshold.*<= 0 for tail == -1'): spatio_temporal_func( X1d_3, adjacency=adjacency, tail=-1, threshold=dict(start=1, step=-1)) with pytest.warns(RuntimeWarning, match='threshold.* is more extreme'): spatio_temporal_func( X1d_3, adjacency=adjacency, tail=1, threshold=dict(start=100, step=1)) bad_con = adjacency.todense() with pytest.raises(ValueError, match='must be a SciPy sparse matrix'): spatio_temporal_func( X1d_3, n_permutations=50, adjacency=bad_con, max_step=1, threshold=1.67) bad_con = adjacency.tocsr()[:-1, :-1].tocoo() with pytest.raises(ValueError, match='adjacency.*the correct size'): spatio_temporal_func( X1d_3, n_permutations=50, adjacency=bad_con, max_step=1, threshold=1.67) with pytest.raises(TypeError, match='must be a'): spatio_temporal_func( X1d_3, adjacency=adjacency, threshold=[]) with pytest.raises(ValueError, match='Invalid value for the \'tail\''): with pytest.warns(None): # sometimes ignoring tail spatio_temporal_func( X1d_3, adjacency=adjacency, tail=2) # make sure it actually found a significant point out_adjacency_6 = spatio_temporal_func( X1d_3, n_permutations=50, adjacency=adjacency, max_step=1, threshold=dict(start=1, step=1)) assert np.min(out_adjacency_6[2]) < 0.05 with pytest.raises(ValueError, match='not compatible'): with pytest.warns(RuntimeWarning, match='No clusters'): spatio_temporal_func( X1d_3, n_permutations=50, adjacency=adjacency, threshold=1e-3, stat_fun=lambda *x: f_oneway(*x)[:-1], buffer_size=None) @pytest.mark.parametrize('threshold', [ 0.1, pytest.param(dict(start=0., step=0.5), id='TFCE'), ]) @pytest.mark.parametrize('kind', ('1samp', 'ind')) def test_permutation_cluster_signs(threshold, kind): """Test cluster signs.""" # difference between two conditions for 3 subjects x 2 vertices x 2 times X = np.array([[[-10, 5], [-2, -7]], [[-4, 5], [-8, -0]], [[-6, 3], [-4, -2]]], float) want_signs = np.sign(np.mean(X, axis=0)) n_permutations = 1 if kind == '1samp': func = permutation_cluster_1samp_test stat_fun = ttest_1samp_no_p use_X = X else: assert kind == 'ind' func = permutation_cluster_test stat_fun = ttest_ind_no_p use_X = [X, np.random.RandomState(0).randn(*X.shape) * 0.1] tobs, clu, clu_pvalues, _ = func( use_X, n_permutations=n_permutations, threshold=threshold, tail=0, stat_fun=stat_fun, out_type='mask') clu_signs = np.zeros(X.shape[1:]) used = np.zeros(X.shape[1:]) assert len(clu) == len(clu_pvalues) for c, p in zip(clu, clu_pvalues): assert not used[c].any() assert len(np.unique(np.sign(tobs[c]))) == 1 clu_signs[c] = np.sign(tobs[c])[0] used[c] = True assert used.all() assert clu_signs.all() assert_array_equal(np.sign(tobs), want_signs) assert_array_equal(clu_signs, want_signs) @requires_sklearn def test_permutation_adjacency_equiv(numba_conditional): """Test cluster level permutations with and without adjacency.""" from sklearn.feature_extraction.image import grid_to_graph rng = np.random.RandomState(0) # subjects, time points, spatial points n_time = 2 n_space = 4 X = rng.randn(6, n_time, n_space) # add some significant points X[:, :, 0:2] += 10 # span two time points and two spatial points X[:, 1, 3] += 20 # span one time point max_steps = [1, 1, 1, 2, 1] # This will run full algorithm in two ways, then the ST-algorithm in 2 ways # All of these should give the same results adjs = [None, grid_to_graph(n_time, n_space), grid_to_graph(1, n_space), grid_to_graph(1, n_space), None] stat_map = None thresholds = [2, 2, 2, 2, dict(start=0.01, step=1.0)] sig_counts = [2, 2, 2, 2, 5] stat_fun = partial(ttest_1samp_no_p, sigma=1e-3) cs = None ps = None for thresh, count, max_step, adj in zip(thresholds, sig_counts, max_steps, adjs): t, clusters, p, H0 = \ permutation_cluster_1samp_test( X, threshold=thresh, adjacency=adj, n_jobs=2, max_step=max_step, stat_fun=stat_fun, seed=0, out_type='mask') # make sure our output datatype is correct assert isinstance(clusters[0], np.ndarray) assert clusters[0].dtype == bool assert_array_equal(clusters[0].shape, X.shape[1:]) # make sure all comparisons were done; for TFCE, no perm # should come up empty inds = np.where(p < 0.05)[0] assert_equal(len(inds), count) assert_allclose(p[inds], 0.03125, atol=1e-6) if isinstance(thresh, dict): assert_equal(len(clusters), n_time * n_space) assert np.all(H0 != 0) continue this_cs = [clusters[ii] for ii in inds] this_ps = p[inds] this_stat_map = np.zeros((n_time, n_space), dtype=bool) for ci, c in enumerate(this_cs): if isinstance(c, tuple): this_c = np.zeros((n_time, n_space), bool) for x, y in zip(c[0], c[1]): this_stat_map[x, y] = True this_c[x, y] = True this_cs[ci] = this_c c = this_c this_stat_map[c] = True if cs is None: ps = this_ps cs = this_cs if stat_map is None: stat_map = this_stat_map assert_array_equal(ps, this_ps) assert len(cs) == len(this_cs) for c1, c2 in zip(cs, this_cs): assert_array_equal(c1, c2) assert_array_equal(stat_map, this_stat_map) @requires_sklearn def test_spatio_temporal_cluster_adjacency(numba_conditional): """Test spatio-temporal cluster permutations.""" from sklearn.feature_extraction.image import grid_to_graph condition1_1d, condition2_1d, condition1_2d, condition2_2d = \ _get_conditions() rng = np.random.RandomState(0) noise1_2d = rng.randn(condition1_2d.shape[0], condition1_2d.shape[1], 10) data1_2d = np.transpose(np.dstack((condition1_2d, noise1_2d)), [0, 2, 1]) noise2_d2 = rng.randn(condition2_2d.shape[0], condition2_2d.shape[1], 10) data2_2d = np.transpose(np.dstack((condition2_2d, noise2_d2)), [0, 2, 1]) adj = grid_to_graph(data1_2d.shape[-1], 1) threshold = dict(start=4.0, step=2) T_obs, clusters, p_values_adj, hist = \ spatio_temporal_cluster_test([data1_2d, data2_2d], adjacency=adj, n_permutations=50, tail=1, seed=1, threshold=threshold, buffer_size=None) buffer_size = data1_2d.size // 10 T_obs, clusters, p_values_no_adj, hist = \ spatio_temporal_cluster_test([data1_2d, data2_2d], n_permutations=50, tail=1, seed=1, threshold=threshold, n_jobs=2, buffer_size=buffer_size) assert_equal(np.sum(p_values_adj < 0.05), np.sum(p_values_no_adj < 0.05)) # make sure results are the same without buffer_size T_obs, clusters, p_values2, hist2 = \ spatio_temporal_cluster_test([data1_2d, data2_2d], n_permutations=50, tail=1, seed=1, threshold=threshold, n_jobs=2, buffer_size=None) assert_array_equal(p_values_no_adj, p_values2) pytest.raises(ValueError, spatio_temporal_cluster_test, [data1_2d, data2_2d], tail=1, threshold=-2.) pytest.raises(ValueError, spatio_temporal_cluster_test, [data1_2d, data2_2d], tail=-1, threshold=2.) pytest.raises(ValueError, spatio_temporal_cluster_test, [data1_2d, data2_2d], tail=0, threshold=-1) def ttest_1samp(X): """Return T-values.""" return stats.ttest_1samp(X, 0)[0] @pytest.mark.parametrize('kind', ('surface', 'volume', 'mixed')) def test_summarize_clusters(kind): """Test cluster summary stcs.""" src_surf = SourceSpaces( [dict(vertno=np.arange(10242), type='surf') for _ in range(2)]) assert src_surf.kind == 'surface' src_vol = SourceSpaces( [dict(vertno=np.arange(10), type='vol')]) assert src_vol.kind == 'volume' if kind == 'surface': src = src_surf klass = SourceEstimate elif kind == 'volume': src = src_vol klass = VolSourceEstimate else: assert kind == 'mixed' src = src_surf + src_vol klass = MixedSourceEstimate n_vertices = sum(len(s['vertno']) for s in src) clu = (np.random.random([1, n_vertices]), [(np.array([0]), np.array([0, 2, 4]))], np.array([0.02, 0.1]), np.array([12, -14, 30])) kwargs = dict() if kind == 'volume': with pytest.raises(ValueError, match='did not match'): summarize_clusters_stc(clu) assert len(src) == 1 kwargs['vertices'] = [src[0]['vertno']] elif kind == 'mixed': kwargs['vertices'] = src stc_sum = summarize_clusters_stc(clu, **kwargs) assert isinstance(stc_sum, klass) assert stc_sum.data.shape[1] == 2 clu[2][0] = 0.3 with pytest.raises(RuntimeError, match='No significant'): summarize_clusters_stc(clu, **kwargs) def test_permutation_test_H0(numba_conditional): """Test that H0 is populated properly during testing.""" rng = np.random.RandomState(0) data = rng.rand(7, 10, 1) - 0.5 with pytest.warns(RuntimeWarning, match='No clusters found'): t, clust, p, h0 = spatio_temporal_cluster_1samp_test( data, threshold=100, n_permutations=1024, seed=rng) assert_equal(len(h0), 0) for n_permutations in (1024, 65, 64, 63): t, clust, p, h0 = spatio_temporal_cluster_1samp_test( data, threshold=0.1, n_permutations=n_permutations, seed=rng) assert_equal(len(h0), min(n_permutations, 64)) assert isinstance(clust[0], tuple) # sets of indices for tail, thresh in zip((-1, 0, 1), (-0.1, 0.1, 0.1)): t, clust, p, h0 = spatio_temporal_cluster_1samp_test( data, threshold=thresh, seed=rng, tail=tail, out_type='mask') assert isinstance(clust[0], np.ndarray) # bool mask # same as "128 if tail else 64" assert_equal(len(h0), 2 ** (7 - (tail == 0))) # exact test def test_tfce_thresholds(numba_conditional): """Test TFCE thresholds.""" rng = np.random.RandomState(0) data = rng.randn(7, 10, 1) - 0.5 # if tail==-1, step must also be negative with pytest.raises(ValueError, match='must be < 0 for tail == -1'): permutation_cluster_1samp_test( data, tail=-1, out_type='mask', threshold=dict(start=0, step=0.1)) # this works (smoke test) permutation_cluster_1samp_test(data, tail=-1, out_type='mask', threshold=dict(start=0, step=-0.1)) # thresholds must be monotonically increasing with pytest.raises(ValueError, match='must be monotonically increasing'): permutation_cluster_1samp_test( data, tail=1, out_type='mask', threshold=dict(start=1, step=-0.5)) # 1D gives slices, 2D+ gives boolean masks @pytest.mark.parametrize('shape', ((11,), (11, 3), (11, 1, 2))) @pytest.mark.parametrize('out_type', ('mask', 'indices')) @pytest.mark.parametrize('adjacency', (None, 'sparse')) def test_output_equiv(shape, out_type, adjacency): """Test equivalence of output types.""" rng = np.random.RandomState(0) n_subjects = 10 data = rng.randn(n_subjects, *shape) data -= data.mean(axis=0, keepdims=True) data[:, 2:4] += 2 data[:, 6:9] += 2 want_mask = np.zeros(shape, int) want_mask[2:4] = 1 want_mask[6:9] = 2 if adjacency is not None: assert adjacency == 'sparse' adjacency = combine_adjacency(*shape) clusters = permutation_cluster_1samp_test( X=data, n_permutations=1, adjacency=adjacency, out_type=out_type)[1] got_mask = np.zeros_like(want_mask) for n, clu in enumerate(clusters, 1): if out_type == 'mask': if len(shape) == 1 and adjacency is None: assert isinstance(clu, tuple) assert len(clu) == 1 assert isinstance(clu[0], slice) else: assert isinstance(clu, np.ndarray) assert clu.dtype == bool assert clu.shape == shape got_mask[clu] = n else: assert isinstance(clu, tuple) for c in clu: assert isinstance(c, np.ndarray) assert c.dtype.kind == 'i' assert out_type == 'indices' got_mask[np.ix_(*clu)] = n assert_array_equal(got_mask, want_mask)
kambysese/mne-python
mne/stats/tests/test_cluster_level.py
mne/utils/progressbar.py
"""Compute Linearly constrained minimum variance (LCMV) beamformer.""" # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Roman Goj <roman.goj@gmail.com> # Britta Westner <britta.wstnr@gmail.com> # # License: BSD (3-clause) import numpy as np from ..rank import compute_rank from ..io.meas_info import _simplify_info from ..io.pick import pick_channels_cov, pick_info from ..forward import _subject_from_forward from ..minimum_norm.inverse import combine_xyz, _check_reference, _check_depth from ..source_estimate import _make_stc, _get_src_type from ..utils import logger, verbose, _check_channels_spatial_filter from ..utils import _check_one_ch_type, _check_info_inv from ._compute_beamformer import ( _prepare_beamformer_input, _compute_power, _compute_beamformer, _check_src_type, Beamformer, _proj_whiten_data) @verbose def make_lcmv(info, forward, data_cov, reg=0.05, noise_cov=None, label=None, pick_ori=None, rank='info', weight_norm='unit-noise-gain-invariant', reduce_rank=False, depth=None, inversion='matrix', verbose=None): """Compute LCMV spatial filter. Parameters ---------- info : instance of Info The measurement info to specify the channels to include. Bad channels in info['bads'] are not used. forward : instance of Forward Forward operator. data_cov : instance of Covariance The data covariance. reg : float The regularization for the whitened data covariance. noise_cov : instance of Covariance The noise covariance. If provided, whitening will be done. Providing a noise covariance is mandatory if you mix sensor types, e.g. gradiometers with magnetometers or EEG with MEG. label : instance of Label Restricts the LCMV solution to a given label. %(bf_pick_ori)s - ``'vector'`` Keeps the currents for each direction separate %(rank_info)s %(weight_norm)s Defaults to ``'unit-noise-gain-invariant'``. %(reduce_rank)s %(depth)s .. versionadded:: 0.18 %(bf_inversion)s .. versionadded:: 0.21 %(verbose)s Returns ------- filters : instance of Beamformer Dictionary containing filter weights from LCMV beamformer. Contains the following keys: 'kind' : str The type of beamformer, in this case 'LCMV'. 'weights' : array The filter weights of the beamformer. 'data_cov' : instance of Covariance The data covariance matrix used to compute the beamformer. 'noise_cov' : instance of Covariance | None The noise covariance matrix used to compute the beamformer. 'whitener' : None | ndarray, shape (n_channels, n_channels) Whitening matrix, provided if whitening was applied to the covariance matrix and leadfield during computation of the beamformer weights. 'weight_norm' : str | None Type of weight normalization used to compute the filter weights. 'pick-ori' : None | 'max-power' | 'normal' | 'vector' The orientation in which the beamformer filters were computed. 'ch_names' : list of str Channels used to compute the beamformer. 'proj' : array Projections used to compute the beamformer. 'is_ssp' : bool If True, projections were applied prior to filter computation. 'vertices' : list Vertices for which the filter weights were computed. 'is_free_ori' : bool If True, the filter was computed with free source orientation. 'n_sources' : int Number of source location for which the filter weight were computed. 'src_type' : str Type of source space. 'source_nn' : ndarray, shape (n_sources, 3) For each source location, the surface normal. 'proj' : ndarray, shape (n_channels, n_channels) Projections used to compute the beamformer. 'subject' : str The subject ID. 'rank' : int The rank of the data covariance matrix used to compute the beamformer weights. 'max-power-ori' : ndarray, shape (n_sources, 3) | None When pick_ori='max-power', this fields contains the estimated direction of maximum power at each source location. 'inversion' : 'single' | 'matrix' Whether the spatial filters were computed for each dipole separately or jointly for all dipoles at each vertex using a matrix inversion. Notes ----- The original reference is :footcite:`VanVeenEtAl1997`. To obtain the Sekihara unit-noise-gain vector beamformer, you should use ``weight_norm='unit-noise-gain', pick_ori='vector'`` followed by :meth:`vec_stc.project('pca', src) <mne.VectorSourceEstimate.project>`. .. versionchanged:: 0.21 The computations were extensively reworked, and the default for ``weight_norm`` was set to ``'unit-noise-gain-invariant'``. References ---------- .. footbibliography:: """ # check number of sensor types present in the data and ensure a noise cov info = _simplify_info(info) noise_cov, _, allow_mismatch = _check_one_ch_type( 'lcmv', info, forward, data_cov, noise_cov) # XXX we need this extra picking step (can't just rely on minimum norm's # because there can be a mismatch. Should probably add an extra arg to # _prepare_beamformer_input at some point (later) picks = _check_info_inv(info, forward, data_cov, noise_cov) info = pick_info(info, picks) data_rank = compute_rank(data_cov, rank=rank, info=info) noise_rank = compute_rank(noise_cov, rank=rank, info=info) for key in data_rank: if (key not in noise_rank or data_rank[key] != noise_rank[key]) and \ not allow_mismatch: raise ValueError('%s data rank (%s) did not match the noise ' 'rank (%s)' % (key, data_rank[key], noise_rank.get(key, None))) del noise_rank rank = data_rank logger.info('Making LCMV beamformer with rank %s' % (rank,)) del data_rank depth = _check_depth(depth, 'depth_sparse') if inversion == 'single': depth['combine_xyz'] = False is_free_ori, info, proj, vertno, G, whitener, nn, orient_std = \ _prepare_beamformer_input( info, forward, label, pick_ori, noise_cov=noise_cov, rank=rank, pca=False, **depth) ch_names = list(info['ch_names']) data_cov = pick_channels_cov(data_cov, include=ch_names) Cm = data_cov._get_square() if 'estimator' in data_cov: del data_cov['estimator'] rank_int = sum(rank.values()) del rank # compute spatial filter n_orient = 3 if is_free_ori else 1 W, max_power_ori = _compute_beamformer( G, Cm, reg, n_orient, weight_norm, pick_ori, reduce_rank, rank_int, inversion=inversion, nn=nn, orient_std=orient_std, whitener=whitener) # get src type to store with filters for _make_stc src_type = _get_src_type(forward['src'], vertno) # get subject to store with filters subject_from = _subject_from_forward(forward) # Is the computed beamformer a scalar or vector beamformer? is_free_ori = is_free_ori if pick_ori in [None, 'vector'] else False is_ssp = bool(info['projs']) filters = Beamformer( kind='LCMV', weights=W, data_cov=data_cov, noise_cov=noise_cov, whitener=whitener, weight_norm=weight_norm, pick_ori=pick_ori, ch_names=ch_names, proj=proj, is_ssp=is_ssp, vertices=vertno, is_free_ori=is_free_ori, n_sources=forward['nsource'], src_type=src_type, source_nn=forward['source_nn'].copy(), subject=subject_from, rank=rank_int, max_power_ori=max_power_ori, inversion=inversion) return filters def _apply_lcmv(data, filters, info, tmin, max_ori_out): """Apply LCMV spatial filter to data for source reconstruction.""" if max_ori_out != 'signed': raise ValueError('max_ori_out must be "signed", got %s' % (max_ori_out,)) if isinstance(data, np.ndarray) and data.ndim == 2: data = [data] return_single = True else: return_single = False W = filters['weights'] for i, M in enumerate(data): if len(M) != len(filters['ch_names']): raise ValueError('data and picks must have the same length') if not return_single: logger.info("Processing epoch : %d" % (i + 1)) M = _proj_whiten_data(M, info['projs'], filters) # project to source space using beamformer weights vector = False if filters['is_free_ori']: sol = np.dot(W, M) if filters['pick_ori'] == 'vector': vector = True else: logger.info('combining the current components...') sol = combine_xyz(sol) else: # Linear inverse: do computation here or delayed if (M.shape[0] < W.shape[0] and filters['pick_ori'] != 'max-power'): sol = (W, M) else: sol = np.dot(W, M) if filters['pick_ori'] == 'max-power' and max_ori_out == 'abs': sol = np.abs(sol) tstep = 1.0 / info['sfreq'] # compatibility with 0.16, add src_type as None if not present: filters, warn_text = _check_src_type(filters) yield _make_stc(sol, vertices=filters['vertices'], tmin=tmin, tstep=tstep, subject=filters['subject'], vector=vector, source_nn=filters['source_nn'], src_type=filters['src_type'], warn_text=warn_text) logger.info('[done]') @verbose def apply_lcmv(evoked, filters, max_ori_out='signed', verbose=None): """Apply Linearly Constrained Minimum Variance (LCMV) beamformer weights. Apply Linearly Constrained Minimum Variance (LCMV) beamformer weights on evoked data. Parameters ---------- evoked : Evoked Evoked data to invert. filters : instance of Beamformer LCMV spatial filter (beamformer weights). Filter weights returned from :func:`make_lcmv`. max_ori_out : 'signed' Specify in case of pick_ori='max-power'. %(verbose)s Returns ------- stc : SourceEstimate | VolSourceEstimate | VectorSourceEstimate Source time courses. See Also -------- make_lcmv, apply_lcmv_raw, apply_lcmv_epochs, apply_lcmv_cov Notes ----- .. versionadded:: 0.18 """ _check_reference(evoked) info = evoked.info data = evoked.data tmin = evoked.times[0] sel = _check_channels_spatial_filter(evoked.ch_names, filters) data = data[sel] stc = _apply_lcmv(data=data, filters=filters, info=info, tmin=tmin, max_ori_out=max_ori_out) return next(stc) @verbose def apply_lcmv_epochs(epochs, filters, max_ori_out='signed', return_generator=False, verbose=None): """Apply Linearly Constrained Minimum Variance (LCMV) beamformer weights. Apply Linearly Constrained Minimum Variance (LCMV) beamformer weights on single trial data. Parameters ---------- epochs : Epochs Single trial epochs. filters : instance of Beamformer LCMV spatial filter (beamformer weights) Filter weights returned from :func:`make_lcmv`. max_ori_out : 'signed' Specify in case of pick_ori='max-power'. return_generator : bool Return a generator object instead of a list. This allows iterating over the stcs without having to keep them all in memory. %(verbose)s Returns ------- stc: list | generator of (SourceEstimate | VolSourceEstimate) The source estimates for all epochs. See Also -------- make_lcmv, apply_lcmv_raw, apply_lcmv, apply_lcmv_cov """ _check_reference(epochs) info = epochs.info tmin = epochs.times[0] sel = _check_channels_spatial_filter(epochs.ch_names, filters) data = epochs.get_data()[:, sel, :] stcs = _apply_lcmv(data=data, filters=filters, info=info, tmin=tmin, max_ori_out=max_ori_out) if not return_generator: stcs = [s for s in stcs] return stcs @verbose def apply_lcmv_raw(raw, filters, start=None, stop=None, max_ori_out='signed', verbose=None): """Apply Linearly Constrained Minimum Variance (LCMV) beamformer weights. Apply Linearly Constrained Minimum Variance (LCMV) beamformer weights on raw data. Parameters ---------- raw : mne.io.Raw Raw data to invert. filters : instance of Beamformer LCMV spatial filter (beamformer weights). Filter weights returned from :func:`make_lcmv`. start : int Index of first time sample (index not time is seconds). stop : int Index of first time sample not to include (index not time is seconds). max_ori_out : 'signed' Specify in case of pick_ori='max-power'. %(verbose)s Returns ------- stc : SourceEstimate | VolSourceEstimate Source time courses. See Also -------- make_lcmv, apply_lcmv_epochs, apply_lcmv, apply_lcmv_cov """ _check_reference(raw) info = raw.info sel = _check_channels_spatial_filter(raw.ch_names, filters) data, times = raw[sel, start:stop] tmin = times[0] stc = _apply_lcmv(data=data, filters=filters, info=info, tmin=tmin, max_ori_out=max_ori_out) return next(stc) @verbose def apply_lcmv_cov(data_cov, filters, verbose=None): """Apply Linearly Constrained Minimum Variance (LCMV) beamformer weights. Apply Linearly Constrained Minimum Variance (LCMV) beamformer weights to a data covariance matrix to estimate source power. Parameters ---------- data_cov : instance of Covariance Data covariance matrix. filters : instance of Beamformer LCMV spatial filter (beamformer weights). Filter weights returned from :func:`make_lcmv`. %(verbose)s Returns ------- stc : SourceEstimate | VolSourceEstimate Source power. See Also -------- make_lcmv, apply_lcmv, apply_lcmv_epochs, apply_lcmv_raw """ sel = _check_channels_spatial_filter(data_cov.ch_names, filters) sel_names = [data_cov.ch_names[ii] for ii in sel] data_cov = pick_channels_cov(data_cov, sel_names) n_orient = filters['weights'].shape[0] // filters['n_sources'] # Need to project and whiten along both dimensions data = _proj_whiten_data(data_cov['data'].T, data_cov['projs'], filters) data = _proj_whiten_data(data.T, data_cov['projs'], filters) del data_cov source_power = _compute_power(data, filters['weights'], n_orient) # compatibility with 0.16, add src_type as None if not present: filters, warn_text = _check_src_type(filters) return(_make_stc(source_power, vertices=filters['vertices'], src_type=filters['src_type'], tmin=0., tstep=1., subject=filters['subject'], source_nn=filters['source_nn'], warn_text=warn_text))
# Authors: Eric Larson <larson.eric.d@gmail.com> # Alexandre Gramfort <alexandre.gramfort@inria.fr> # # License: BSD (3-clause) from functools import partial import os import numpy as np from scipy import sparse, linalg, stats from numpy.testing import (assert_equal, assert_array_equal, assert_array_almost_equal, assert_allclose) import pytest from mne import (SourceEstimate, VolSourceEstimate, MixedSourceEstimate, SourceSpaces) from mne.parallel import _force_serial from mne.stats import ttest_ind_no_p, combine_adjacency from mne.stats.cluster_level import (permutation_cluster_test, f_oneway, permutation_cluster_1samp_test, spatio_temporal_cluster_test, spatio_temporal_cluster_1samp_test, ttest_1samp_no_p, summarize_clusters_stc) from mne.utils import catch_logging, check_version, requires_sklearn n_space = 50 def _get_conditions(): noise_level = 20 n_time_1 = 20 n_time_2 = 13 normfactor = np.hanning(20).sum() rng = np.random.RandomState(42) condition1_1d = rng.randn(n_time_1, n_space) * noise_level for c in condition1_1d: c[:] = np.convolve(c, np.hanning(20), mode="same") / normfactor condition2_1d = rng.randn(n_time_2, n_space) * noise_level for c in condition2_1d: c[:] = np.convolve(c, np.hanning(20), mode="same") / normfactor pseudoekp = 10 * np.hanning(25)[None, :] condition1_1d[:, 25:] += pseudoekp condition2_1d[:, 25:] -= pseudoekp condition1_2d = condition1_1d[:, :, np.newaxis] condition2_2d = condition2_1d[:, :, np.newaxis] return condition1_1d, condition2_1d, condition1_2d, condition2_2d def test_thresholds(numba_conditional): """Test automatic threshold calculations.""" # within subjects rng = np.random.RandomState(0) X = rng.randn(10, 1, 1) + 0.08 want_thresh = -stats.t.ppf(0.025, len(X) - 1) assert 0.03 < stats.ttest_1samp(X[:, 0, 0], 0)[1] < 0.05 my_fun = partial(ttest_1samp_no_p) with catch_logging() as log: with pytest.warns(RuntimeWarning, match='threshold is only valid'): out = permutation_cluster_1samp_test( X, stat_fun=my_fun, seed=0, verbose=True, out_type='mask') log = log.getvalue() assert str(want_thresh)[:6] in log assert len(out[1]) == 1 # 1 cluster assert_allclose(out[2], 0.033203, atol=1e-6) # between subjects Y = rng.randn(10, 1, 1) Z = rng.randn(10, 1, 1) - 0.7 X = [X, Y, Z] want_thresh = stats.f.ppf(1. - 0.05, 2, sum(len(a) for a in X) - len(X)) p = stats.f_oneway(*X)[1] assert 0.03 < p < 0.05 my_fun = partial(f_oneway) # just to make the check fail with catch_logging() as log: with pytest.warns(RuntimeWarning, match='threshold is only valid'): out = permutation_cluster_test(X, tail=1, stat_fun=my_fun, seed=0, verbose=True, out_type='mask') log = log.getvalue() assert str(want_thresh)[:6] in log assert len(out[1]) == 1 # 1 cluster assert_allclose(out[2], 0.041992, atol=1e-6) with pytest.warns(RuntimeWarning, match='Ignoring argument "tail"'): permutation_cluster_test(X, tail=0, out_type='mask') # nan handling in TFCE X = np.repeat(X[0], 2, axis=1) X[:, 1] = 0 with pytest.warns(RuntimeWarning, match='invalid value'): # NumPy out = permutation_cluster_1samp_test( X, seed=0, threshold=dict(start=0, step=0.1), out_type='mask') assert (out[2] < 0.05).any() assert not (out[2] < 0.05).all() X[:, 0] = 0 with pytest.raises(RuntimeError, match='finite'): with np.errstate(invalid='ignore'): permutation_cluster_1samp_test( X, seed=0, threshold=dict(start=0, step=0.1), buffer_size=None, out_type='mask') def test_cache_dir(tmpdir, numba_conditional): """Test use of cache dir.""" tempdir = str(tmpdir) orig_dir = os.getenv('MNE_CACHE_DIR', None) orig_size = os.getenv('MNE_MEMMAP_MIN_SIZE', None) rng = np.random.RandomState(0) X = rng.randn(9, 2, 10) try: os.environ['MNE_MEMMAP_MIN_SIZE'] = '1K' os.environ['MNE_CACHE_DIR'] = tempdir # Fix error for #1507: in-place when memmapping with catch_logging() as log_file: permutation_cluster_1samp_test( X, buffer_size=None, n_jobs=2, n_permutations=1, seed=0, stat_fun=ttest_1samp_no_p, verbose=False, out_type='mask') assert 'independently' not in log_file.getvalue() # ensure that non-independence yields warning stat_fun = partial(ttest_1samp_no_p, sigma=1e-3) if check_version('numpy', '1.17'): random_state = np.random.default_rng(0) else: random_state = 0 with pytest.warns(RuntimeWarning, match='independently'): permutation_cluster_1samp_test( X, buffer_size=10, n_jobs=2, n_permutations=1, seed=random_state, stat_fun=stat_fun, verbose=False, out_type='mask') finally: if orig_dir is not None: os.environ['MNE_CACHE_DIR'] = orig_dir else: del os.environ['MNE_CACHE_DIR'] if orig_size is not None: os.environ['MNE_MEMMAP_MIN_SIZE'] = orig_size else: del os.environ['MNE_MEMMAP_MIN_SIZE'] def test_permutation_large_n_samples(numba_conditional): """Test that non-replacement works with large N.""" X = np.random.RandomState(0).randn(72, 1) + 1 for n_samples in (11, 72): tails = (0, 1) if n_samples <= 20 else (0,) for tail in tails: H0 = permutation_cluster_1samp_test( X[:n_samples], threshold=1e-4, tail=tail, out_type='mask')[-1] assert H0.shape == (1024,) assert len(np.unique(H0)) >= 1024 - (H0 == 0).sum() def test_permutation_step_down_p(numba_conditional): """Test cluster level permutations with step_down_p.""" rng = np.random.RandomState(0) # subjects, time points, spatial points X = rng.randn(9, 2, 10) # add some significant points X[:, 0:2, 0:2] += 2 # span two time points and two spatial points X[:, 1, 5:9] += 0.5 # span four time points with 4x smaller amplitude thresh = 2 # make sure it works when we use ALL points in step-down t, clusters, p, H0 = \ permutation_cluster_1samp_test(X, threshold=thresh, step_down_p=1.0, out_type='mask') # make sure using step-down will actually yield improvements sometimes t, clusters, p_old, H0 = \ permutation_cluster_1samp_test(X, threshold=thresh, step_down_p=0.0, out_type='mask') assert_equal(np.sum(p_old < 0.05), 1) # just spatial cluster p_min = np.min(p_old) assert_allclose(p_min, 0.003906, atol=1e-6) t, clusters, p_new, H0 = \ permutation_cluster_1samp_test(X, threshold=thresh, step_down_p=0.05, out_type='mask') assert_equal(np.sum(p_new < 0.05), 2) # time one rescued assert np.all(p_old >= p_new) p_next = p_new[(p_new > 0.004) & (p_new < 0.05)][0] assert_allclose(p_next, 0.015625, atol=1e-6) def test_cluster_permutation_test(numba_conditional): """Test cluster level permutations tests.""" condition1_1d, condition2_1d, condition1_2d, condition2_2d = \ _get_conditions() for condition1, condition2 in zip((condition1_1d, condition1_2d), (condition2_1d, condition2_2d)): T_obs, clusters, cluster_p_values, hist = permutation_cluster_test( [condition1, condition2], n_permutations=100, tail=1, seed=1, buffer_size=None, out_type='mask') p_min = np.min(cluster_p_values) assert_equal(np.sum(cluster_p_values < 0.05), 1) assert_allclose(p_min, 0.01, atol=1e-6) # test with 2 jobs and buffer_size enabled buffer_size = condition1.shape[1] // 10 T_obs, clusters, cluster_p_values_buff, hist =\ permutation_cluster_test([condition1, condition2], n_permutations=100, tail=1, seed=1, n_jobs=2, buffer_size=buffer_size, out_type='mask') assert_array_equal(cluster_p_values, cluster_p_values_buff) def stat_fun(X, Y): return stats.f_oneway(X, Y)[0] with pytest.warns(RuntimeWarning, match='is only valid'): permutation_cluster_test([condition1, condition2], n_permutations=1, stat_fun=stat_fun, out_type='mask') @pytest.mark.parametrize('stat_fun', [ ttest_1samp_no_p, partial(ttest_1samp_no_p, sigma=1e-1) ]) def test_cluster_permutation_t_test(numba_conditional, stat_fun): """Test cluster level permutations T-test.""" condition1_1d, condition2_1d, condition1_2d, condition2_2d = \ _get_conditions() # use a very large sigma to make sure Ts are not independent for condition1, p in ((condition1_1d, 0.01), (condition1_2d, 0.01)): # these are so significant we can get away with fewer perms T_obs, clusters, cluster_p_values, hist =\ permutation_cluster_1samp_test(condition1, n_permutations=100, tail=0, seed=1, out_type='mask', buffer_size=None) assert_equal(np.sum(cluster_p_values < 0.05), 1) p_min = np.min(cluster_p_values) assert_allclose(p_min, p, atol=1e-6) T_obs_pos, c_1, cluster_p_values_pos, _ =\ permutation_cluster_1samp_test(condition1, n_permutations=100, tail=1, threshold=1.67, seed=1, stat_fun=stat_fun, out_type='mask', buffer_size=None) T_obs_neg, _, cluster_p_values_neg, _ =\ permutation_cluster_1samp_test(-condition1, n_permutations=100, tail=-1, threshold=-1.67, seed=1, stat_fun=stat_fun, buffer_size=None, out_type='mask') assert_array_equal(T_obs_pos, -T_obs_neg) assert_array_equal(cluster_p_values_pos < 0.05, cluster_p_values_neg < 0.05) # test with 2 jobs and buffer_size enabled buffer_size = condition1.shape[1] // 10 with pytest.warns(None): # sometimes "independently" T_obs_neg_buff, _, cluster_p_values_neg_buff, _ = \ permutation_cluster_1samp_test( -condition1, n_permutations=100, tail=-1, out_type='mask', threshold=-1.67, seed=1, n_jobs=2, stat_fun=stat_fun, buffer_size=buffer_size) assert_array_equal(T_obs_neg, T_obs_neg_buff) assert_array_equal(cluster_p_values_neg, cluster_p_values_neg_buff) # Bad stat_fun with pytest.raises(TypeError, match='must be .* ndarray'): permutation_cluster_1samp_test( condition1, threshold=1, stat_fun=lambda x: None, out_type='mask') with pytest.raises(ValueError, match='not compatible'): permutation_cluster_1samp_test( condition1, threshold=1, stat_fun=lambda x: stat_fun(x)[:-1], out_type='mask') @requires_sklearn def test_cluster_permutation_with_adjacency(numba_conditional): """Test cluster level permutations with adjacency matrix.""" from sklearn.feature_extraction.image import grid_to_graph condition1_1d, condition2_1d, condition1_2d, condition2_2d = \ _get_conditions() n_pts = condition1_1d.shape[1] # we don't care about p-values in any of these, so do fewer permutations args = dict(seed=None, max_step=1, exclude=None, out_type='mask', step_down_p=0, t_power=1, threshold=1.67, check_disjoint=False, n_permutations=50) did_warn = False for X1d, X2d, func, spatio_temporal_func in \ [(condition1_1d, condition1_2d, permutation_cluster_1samp_test, spatio_temporal_cluster_1samp_test), ([condition1_1d, condition2_1d], [condition1_2d, condition2_2d], permutation_cluster_test, spatio_temporal_cluster_test)]: out = func(X1d, **args) adjacency = grid_to_graph(1, n_pts) out_adjacency = func(X1d, adjacency=adjacency, **args) assert_array_equal(out[0], out_adjacency[0]) for a, b in zip(out_adjacency[1], out[1]): assert_array_equal(out[0][a], out[0][b]) assert np.all(a[b]) # test spatio-temporal w/o time adjacency (repeat spatial pattern) adjacency_2 = sparse.coo_matrix( linalg.block_diag(adjacency.asfptype().todense(), adjacency.asfptype().todense())) # nesting here is time then space: adjacency_2a = combine_adjacency(np.eye(2), adjacency) assert_array_equal(adjacency_2.toarray().astype(bool), adjacency_2a.toarray().astype(bool)) if isinstance(X1d, list): X1d_2 = [np.concatenate((x, x), axis=1) for x in X1d] else: X1d_2 = np.concatenate((X1d, X1d), axis=1) out_adjacency_2 = func(X1d_2, adjacency=adjacency_2, **args) # make sure we were operating on the same values split = len(out[0]) assert_array_equal(out[0], out_adjacency_2[0][:split]) assert_array_equal(out[0], out_adjacency_2[0][split:]) # make sure we really got 2x the number of original clusters n_clust_orig = len(out[1]) assert len(out_adjacency_2[1]) == 2 * n_clust_orig # Make sure that we got the old ones back data_1 = {np.sum(out[0][b[:n_pts]]) for b in out[1]} data_2 = {np.sum(out_adjacency_2[0][a]) for a in out_adjacency_2[1][:]} assert len(data_1.intersection(data_2)) == len(data_1) # now use the other algorithm if isinstance(X1d, list): X1d_3 = [np.reshape(x, (-1, 2, n_space)) for x in X1d_2] else: X1d_3 = np.reshape(X1d_2, (-1, 2, n_space)) out_adjacency_3 = spatio_temporal_func( X1d_3, n_permutations=50, adjacency=adjacency, max_step=0, threshold=1.67, check_disjoint=True) # make sure we were operating on the same values split = len(out[0]) assert_array_equal(out[0], out_adjacency_3[0][0]) assert_array_equal(out[0], out_adjacency_3[0][1]) # make sure we really got 2x the number of original clusters assert len(out_adjacency_3[1]) == 2 * n_clust_orig # Make sure that we got the old ones back data_1 = {np.sum(out[0][b[:n_pts]]) for b in out[1]} data_2 = {np.sum(out_adjacency_3[0][a[0], a[1]]) for a in out_adjacency_3[1]} assert len(data_1.intersection(data_2)) == len(data_1) # test new versus old method out_adjacency_4 = spatio_temporal_func( X1d_3, n_permutations=50, adjacency=adjacency, max_step=2, threshold=1.67) out_adjacency_5 = spatio_temporal_func( X1d_3, n_permutations=50, adjacency=adjacency, max_step=1, threshold=1.67) # clusters could be in a different order sums_4 = [np.sum(out_adjacency_4[0][a]) for a in out_adjacency_4[1]] sums_5 = [np.sum(out_adjacency_4[0][a]) for a in out_adjacency_5[1]] sums_4 = np.sort(sums_4) sums_5 = np.sort(sums_5) assert_array_almost_equal(sums_4, sums_5) if not _force_serial: pytest.raises(ValueError, spatio_temporal_func, X1d_3, n_permutations=1, adjacency=adjacency, max_step=1, threshold=1.67, n_jobs=-1000) # not enough TFCE params with pytest.raises(KeyError, match='threshold, if dict, must have'): spatio_temporal_func( X1d_3, adjacency=adjacency, threshold=dict(me='hello')) # too extreme a start threshold with pytest.warns(None) as w: spatio_temporal_func(X1d_3, adjacency=adjacency, threshold=dict(start=10, step=1)) if not did_warn: assert len(w) == 1 did_warn = True with pytest.raises(ValueError, match='threshold.*<= 0 for tail == -1'): spatio_temporal_func( X1d_3, adjacency=adjacency, tail=-1, threshold=dict(start=1, step=-1)) with pytest.warns(RuntimeWarning, match='threshold.* is more extreme'): spatio_temporal_func( X1d_3, adjacency=adjacency, tail=1, threshold=dict(start=100, step=1)) bad_con = adjacency.todense() with pytest.raises(ValueError, match='must be a SciPy sparse matrix'): spatio_temporal_func( X1d_3, n_permutations=50, adjacency=bad_con, max_step=1, threshold=1.67) bad_con = adjacency.tocsr()[:-1, :-1].tocoo() with pytest.raises(ValueError, match='adjacency.*the correct size'): spatio_temporal_func( X1d_3, n_permutations=50, adjacency=bad_con, max_step=1, threshold=1.67) with pytest.raises(TypeError, match='must be a'): spatio_temporal_func( X1d_3, adjacency=adjacency, threshold=[]) with pytest.raises(ValueError, match='Invalid value for the \'tail\''): with pytest.warns(None): # sometimes ignoring tail spatio_temporal_func( X1d_3, adjacency=adjacency, tail=2) # make sure it actually found a significant point out_adjacency_6 = spatio_temporal_func( X1d_3, n_permutations=50, adjacency=adjacency, max_step=1, threshold=dict(start=1, step=1)) assert np.min(out_adjacency_6[2]) < 0.05 with pytest.raises(ValueError, match='not compatible'): with pytest.warns(RuntimeWarning, match='No clusters'): spatio_temporal_func( X1d_3, n_permutations=50, adjacency=adjacency, threshold=1e-3, stat_fun=lambda *x: f_oneway(*x)[:-1], buffer_size=None) @pytest.mark.parametrize('threshold', [ 0.1, pytest.param(dict(start=0., step=0.5), id='TFCE'), ]) @pytest.mark.parametrize('kind', ('1samp', 'ind')) def test_permutation_cluster_signs(threshold, kind): """Test cluster signs.""" # difference between two conditions for 3 subjects x 2 vertices x 2 times X = np.array([[[-10, 5], [-2, -7]], [[-4, 5], [-8, -0]], [[-6, 3], [-4, -2]]], float) want_signs = np.sign(np.mean(X, axis=0)) n_permutations = 1 if kind == '1samp': func = permutation_cluster_1samp_test stat_fun = ttest_1samp_no_p use_X = X else: assert kind == 'ind' func = permutation_cluster_test stat_fun = ttest_ind_no_p use_X = [X, np.random.RandomState(0).randn(*X.shape) * 0.1] tobs, clu, clu_pvalues, _ = func( use_X, n_permutations=n_permutations, threshold=threshold, tail=0, stat_fun=stat_fun, out_type='mask') clu_signs = np.zeros(X.shape[1:]) used = np.zeros(X.shape[1:]) assert len(clu) == len(clu_pvalues) for c, p in zip(clu, clu_pvalues): assert not used[c].any() assert len(np.unique(np.sign(tobs[c]))) == 1 clu_signs[c] = np.sign(tobs[c])[0] used[c] = True assert used.all() assert clu_signs.all() assert_array_equal(np.sign(tobs), want_signs) assert_array_equal(clu_signs, want_signs) @requires_sklearn def test_permutation_adjacency_equiv(numba_conditional): """Test cluster level permutations with and without adjacency.""" from sklearn.feature_extraction.image import grid_to_graph rng = np.random.RandomState(0) # subjects, time points, spatial points n_time = 2 n_space = 4 X = rng.randn(6, n_time, n_space) # add some significant points X[:, :, 0:2] += 10 # span two time points and two spatial points X[:, 1, 3] += 20 # span one time point max_steps = [1, 1, 1, 2, 1] # This will run full algorithm in two ways, then the ST-algorithm in 2 ways # All of these should give the same results adjs = [None, grid_to_graph(n_time, n_space), grid_to_graph(1, n_space), grid_to_graph(1, n_space), None] stat_map = None thresholds = [2, 2, 2, 2, dict(start=0.01, step=1.0)] sig_counts = [2, 2, 2, 2, 5] stat_fun = partial(ttest_1samp_no_p, sigma=1e-3) cs = None ps = None for thresh, count, max_step, adj in zip(thresholds, sig_counts, max_steps, adjs): t, clusters, p, H0 = \ permutation_cluster_1samp_test( X, threshold=thresh, adjacency=adj, n_jobs=2, max_step=max_step, stat_fun=stat_fun, seed=0, out_type='mask') # make sure our output datatype is correct assert isinstance(clusters[0], np.ndarray) assert clusters[0].dtype == bool assert_array_equal(clusters[0].shape, X.shape[1:]) # make sure all comparisons were done; for TFCE, no perm # should come up empty inds = np.where(p < 0.05)[0] assert_equal(len(inds), count) assert_allclose(p[inds], 0.03125, atol=1e-6) if isinstance(thresh, dict): assert_equal(len(clusters), n_time * n_space) assert np.all(H0 != 0) continue this_cs = [clusters[ii] for ii in inds] this_ps = p[inds] this_stat_map = np.zeros((n_time, n_space), dtype=bool) for ci, c in enumerate(this_cs): if isinstance(c, tuple): this_c = np.zeros((n_time, n_space), bool) for x, y in zip(c[0], c[1]): this_stat_map[x, y] = True this_c[x, y] = True this_cs[ci] = this_c c = this_c this_stat_map[c] = True if cs is None: ps = this_ps cs = this_cs if stat_map is None: stat_map = this_stat_map assert_array_equal(ps, this_ps) assert len(cs) == len(this_cs) for c1, c2 in zip(cs, this_cs): assert_array_equal(c1, c2) assert_array_equal(stat_map, this_stat_map) @requires_sklearn def test_spatio_temporal_cluster_adjacency(numba_conditional): """Test spatio-temporal cluster permutations.""" from sklearn.feature_extraction.image import grid_to_graph condition1_1d, condition2_1d, condition1_2d, condition2_2d = \ _get_conditions() rng = np.random.RandomState(0) noise1_2d = rng.randn(condition1_2d.shape[0], condition1_2d.shape[1], 10) data1_2d = np.transpose(np.dstack((condition1_2d, noise1_2d)), [0, 2, 1]) noise2_d2 = rng.randn(condition2_2d.shape[0], condition2_2d.shape[1], 10) data2_2d = np.transpose(np.dstack((condition2_2d, noise2_d2)), [0, 2, 1]) adj = grid_to_graph(data1_2d.shape[-1], 1) threshold = dict(start=4.0, step=2) T_obs, clusters, p_values_adj, hist = \ spatio_temporal_cluster_test([data1_2d, data2_2d], adjacency=adj, n_permutations=50, tail=1, seed=1, threshold=threshold, buffer_size=None) buffer_size = data1_2d.size // 10 T_obs, clusters, p_values_no_adj, hist = \ spatio_temporal_cluster_test([data1_2d, data2_2d], n_permutations=50, tail=1, seed=1, threshold=threshold, n_jobs=2, buffer_size=buffer_size) assert_equal(np.sum(p_values_adj < 0.05), np.sum(p_values_no_adj < 0.05)) # make sure results are the same without buffer_size T_obs, clusters, p_values2, hist2 = \ spatio_temporal_cluster_test([data1_2d, data2_2d], n_permutations=50, tail=1, seed=1, threshold=threshold, n_jobs=2, buffer_size=None) assert_array_equal(p_values_no_adj, p_values2) pytest.raises(ValueError, spatio_temporal_cluster_test, [data1_2d, data2_2d], tail=1, threshold=-2.) pytest.raises(ValueError, spatio_temporal_cluster_test, [data1_2d, data2_2d], tail=-1, threshold=2.) pytest.raises(ValueError, spatio_temporal_cluster_test, [data1_2d, data2_2d], tail=0, threshold=-1) def ttest_1samp(X): """Return T-values.""" return stats.ttest_1samp(X, 0)[0] @pytest.mark.parametrize('kind', ('surface', 'volume', 'mixed')) def test_summarize_clusters(kind): """Test cluster summary stcs.""" src_surf = SourceSpaces( [dict(vertno=np.arange(10242), type='surf') for _ in range(2)]) assert src_surf.kind == 'surface' src_vol = SourceSpaces( [dict(vertno=np.arange(10), type='vol')]) assert src_vol.kind == 'volume' if kind == 'surface': src = src_surf klass = SourceEstimate elif kind == 'volume': src = src_vol klass = VolSourceEstimate else: assert kind == 'mixed' src = src_surf + src_vol klass = MixedSourceEstimate n_vertices = sum(len(s['vertno']) for s in src) clu = (np.random.random([1, n_vertices]), [(np.array([0]), np.array([0, 2, 4]))], np.array([0.02, 0.1]), np.array([12, -14, 30])) kwargs = dict() if kind == 'volume': with pytest.raises(ValueError, match='did not match'): summarize_clusters_stc(clu) assert len(src) == 1 kwargs['vertices'] = [src[0]['vertno']] elif kind == 'mixed': kwargs['vertices'] = src stc_sum = summarize_clusters_stc(clu, **kwargs) assert isinstance(stc_sum, klass) assert stc_sum.data.shape[1] == 2 clu[2][0] = 0.3 with pytest.raises(RuntimeError, match='No significant'): summarize_clusters_stc(clu, **kwargs) def test_permutation_test_H0(numba_conditional): """Test that H0 is populated properly during testing.""" rng = np.random.RandomState(0) data = rng.rand(7, 10, 1) - 0.5 with pytest.warns(RuntimeWarning, match='No clusters found'): t, clust, p, h0 = spatio_temporal_cluster_1samp_test( data, threshold=100, n_permutations=1024, seed=rng) assert_equal(len(h0), 0) for n_permutations in (1024, 65, 64, 63): t, clust, p, h0 = spatio_temporal_cluster_1samp_test( data, threshold=0.1, n_permutations=n_permutations, seed=rng) assert_equal(len(h0), min(n_permutations, 64)) assert isinstance(clust[0], tuple) # sets of indices for tail, thresh in zip((-1, 0, 1), (-0.1, 0.1, 0.1)): t, clust, p, h0 = spatio_temporal_cluster_1samp_test( data, threshold=thresh, seed=rng, tail=tail, out_type='mask') assert isinstance(clust[0], np.ndarray) # bool mask # same as "128 if tail else 64" assert_equal(len(h0), 2 ** (7 - (tail == 0))) # exact test def test_tfce_thresholds(numba_conditional): """Test TFCE thresholds.""" rng = np.random.RandomState(0) data = rng.randn(7, 10, 1) - 0.5 # if tail==-1, step must also be negative with pytest.raises(ValueError, match='must be < 0 for tail == -1'): permutation_cluster_1samp_test( data, tail=-1, out_type='mask', threshold=dict(start=0, step=0.1)) # this works (smoke test) permutation_cluster_1samp_test(data, tail=-1, out_type='mask', threshold=dict(start=0, step=-0.1)) # thresholds must be monotonically increasing with pytest.raises(ValueError, match='must be monotonically increasing'): permutation_cluster_1samp_test( data, tail=1, out_type='mask', threshold=dict(start=1, step=-0.5)) # 1D gives slices, 2D+ gives boolean masks @pytest.mark.parametrize('shape', ((11,), (11, 3), (11, 1, 2))) @pytest.mark.parametrize('out_type', ('mask', 'indices')) @pytest.mark.parametrize('adjacency', (None, 'sparse')) def test_output_equiv(shape, out_type, adjacency): """Test equivalence of output types.""" rng = np.random.RandomState(0) n_subjects = 10 data = rng.randn(n_subjects, *shape) data -= data.mean(axis=0, keepdims=True) data[:, 2:4] += 2 data[:, 6:9] += 2 want_mask = np.zeros(shape, int) want_mask[2:4] = 1 want_mask[6:9] = 2 if adjacency is not None: assert adjacency == 'sparse' adjacency = combine_adjacency(*shape) clusters = permutation_cluster_1samp_test( X=data, n_permutations=1, adjacency=adjacency, out_type=out_type)[1] got_mask = np.zeros_like(want_mask) for n, clu in enumerate(clusters, 1): if out_type == 'mask': if len(shape) == 1 and adjacency is None: assert isinstance(clu, tuple) assert len(clu) == 1 assert isinstance(clu[0], slice) else: assert isinstance(clu, np.ndarray) assert clu.dtype == bool assert clu.shape == shape got_mask[clu] = n else: assert isinstance(clu, tuple) for c in clu: assert isinstance(c, np.ndarray) assert c.dtype.kind == 'i' assert out_type == 'indices' got_mask[np.ix_(*clu)] = n assert_array_equal(got_mask, want_mask)
kambysese/mne-python
mne/stats/tests/test_cluster_level.py
mne/beamformer/_lcmv.py
from OpenGL.GL import * from .GLMeshItem import GLMeshItem from .. MeshData import MeshData from ...Qt import QtGui import numpy as np __all__ = ['GLSurfacePlotItem'] class GLSurfacePlotItem(GLMeshItem): """ **Bases:** :class:`GLMeshItem <pyqtgraph.opengl.GLMeshItem>` Displays a surface plot on a regular x,y grid """ def __init__(self, x=None, y=None, z=None, colors=None, **kwds): """ The x, y, z, and colors arguments are passed to setData(). All other keyword arguments are passed to GLMeshItem.__init__(). """ self._x = None self._y = None self._z = None self._color = None self._vertexes = None self._meshdata = MeshData() GLMeshItem.__init__(self, meshdata=self._meshdata, **kwds) self.setData(x, y, z, colors) def setData(self, x=None, y=None, z=None, colors=None): """ Update the data in this surface plot. ============== ===================================================================== **Arguments:** x,y 1D arrays of values specifying the x,y positions of vertexes in the grid. If these are omitted, then the values will be assumed to be integers. z 2D array of height values for each grid vertex. colors (width, height, 4) array of vertex colors. ============== ===================================================================== All arguments are optional. Note that if vertex positions are updated, the normal vectors for each triangle must be recomputed. This is somewhat expensive if the surface was initialized with smooth=False and very expensive if smooth=True. For faster performance, initialize with computeNormals=False and use per-vertex colors or a normal-independent shader program. """ if x is not None: if self._x is None or len(x) != len(self._x): self._vertexes = None self._x = x if y is not None: if self._y is None or len(y) != len(self._y): self._vertexes = None self._y = y if z is not None: #if self._x is None: #self._x = np.arange(z.shape[0]) #self._vertexes = None #if self._y is None: #self._y = np.arange(z.shape[1]) #self._vertexes = None if self._x is not None and z.shape[0] != len(self._x): raise Exception('Z values must have shape (len(x), len(y))') if self._y is not None and z.shape[1] != len(self._y): raise Exception('Z values must have shape (len(x), len(y))') self._z = z if self._vertexes is not None and self._z.shape != self._vertexes.shape[:2]: self._vertexes = None if colors is not None: self._colors = colors self._meshdata.setVertexColors(colors) if self._z is None: return updateMesh = False newVertexes = False ## Generate vertex and face array if self._vertexes is None: newVertexes = True self._vertexes = np.empty((self._z.shape[0], self._z.shape[1], 3), dtype=float) self.generateFaces() self._meshdata.setFaces(self._faces) updateMesh = True ## Copy x, y, z data into vertex array if newVertexes or x is not None: if x is None: if self._x is None: x = np.arange(self._z.shape[0]) else: x = self._x self._vertexes[:, :, 0] = x.reshape(len(x), 1) updateMesh = True if newVertexes or y is not None: if y is None: if self._y is None: y = np.arange(self._z.shape[1]) else: y = self._y self._vertexes[:, :, 1] = y.reshape(1, len(y)) updateMesh = True if newVertexes or z is not None: self._vertexes[...,2] = self._z updateMesh = True ## Update MeshData if updateMesh: self._meshdata.setVertexes(self._vertexes.reshape(self._vertexes.shape[0]*self._vertexes.shape[1], 3)) self.meshDataChanged() def generateFaces(self): cols = self._z.shape[1]-1 rows = self._z.shape[0]-1 faces = np.empty((cols*rows*2, 3), dtype=np.uint) rowtemplate1 = np.arange(cols).reshape(cols, 1) + np.array([[0, 1, cols+1]]) rowtemplate2 = np.arange(cols).reshape(cols, 1) + np.array([[cols+1, 1, cols+2]]) for row in range(rows): start = row * cols * 2 faces[start:start+cols] = rowtemplate1 + row * (cols+1) faces[start+cols:start+(cols*2)] = rowtemplate2 + row * (cols+1) self._faces = faces
#import PySide import pyqtgraph as pg import pytest app = pg.mkQApp() qtest = pg.Qt.QtTest.QTest QRectF = pg.QtCore.QRectF def assertMapping(vb, r1, r2): assert vb.mapFromView(r1.topLeft()) == r2.topLeft() assert vb.mapFromView(r1.bottomLeft()) == r2.bottomLeft() assert vb.mapFromView(r1.topRight()) == r2.topRight() assert vb.mapFromView(r1.bottomRight()) == r2.bottomRight() def init_viewbox(): """Helper function to init the ViewBox """ global win, vb win = pg.GraphicsWindow() win.ci.layout.setContentsMargins(0,0,0,0) win.resize(200, 200) win.show() vb = win.addViewBox() # set range before viewbox is shown vb.setRange(xRange=[0, 10], yRange=[0, 10], padding=0) # required to make mapFromView work properly. qtest.qWaitForWindowShown(win) g = pg.GridItem() vb.addItem(g) app.processEvents() def test_ViewBox(): init_viewbox() w = vb.geometry().width() h = vb.geometry().height() view1 = QRectF(0, 0, 10, 10) size1 = QRectF(0, h, w, -h) assertMapping(vb, view1, size1) # test resize win.resize(400, 400) app.processEvents() w = vb.geometry().width() h = vb.geometry().height() size1 = QRectF(0, h, w, -h) assertMapping(vb, view1, size1) # now lock aspect vb.setAspectLocked() # test wide resize win.resize(800, 400) app.processEvents() w = vb.geometry().width() h = vb.geometry().height() view1 = QRectF(-5, 0, 20, 10) size1 = QRectF(0, h, w, -h) assertMapping(vb, view1, size1) # test tall resize win.resize(400, 800) app.processEvents() w = vb.geometry().width() h = vb.geometry().height() view1 = QRectF(0, -5, 10, 20) size1 = QRectF(0, h, w, -h) assertMapping(vb, view1, size1) skipreason = "Skipping this test until someone has time to fix it." @pytest.mark.skipif(True, reason=skipreason) def test_limits_and_resize(): init_viewbox() # now lock aspect vb.setAspectLocked() # test limits + resize (aspect ratio constraint has priority over limits win.resize(400, 400) app.processEvents() vb.setLimits(xMin=0, xMax=10, yMin=0, yMax=10) win.resize(800, 400) app.processEvents() w = vb.geometry().width() h = vb.geometry().height() view1 = QRectF(-5, 0, 20, 10) size1 = QRectF(0, h, w, -h) assertMapping(vb, view1, size1)
ng110/pyqtgraph
pyqtgraph/graphicsItems/ViewBox/tests/test_ViewBox.py
pyqtgraph/opengl/items/GLSurfacePlotItem.py
# -*- coding: utf-8 -*- from .Flowchart import * from .library import getNodeType, registerNodeType, getNodeTree
#import PySide import pyqtgraph as pg import pytest app = pg.mkQApp() qtest = pg.Qt.QtTest.QTest QRectF = pg.QtCore.QRectF def assertMapping(vb, r1, r2): assert vb.mapFromView(r1.topLeft()) == r2.topLeft() assert vb.mapFromView(r1.bottomLeft()) == r2.bottomLeft() assert vb.mapFromView(r1.topRight()) == r2.topRight() assert vb.mapFromView(r1.bottomRight()) == r2.bottomRight() def init_viewbox(): """Helper function to init the ViewBox """ global win, vb win = pg.GraphicsWindow() win.ci.layout.setContentsMargins(0,0,0,0) win.resize(200, 200) win.show() vb = win.addViewBox() # set range before viewbox is shown vb.setRange(xRange=[0, 10], yRange=[0, 10], padding=0) # required to make mapFromView work properly. qtest.qWaitForWindowShown(win) g = pg.GridItem() vb.addItem(g) app.processEvents() def test_ViewBox(): init_viewbox() w = vb.geometry().width() h = vb.geometry().height() view1 = QRectF(0, 0, 10, 10) size1 = QRectF(0, h, w, -h) assertMapping(vb, view1, size1) # test resize win.resize(400, 400) app.processEvents() w = vb.geometry().width() h = vb.geometry().height() size1 = QRectF(0, h, w, -h) assertMapping(vb, view1, size1) # now lock aspect vb.setAspectLocked() # test wide resize win.resize(800, 400) app.processEvents() w = vb.geometry().width() h = vb.geometry().height() view1 = QRectF(-5, 0, 20, 10) size1 = QRectF(0, h, w, -h) assertMapping(vb, view1, size1) # test tall resize win.resize(400, 800) app.processEvents() w = vb.geometry().width() h = vb.geometry().height() view1 = QRectF(0, -5, 10, 20) size1 = QRectF(0, h, w, -h) assertMapping(vb, view1, size1) skipreason = "Skipping this test until someone has time to fix it." @pytest.mark.skipif(True, reason=skipreason) def test_limits_and_resize(): init_viewbox() # now lock aspect vb.setAspectLocked() # test limits + resize (aspect ratio constraint has priority over limits win.resize(400, 400) app.processEvents() vb.setLimits(xMin=0, xMax=10, yMin=0, yMax=10) win.resize(800, 400) app.processEvents() w = vb.geometry().width() h = vb.geometry().height() view1 = QRectF(-5, 0, 20, 10) size1 = QRectF(0, h, w, -h) assertMapping(vb, view1, size1)
ng110/pyqtgraph
pyqtgraph/graphicsItems/ViewBox/tests/test_ViewBox.py
pyqtgraph/flowchart/__init__.py
# -*- coding: utf-8 -*- """ ROI.py - Interactive graphics items for GraphicsView (ROI widgets) Copyright 2010 Luke Campagnola Distributed under MIT/X11 license. See license.txt for more infomation. Implements a series of graphics items which display movable/scalable/rotatable shapes for use as region-of-interest markers. ROI class automatically handles extraction of array data from ImageItems. The ROI class is meant to serve as the base for more specific types; see several examples of how to build an ROI at the bottom of the file. """ from ..Qt import QtCore, QtGui import numpy as np #from numpy.linalg import norm from ..Point import * from ..SRTTransform import SRTTransform from math import cos, sin from .. import functions as fn from .GraphicsObject import GraphicsObject from .UIGraphicsItem import UIGraphicsItem __all__ = [ 'ROI', 'TestROI', 'RectROI', 'EllipseROI', 'CircleROI', 'PolygonROI', 'LineROI', 'MultiLineROI', 'MultiRectROI', 'LineSegmentROI', 'PolyLineROI', 'SpiralROI', 'CrosshairROI', ] def rectStr(r): return "[%f, %f] + [%f, %f]" % (r.x(), r.y(), r.width(), r.height()) class ROI(GraphicsObject): """ Generic region-of-interest widget. Can be used for implementing many types of selection box with rotate/translate/scale handles. ROIs can be customized to have a variety of shapes (by subclassing or using any of the built-in subclasses) and any combination of draggable handles that allow the user to manipulate the ROI. ================ =========================================================== **Arguments** pos (length-2 sequence) Indicates the position of the ROI's origin. For most ROIs, this is the lower-left corner of its bounding rectangle. size (length-2 sequence) Indicates the width and height of the ROI. angle (float) The rotation of the ROI in degrees. Default is 0. invertible (bool) If True, the user may resize the ROI to have negative width or height (assuming the ROI has scale handles). Default is False. maxBounds (QRect, QRectF, or None) Specifies boundaries that the ROI cannot be dragged outside of by the user. Default is None. snapSize (float) The spacing of snap positions used when *scaleSnap* or *translateSnap* are enabled. Default is 1.0. scaleSnap (bool) If True, the width and height of the ROI are forced to be integer multiples of *snapSize* when being resized by the user. Default is False. translateSnap (bool) If True, the x and y positions of the ROI are forced to be integer multiples of *snapSize* when being resized by the user. Default is False. rotateSnap (bool) If True, the ROI angle is forced to a multiple of 15 degrees when rotated by the user. Default is False. parent (QGraphicsItem) The graphics item parent of this ROI. It is generally not necessary to specify the parent. pen (QPen or argument to pg.mkPen) The pen to use when drawing the shape of the ROI. movable (bool) If True, the ROI can be moved by dragging anywhere inside the ROI. Default is True. removable (bool) If True, the ROI will be given a context menu with an option to remove the ROI. The ROI emits sigRemoveRequested when this menu action is selected. Default is False. ================ =========================================================== ======================= ==================================================== **Signals** sigRegionChangeFinished Emitted when the user stops dragging the ROI (or one of its handles) or if the ROI is changed programatically. sigRegionChangeStarted Emitted when the user starts dragging the ROI (or one of its handles). sigRegionChanged Emitted any time the position of the ROI changes, including while it is being dragged by the user. sigHoverEvent Emitted when the mouse hovers over the ROI. sigClicked Emitted when the user clicks on the ROI. Note that clicking is disabled by default to prevent stealing clicks from objects behind the ROI. To enable clicking, call roi.setAcceptedMouseButtons(QtCore.Qt.LeftButton). See QtGui.QGraphicsItem documentation for more details. sigRemoveRequested Emitted when the user selects 'remove' from the ROI's context menu (if available). ======================= ==================================================== """ sigRegionChangeFinished = QtCore.Signal(object) sigRegionChangeStarted = QtCore.Signal(object) sigRegionChanged = QtCore.Signal(object) sigHoverEvent = QtCore.Signal(object) sigClicked = QtCore.Signal(object, object) sigRemoveRequested = QtCore.Signal(object) def __init__(self, pos, size=Point(1, 1), angle=0.0, invertible=False, maxBounds=None, snapSize=1.0, scaleSnap=False, translateSnap=False, rotateSnap=False, parent=None, pen=None, movable=True, removable=False): #QObjectWorkaround.__init__(self) GraphicsObject.__init__(self, parent) self.setAcceptedMouseButtons(QtCore.Qt.NoButton) pos = Point(pos) size = Point(size) self.aspectLocked = False self.translatable = movable self.rotateAllowed = True self.removable = removable self.menu = None self.freeHandleMoved = False ## keep track of whether free handles have moved since last change signal was emitted. self.mouseHovering = False if pen is None: pen = (255, 255, 255) self.setPen(pen) self.handlePen = QtGui.QPen(QtGui.QColor(150, 255, 255)) self.handles = [] self.state = {'pos': Point(0,0), 'size': Point(1,1), 'angle': 0} ## angle is in degrees for ease of Qt integration self.lastState = None self.setPos(pos) self.setAngle(angle) self.setSize(size) self.setZValue(10) self.isMoving = False self.handleSize = 5 self.invertible = invertible self.maxBounds = maxBounds self.snapSize = snapSize self.translateSnap = translateSnap self.rotateSnap = rotateSnap self.scaleSnap = scaleSnap #self.setFlag(self.ItemIsSelectable, True) def getState(self): return self.stateCopy() def stateCopy(self): sc = {} sc['pos'] = Point(self.state['pos']) sc['size'] = Point(self.state['size']) sc['angle'] = self.state['angle'] return sc def saveState(self): """Return the state of the widget in a format suitable for storing to disk. (Points are converted to tuple) Combined with setState(), this allows ROIs to be easily saved and restored.""" state = {} state['pos'] = tuple(self.state['pos']) state['size'] = tuple(self.state['size']) state['angle'] = self.state['angle'] return state def setState(self, state, update=True): """ Set the state of the ROI from a structure generated by saveState() or getState(). """ self.setPos(state['pos'], update=False) self.setSize(state['size'], update=False) self.setAngle(state['angle'], update=update) def setZValue(self, z): QtGui.QGraphicsItem.setZValue(self, z) for h in self.handles: h['item'].setZValue(z+1) def parentBounds(self): """ Return the bounding rectangle of this ROI in the coordinate system of its parent. """ return self.mapToParent(self.boundingRect()).boundingRect() def setPen(self, *args, **kwargs): """ Set the pen to use when drawing the ROI shape. For arguments, see :func:`mkPen <pyqtgraph.mkPen>`. """ self.pen = fn.mkPen(*args, **kwargs) self.currentPen = self.pen self.update() def size(self): """Return the size (w,h) of the ROI.""" return self.getState()['size'] def pos(self): """Return the position (x,y) of the ROI's origin. For most ROIs, this will be the lower-left corner.""" return self.getState()['pos'] def angle(self): """Return the angle of the ROI in degrees.""" return self.getState()['angle'] def setPos(self, pos, update=True, finish=True): """Set the position of the ROI (in the parent's coordinate system). By default, this will cause both sigRegionChanged and sigRegionChangeFinished to be emitted. If finish is False, then sigRegionChangeFinished will not be emitted. You can then use stateChangeFinished() to cause the signal to be emitted after a series of state changes. If update is False, the state change will be remembered but not processed and no signals will be emitted. You can then use stateChanged() to complete the state change. This allows multiple change functions to be called sequentially while minimizing processing overhead and repeated signals. Setting update=False also forces finish=False. """ pos = Point(pos) self.state['pos'] = pos QtGui.QGraphicsItem.setPos(self, pos) if update: self.stateChanged(finish=finish) def setSize(self, size, update=True, finish=True): """Set the size of the ROI. May be specified as a QPoint, Point, or list of two values. See setPos() for an explanation of the update and finish arguments. """ size = Point(size) self.prepareGeometryChange() self.state['size'] = size if update: self.stateChanged(finish=finish) def setAngle(self, angle, update=True, finish=True): """Set the angle of rotation (in degrees) for this ROI. See setPos() for an explanation of the update and finish arguments. """ self.state['angle'] = angle tr = QtGui.QTransform() #tr.rotate(-angle * 180 / np.pi) tr.rotate(angle) self.setTransform(tr) if update: self.stateChanged(finish=finish) def scale(self, s, center=[0,0], update=True, finish=True): """ Resize the ROI by scaling relative to *center*. See setPos() for an explanation of the *update* and *finish* arguments. """ c = self.mapToParent(Point(center) * self.state['size']) self.prepareGeometryChange() newSize = self.state['size'] * s c1 = self.mapToParent(Point(center) * newSize) newPos = self.state['pos'] + c - c1 self.setSize(newSize, update=False) self.setPos(newPos, update=update, finish=finish) def translate(self, *args, **kargs): """ Move the ROI to a new position. Accepts either (x, y, snap) or ([x,y], snap) as arguments If the ROI is bounded and the move would exceed boundaries, then the ROI is moved to the nearest acceptable position instead. *snap* can be: =============== ========================================================================== None (default) use self.translateSnap and self.snapSize to determine whether/how to snap False do not snap Point(w,h) snap to rectangular grid with spacing (w,h) True snap using self.snapSize (and ignoring self.translateSnap) =============== ========================================================================== Also accepts *update* and *finish* arguments (see setPos() for a description of these). """ if len(args) == 1: pt = args[0] else: pt = args newState = self.stateCopy() newState['pos'] = newState['pos'] + pt ## snap position #snap = kargs.get('snap', None) #if (snap is not False) and not (snap is None and self.translateSnap is False): snap = kargs.get('snap', None) if snap is None: snap = self.translateSnap if snap is not False: newState['pos'] = self.getSnapPosition(newState['pos'], snap=snap) #d = ev.scenePos() - self.mapToScene(self.pressPos) if self.maxBounds is not None: r = self.stateRect(newState) #r0 = self.sceneTransform().mapRect(self.boundingRect()) d = Point(0,0) if self.maxBounds.left() > r.left(): d[0] = self.maxBounds.left() - r.left() elif self.maxBounds.right() < r.right(): d[0] = self.maxBounds.right() - r.right() if self.maxBounds.top() > r.top(): d[1] = self.maxBounds.top() - r.top() elif self.maxBounds.bottom() < r.bottom(): d[1] = self.maxBounds.bottom() - r.bottom() newState['pos'] += d #self.state['pos'] = newState['pos'] update = kargs.get('update', True) finish = kargs.get('finish', True) self.setPos(newState['pos'], update=update, finish=finish) #if 'update' not in kargs or kargs['update'] is True: #self.stateChanged() def rotate(self, angle, update=True, finish=True): """ Rotate the ROI by *angle* degrees. Also accepts *update* and *finish* arguments (see setPos() for a description of these). """ self.setAngle(self.angle()+angle, update=update, finish=finish) def handleMoveStarted(self): self.preMoveState = self.getState() def addTranslateHandle(self, pos, axes=None, item=None, name=None, index=None): """ Add a new translation handle to the ROI. Dragging the handle will move the entire ROI without changing its angle or shape. Note that, by default, ROIs may be moved by dragging anywhere inside the ROI. However, for larger ROIs it may be desirable to disable this and instead provide one or more translation handles. =================== ==================================================== **Arguments** pos (length-2 sequence) The position of the handle relative to the shape of the ROI. A value of (0,0) indicates the origin, whereas (1, 1) indicates the upper-right corner, regardless of the ROI's size. item The Handle instance to add. If None, a new handle will be created. name The name of this handle (optional). Handles are identified by name when calling getLocalHandlePositions and getSceneHandlePositions. =================== ==================================================== """ pos = Point(pos) return self.addHandle({'name': name, 'type': 't', 'pos': pos, 'item': item}, index=index) def addFreeHandle(self, pos=None, axes=None, item=None, name=None, index=None): """ Add a new free handle to the ROI. Dragging free handles has no effect on the position or shape of the ROI. =================== ==================================================== **Arguments** pos (length-2 sequence) The position of the handle relative to the shape of the ROI. A value of (0,0) indicates the origin, whereas (1, 1) indicates the upper-right corner, regardless of the ROI's size. item The Handle instance to add. If None, a new handle will be created. name The name of this handle (optional). Handles are identified by name when calling getLocalHandlePositions and getSceneHandlePositions. =================== ==================================================== """ if pos is not None: pos = Point(pos) return self.addHandle({'name': name, 'type': 'f', 'pos': pos, 'item': item}, index=index) def addScaleHandle(self, pos, center, axes=None, item=None, name=None, lockAspect=False, index=None): """ Add a new scale handle to the ROI. Dragging a scale handle allows the user to change the height and/or width of the ROI. =================== ==================================================== **Arguments** pos (length-2 sequence) The position of the handle relative to the shape of the ROI. A value of (0,0) indicates the origin, whereas (1, 1) indicates the upper-right corner, regardless of the ROI's size. center (length-2 sequence) The center point around which scaling takes place. If the center point has the same x or y value as the handle position, then scaling will be disabled for that axis. item The Handle instance to add. If None, a new handle will be created. name The name of this handle (optional). Handles are identified by name when calling getLocalHandlePositions and getSceneHandlePositions. =================== ==================================================== """ pos = Point(pos) center = Point(center) info = {'name': name, 'type': 's', 'center': center, 'pos': pos, 'item': item, 'lockAspect': lockAspect} if pos.x() == center.x(): info['xoff'] = True if pos.y() == center.y(): info['yoff'] = True return self.addHandle(info, index=index) def addRotateHandle(self, pos, center, item=None, name=None, index=None): """ Add a new rotation handle to the ROI. Dragging a rotation handle allows the user to change the angle of the ROI. =================== ==================================================== **Arguments** pos (length-2 sequence) The position of the handle relative to the shape of the ROI. A value of (0,0) indicates the origin, whereas (1, 1) indicates the upper-right corner, regardless of the ROI's size. center (length-2 sequence) The center point around which rotation takes place. item The Handle instance to add. If None, a new handle will be created. name The name of this handle (optional). Handles are identified by name when calling getLocalHandlePositions and getSceneHandlePositions. =================== ==================================================== """ pos = Point(pos) center = Point(center) return self.addHandle({'name': name, 'type': 'r', 'center': center, 'pos': pos, 'item': item}, index=index) def addScaleRotateHandle(self, pos, center, item=None, name=None, index=None): """ Add a new scale+rotation handle to the ROI. When dragging a handle of this type, the user can simultaneously rotate the ROI around an arbitrary center point as well as scale the ROI by dragging the handle toward or away from the center point. =================== ==================================================== **Arguments** pos (length-2 sequence) The position of the handle relative to the shape of the ROI. A value of (0,0) indicates the origin, whereas (1, 1) indicates the upper-right corner, regardless of the ROI's size. center (length-2 sequence) The center point around which scaling and rotation take place. item The Handle instance to add. If None, a new handle will be created. name The name of this handle (optional). Handles are identified by name when calling getLocalHandlePositions and getSceneHandlePositions. =================== ==================================================== """ pos = Point(pos) center = Point(center) if pos[0] != center[0] and pos[1] != center[1]: raise Exception("Scale/rotate handles must have either the same x or y coordinate as their center point.") return self.addHandle({'name': name, 'type': 'sr', 'center': center, 'pos': pos, 'item': item}, index=index) def addRotateFreeHandle(self, pos, center, axes=None, item=None, name=None, index=None): """ Add a new rotation+free handle to the ROI. When dragging a handle of this type, the user can rotate the ROI around an arbitrary center point, while moving toward or away from the center point has no effect on the shape of the ROI. =================== ==================================================== **Arguments** pos (length-2 sequence) The position of the handle relative to the shape of the ROI. A value of (0,0) indicates the origin, whereas (1, 1) indicates the upper-right corner, regardless of the ROI's size. center (length-2 sequence) The center point around which rotation takes place. item The Handle instance to add. If None, a new handle will be created. name The name of this handle (optional). Handles are identified by name when calling getLocalHandlePositions and getSceneHandlePositions. =================== ==================================================== """ pos = Point(pos) center = Point(center) return self.addHandle({'name': name, 'type': 'rf', 'center': center, 'pos': pos, 'item': item}, index=index) def addHandle(self, info, index=None): ## If a Handle was not supplied, create it now if 'item' not in info or info['item'] is None: h = Handle(self.handleSize, typ=info['type'], pen=self.handlePen, parent=self) h.setPos(info['pos'] * self.state['size']) info['item'] = h else: h = info['item'] if info['pos'] is None: info['pos'] = h.pos() ## connect the handle to this ROI #iid = len(self.handles) h.connectROI(self) if index is None: self.handles.append(info) else: self.handles.insert(index, info) h.setZValue(self.zValue()+1) self.stateChanged() return h def indexOfHandle(self, handle): """ Return the index of *handle* in the list of this ROI's handles. """ if isinstance(handle, Handle): index = [i for i, info in enumerate(self.handles) if info['item'] is handle] if len(index) == 0: raise Exception("Cannot remove handle; it is not attached to this ROI") return index[0] else: return handle def removeHandle(self, handle): """Remove a handle from this ROI. Argument may be either a Handle instance or the integer index of the handle.""" index = self.indexOfHandle(handle) handle = self.handles[index]['item'] self.handles.pop(index) handle.disconnectROI(self) if len(handle.rois) == 0: self.scene().removeItem(handle) self.stateChanged() def replaceHandle(self, oldHandle, newHandle): """Replace one handle in the ROI for another. This is useful when connecting multiple ROIs together. *oldHandle* may be a Handle instance or the index of a handle to be replaced.""" index = self.indexOfHandle(oldHandle) info = self.handles[index] self.removeHandle(index) info['item'] = newHandle info['pos'] = newHandle.pos() self.addHandle(info, index=index) def checkRemoveHandle(self, handle): ## This is used when displaying a Handle's context menu to determine ## whether removing is allowed. ## Subclasses may wish to override this to disable the menu entry. ## Note: by default, handles are not user-removable even if this method returns True. return True def getLocalHandlePositions(self, index=None): """Returns the position of handles in the ROI's coordinate system. The format returned is a list of (name, pos) tuples. """ if index == None: positions = [] for h in self.handles: positions.append((h['name'], h['pos'])) return positions else: return (self.handles[index]['name'], self.handles[index]['pos']) def getSceneHandlePositions(self, index=None): """Returns the position of handles in the scene coordinate system. The format returned is a list of (name, pos) tuples. """ if index == None: positions = [] for h in self.handles: positions.append((h['name'], h['item'].scenePos())) return positions else: return (self.handles[index]['name'], self.handles[index]['item'].scenePos()) def getHandles(self): """ Return a list of this ROI's Handles. """ return [h['item'] for h in self.handles] def mapSceneToParent(self, pt): return self.mapToParent(self.mapFromScene(pt)) def setSelected(self, s): QtGui.QGraphicsItem.setSelected(self, s) #print "select", self, s if s: for h in self.handles: h['item'].show() else: for h in self.handles: h['item'].hide() def hoverEvent(self, ev): hover = False if not ev.isExit(): if self.translatable and ev.acceptDrags(QtCore.Qt.LeftButton): hover=True for btn in [QtCore.Qt.LeftButton, QtCore.Qt.RightButton, QtCore.Qt.MidButton]: if int(self.acceptedMouseButtons() & btn) > 0 and ev.acceptClicks(btn): hover=True if self.contextMenuEnabled(): ev.acceptClicks(QtCore.Qt.RightButton) if hover: self.setMouseHover(True) self.sigHoverEvent.emit(self) ev.acceptClicks(QtCore.Qt.LeftButton) ## If the ROI is hilighted, we should accept all clicks to avoid confusion. ev.acceptClicks(QtCore.Qt.RightButton) ev.acceptClicks(QtCore.Qt.MidButton) else: self.setMouseHover(False) def setMouseHover(self, hover): ## Inform the ROI that the mouse is(not) hovering over it if self.mouseHovering == hover: return self.mouseHovering = hover if hover: self.currentPen = fn.mkPen(255, 255, 0) else: self.currentPen = self.pen self.update() def contextMenuEnabled(self): return self.removable def raiseContextMenu(self, ev): if not self.contextMenuEnabled(): return menu = self.getMenu() menu = self.scene().addParentContextMenus(self, menu, ev) pos = ev.screenPos() menu.popup(QtCore.QPoint(pos.x(), pos.y())) def getMenu(self): if self.menu is None: self.menu = QtGui.QMenu() self.menu.setTitle("ROI") remAct = QtGui.QAction("Remove ROI", self.menu) remAct.triggered.connect(self.removeClicked) self.menu.addAction(remAct) self.menu.remAct = remAct return self.menu def removeClicked(self): ## Send remove event only after we have exited the menu event handler QtCore.QTimer.singleShot(0, lambda: self.sigRemoveRequested.emit(self)) def mouseDragEvent(self, ev): if ev.isStart(): #p = ev.pos() #if not self.isMoving and not self.shape().contains(p): #ev.ignore() #return if ev.button() == QtCore.Qt.LeftButton: self.setSelected(True) if self.translatable: self.isMoving = True self.preMoveState = self.getState() self.cursorOffset = self.pos() - self.mapToParent(ev.buttonDownPos()) self.sigRegionChangeStarted.emit(self) ev.accept() else: ev.ignore() elif ev.isFinish(): if self.translatable: if self.isMoving: self.stateChangeFinished() self.isMoving = False return if self.translatable and self.isMoving and ev.buttons() == QtCore.Qt.LeftButton: snap = True if (ev.modifiers() & QtCore.Qt.ControlModifier) else None newPos = self.mapToParent(ev.pos()) + self.cursorOffset self.translate(newPos - self.pos(), snap=snap, finish=False) def mouseClickEvent(self, ev): if ev.button() == QtCore.Qt.RightButton and self.isMoving: ev.accept() self.cancelMove() if ev.button() == QtCore.Qt.RightButton and self.contextMenuEnabled(): self.raiseContextMenu(ev) ev.accept() elif int(ev.button() & self.acceptedMouseButtons()) > 0: ev.accept() self.sigClicked.emit(self, ev) else: ev.ignore() def cancelMove(self): self.isMoving = False self.setState(self.preMoveState) def checkPointMove(self, handle, pos, modifiers): """When handles move, they must ask the ROI if the move is acceptable. By default, this always returns True. Subclasses may wish override. """ return True def movePoint(self, handle, pos, modifiers=QtCore.Qt.KeyboardModifier(), finish=True, coords='parent'): ## called by Handles when they are moved. ## pos is the new position of the handle in scene coords, as requested by the handle. newState = self.stateCopy() index = self.indexOfHandle(handle) h = self.handles[index] p0 = self.mapToParent(h['pos'] * self.state['size']) p1 = Point(pos) if coords == 'parent': pass elif coords == 'scene': p1 = self.mapSceneToParent(p1) else: raise Exception("New point location must be given in either 'parent' or 'scene' coordinates.") ## transform p0 and p1 into parent's coordinates (same as scene coords if there is no parent). I forget why. #p0 = self.mapSceneToParent(p0) #p1 = self.mapSceneToParent(p1) ## Handles with a 'center' need to know their local position relative to the center point (lp0, lp1) if 'center' in h: c = h['center'] cs = c * self.state['size'] lp0 = self.mapFromParent(p0) - cs lp1 = self.mapFromParent(p1) - cs if h['type'] == 't': snap = True if (modifiers & QtCore.Qt.ControlModifier) else None #if self.translateSnap or (): #snap = Point(self.snapSize, self.snapSize) self.translate(p1-p0, snap=snap, update=False) elif h['type'] == 'f': newPos = self.mapFromParent(p1) h['item'].setPos(newPos) h['pos'] = newPos self.freeHandleMoved = True #self.sigRegionChanged.emit(self) ## should be taken care of by call to stateChanged() elif h['type'] == 's': ## If a handle and its center have the same x or y value, we can't scale across that axis. if h['center'][0] == h['pos'][0]: lp1[0] = 0 if h['center'][1] == h['pos'][1]: lp1[1] = 0 ## snap if self.scaleSnap or (modifiers & QtCore.Qt.ControlModifier): lp1[0] = round(lp1[0] / self.snapSize) * self.snapSize lp1[1] = round(lp1[1] / self.snapSize) * self.snapSize ## preserve aspect ratio (this can override snapping) if h['lockAspect'] or (modifiers & QtCore.Qt.AltModifier): #arv = Point(self.preMoveState['size']) - lp1 = lp1.proj(lp0) ## determine scale factors and new size of ROI hs = h['pos'] - c if hs[0] == 0: hs[0] = 1 if hs[1] == 0: hs[1] = 1 newSize = lp1 / hs ## Perform some corrections and limit checks if newSize[0] == 0: newSize[0] = newState['size'][0] if newSize[1] == 0: newSize[1] = newState['size'][1] if not self.invertible: if newSize[0] < 0: newSize[0] = newState['size'][0] if newSize[1] < 0: newSize[1] = newState['size'][1] if self.aspectLocked: newSize[0] = newSize[1] ## Move ROI so the center point occupies the same scene location after the scale s0 = c * self.state['size'] s1 = c * newSize cc = self.mapToParent(s0 - s1) - self.mapToParent(Point(0, 0)) ## update state, do more boundary checks newState['size'] = newSize newState['pos'] = newState['pos'] + cc if self.maxBounds is not None: r = self.stateRect(newState) if not self.maxBounds.contains(r): return self.setPos(newState['pos'], update=False) self.setSize(newState['size'], update=False) elif h['type'] in ['r', 'rf']: if h['type'] == 'rf': self.freeHandleMoved = True if not self.rotateAllowed: return ## If the handle is directly over its center point, we can't compute an angle. try: if lp1.length() == 0 or lp0.length() == 0: return except OverflowError: return ## determine new rotation angle, constrained if necessary ang = newState['angle'] - lp0.angle(lp1) if ang is None: ## this should never happen.. return if self.rotateSnap or (modifiers & QtCore.Qt.ControlModifier): ang = round(ang / 15.) * 15. ## 180/12 = 15 ## create rotation transform tr = QtGui.QTransform() tr.rotate(ang) ## move ROI so that center point remains stationary after rotate cc = self.mapToParent(cs) - (tr.map(cs) + self.state['pos']) newState['angle'] = ang newState['pos'] = newState['pos'] + cc ## check boundaries, update if self.maxBounds is not None: r = self.stateRect(newState) if not self.maxBounds.contains(r): return #self.setTransform(tr) self.setPos(newState['pos'], update=False) self.setAngle(ang, update=False) #self.state = newState ## If this is a free-rotate handle, its distance from the center may change. if h['type'] == 'rf': h['item'].setPos(self.mapFromScene(p1)) ## changes ROI coordinates of handle elif h['type'] == 'sr': if h['center'][0] == h['pos'][0]: scaleAxis = 1 nonScaleAxis=0 else: scaleAxis = 0 nonScaleAxis=1 try: if lp1.length() == 0 or lp0.length() == 0: return except OverflowError: return ang = newState['angle'] - lp0.angle(lp1) if ang is None: return if self.rotateSnap or (modifiers & QtCore.Qt.ControlModifier): #ang = round(ang / (np.pi/12.)) * (np.pi/12.) ang = round(ang / 15.) * 15. hs = abs(h['pos'][scaleAxis] - c[scaleAxis]) newState['size'][scaleAxis] = lp1.length() / hs #if self.scaleSnap or (modifiers & QtCore.Qt.ControlModifier): if self.scaleSnap: ## use CTRL only for angular snap here. newState['size'][scaleAxis] = round(newState['size'][scaleAxis] / self.snapSize) * self.snapSize if newState['size'][scaleAxis] == 0: newState['size'][scaleAxis] = 1 if self.aspectLocked: newState['size'][nonScaleAxis] = newState['size'][scaleAxis] c1 = c * newState['size'] tr = QtGui.QTransform() tr.rotate(ang) cc = self.mapToParent(cs) - (tr.map(c1) + self.state['pos']) newState['angle'] = ang newState['pos'] = newState['pos'] + cc if self.maxBounds is not None: r = self.stateRect(newState) if not self.maxBounds.contains(r): return #self.setTransform(tr) #self.setPos(newState['pos'], update=False) #self.prepareGeometryChange() #self.state = newState self.setState(newState, update=False) self.stateChanged(finish=finish) def stateChanged(self, finish=True): """Process changes to the state of the ROI. If there are any changes, then the positions of handles are updated accordingly and sigRegionChanged is emitted. If finish is True, then sigRegionChangeFinished will also be emitted.""" changed = False if self.lastState is None: changed = True else: for k in list(self.state.keys()): if self.state[k] != self.lastState[k]: changed = True self.prepareGeometryChange() if changed: ## Move all handles to match the current configuration of the ROI for h in self.handles: if h['item'] in self.childItems(): p = h['pos'] h['item'].setPos(h['pos'] * self.state['size']) #else: # trans = self.state['pos']-self.lastState['pos'] # h['item'].setPos(h['pos'] + h['item'].parentItem().mapFromParent(trans)) self.update() self.sigRegionChanged.emit(self) elif self.freeHandleMoved: self.sigRegionChanged.emit(self) self.freeHandleMoved = False self.lastState = self.stateCopy() if finish: self.stateChangeFinished() def stateChangeFinished(self): self.sigRegionChangeFinished.emit(self) def stateRect(self, state): r = QtCore.QRectF(0, 0, state['size'][0], state['size'][1]) tr = QtGui.QTransform() #tr.rotate(-state['angle'] * 180 / np.pi) tr.rotate(-state['angle']) r = tr.mapRect(r) return r.adjusted(state['pos'][0], state['pos'][1], state['pos'][0], state['pos'][1]) def getSnapPosition(self, pos, snap=None): ## Given that pos has been requested, return the nearest snap-to position ## optionally, snap may be passed in to specify a rectangular snap grid. ## override this function for more interesting snap functionality.. if snap is None or snap is True: if self.snapSize is None: return pos snap = Point(self.snapSize, self.snapSize) return Point( round(pos[0] / snap[0]) * snap[0], round(pos[1] / snap[1]) * snap[1] ) def boundingRect(self): return QtCore.QRectF(0, 0, self.state['size'][0], self.state['size'][1]).normalized() def paint(self, p, opt, widget): # p.save() # Note: don't use self.boundingRect here, because subclasses may need to redefine it. r = QtCore.QRectF(0, 0, self.state['size'][0], self.state['size'][1]).normalized() p.setRenderHint(QtGui.QPainter.Antialiasing) p.setPen(self.currentPen) p.translate(r.left(), r.top()) p.scale(r.width(), r.height()) p.drawRect(0, 0, 1, 1) # p.restore() def getArraySlice(self, data, img, axes=(0,1), returnSlice=True): """Return a tuple of slice objects that can be used to slice the region from data covered by this ROI. Also returns the transform which maps the ROI into data coordinates. If returnSlice is set to False, the function returns a pair of tuples with the values that would have been used to generate the slice objects. ((ax0Start, ax0Stop), (ax1Start, ax1Stop)) If the slice can not be computed (usually because the scene/transforms are not properly constructed yet), then the method returns None. """ #print "getArraySlice" ## Determine shape of array along ROI axes dShape = (data.shape[axes[0]], data.shape[axes[1]]) #print " dshape", dShape ## Determine transform that maps ROI bounding box to image coordinates try: tr = self.sceneTransform() * fn.invertQTransform(img.sceneTransform()) except np.linalg.linalg.LinAlgError: return None ## Modify transform to scale from image coords to data coords #m = QtGui.QTransform() tr.scale(float(dShape[0]) / img.width(), float(dShape[1]) / img.height()) #tr = tr * m ## Transform ROI bounds into data bounds dataBounds = tr.mapRect(self.boundingRect()) #print " boundingRect:", self.boundingRect() #print " dataBounds:", dataBounds ## Intersect transformed ROI bounds with data bounds intBounds = dataBounds.intersected(QtCore.QRectF(0, 0, dShape[0], dShape[1])) #print " intBounds:", intBounds ## Determine index values to use when referencing the array. bounds = ( (int(min(intBounds.left(), intBounds.right())), int(1+max(intBounds.left(), intBounds.right()))), (int(min(intBounds.bottom(), intBounds.top())), int(1+max(intBounds.bottom(), intBounds.top()))) ) #print " bounds:", bounds if returnSlice: ## Create slice objects sl = [slice(None)] * data.ndim sl[axes[0]] = slice(*bounds[0]) sl[axes[1]] = slice(*bounds[1]) return tuple(sl), tr else: return bounds, tr def getArrayRegion(self, data, img, axes=(0,1), returnMappedCoords=False, **kwds): """Use the position and orientation of this ROI relative to an imageItem to pull a slice from an array. =================== ==================================================== **Arguments** data The array to slice from. Note that this array does *not* have to be the same data that is represented in *img*. img (ImageItem or other suitable QGraphicsItem) Used to determine the relationship between the ROI and the boundaries of *data*. axes (length-2 tuple) Specifies the axes in *data* that correspond to the x and y axes of *img*. returnMappedCoords (bool) If True, the array slice is returned along with a corresponding array of coordinates that were used to extract data from the original array. \**kwds All keyword arguments are passed to :func:`affineSlice <pyqtgraph.affineSlice>`. =================== ==================================================== This method uses :func:`affineSlice <pyqtgraph.affineSlice>` to generate the slice from *data* and uses :func:`getAffineSliceParams <pyqtgraph.ROI.getAffineSliceParams>` to determine the parameters to pass to :func:`affineSlice <pyqtgraph.affineSlice>`. If *returnMappedCoords* is True, then the method returns a tuple (result, coords) such that coords is the set of coordinates used to interpolate values from the original data, mapped into the parent coordinate system of the image. This is useful, when slicing data from images that have been transformed, for determining the location of each value in the sliced data. All extra keyword arguments are passed to :func:`affineSlice <pyqtgraph.affineSlice>`. """ shape, vectors, origin = self.getAffineSliceParams(data, img, axes) if not returnMappedCoords: return fn.affineSlice(data, shape=shape, vectors=vectors, origin=origin, axes=axes, **kwds) else: kwds['returnCoords'] = True result, coords = fn.affineSlice(data, shape=shape, vectors=vectors, origin=origin, axes=axes, **kwds) ### map coordinates and return mapped = fn.transformCoordinates(img.transform(), coords) return result, mapped def getAffineSliceParams(self, data, img, axes=(0,1)): """ Returns the parameters needed to use :func:`affineSlice <pyqtgraph.affineSlice>` (shape, vectors, origin) to extract a subset of *data* using this ROI and *img* to specify the subset. See :func:`getArrayRegion <pyqtgraph.ROI.getArrayRegion>` for more information. """ if self.scene() is not img.scene(): raise Exception("ROI and target item must be members of the same scene.") shape = self.state['size'] origin = self.mapToItem(img, QtCore.QPointF(0, 0)) ## vx and vy point in the directions of the slice axes, but must be scaled properly vx = self.mapToItem(img, QtCore.QPointF(1, 0)) - origin vy = self.mapToItem(img, QtCore.QPointF(0, 1)) - origin lvx = np.sqrt(vx.x()**2 + vx.y()**2) lvy = np.sqrt(vy.x()**2 + vy.y()**2) pxLen = img.width() / float(data.shape[axes[0]]) #img.width is number of pixels or width of item? #need pxWidth and pxHeight instead of pxLen ? sx = pxLen / lvx sy = pxLen / lvy vectors = ((vx.x()*sx, vx.y()*sx), (vy.x()*sy, vy.y()*sy)) shape = self.state['size'] shape = [abs(shape[0]/sx), abs(shape[1]/sy)] origin = (origin.x(), origin.y()) return shape, vectors, origin def getGlobalTransform(self, relativeTo=None): """Return global transformation (rotation angle+translation) required to move from relative state to current state. If relative state isn't specified, then we use the state of the ROI when mouse is pressed.""" if relativeTo == None: relativeTo = self.preMoveState st = self.getState() ## this is only allowed because we will be comparing the two relativeTo['scale'] = relativeTo['size'] st['scale'] = st['size'] t1 = SRTTransform(relativeTo) t2 = SRTTransform(st) return t2/t1 #st = self.getState() ### rotation #ang = (st['angle']-relativeTo['angle']) * 180. / 3.14159265358 #rot = QtGui.QTransform() #rot.rotate(-ang) ### We need to come up with a universal transformation--one that can be applied to other objects ### such that all maintain alignment. ### More specifically, we need to turn the ROI's position and angle into ### a rotation _around the origin_ and a translation. #p0 = Point(relativeTo['pos']) ### base position, rotated #p1 = rot.map(p0) #trans = Point(st['pos']) - p1 #return trans, ang def applyGlobalTransform(self, tr): st = self.getState() st['scale'] = st['size'] st = SRTTransform(st) st = (st * tr).saveState() st['size'] = st['scale'] self.setState(st) class Handle(UIGraphicsItem): """ Handle represents a single user-interactable point attached to an ROI. They are usually created by a call to one of the ROI.add___Handle() methods. Handles are represented as a square, diamond, or circle, and are drawn with fixed pixel size regardless of the scaling of the view they are displayed in. Handles may be dragged to change the position, size, orientation, or other properties of the ROI they are attached to. """ types = { ## defines number of sides, start angle for each handle type 't': (4, np.pi/4), 'f': (4, np.pi/4), 's': (4, 0), 'r': (12, 0), 'sr': (12, 0), 'rf': (12, 0), } sigClicked = QtCore.Signal(object, object) # self, event sigRemoveRequested = QtCore.Signal(object) # self def __init__(self, radius, typ=None, pen=(200, 200, 220), parent=None, deletable=False): #print " create item with parent", parent #self.bounds = QtCore.QRectF(-1e-10, -1e-10, 2e-10, 2e-10) #self.setFlags(self.ItemIgnoresTransformations | self.ItemSendsScenePositionChanges) self.rois = [] self.radius = radius self.typ = typ self.pen = fn.mkPen(pen) self.currentPen = self.pen self.pen.setWidth(0) self.pen.setCosmetic(True) self.isMoving = False self.sides, self.startAng = self.types[typ] self.buildPath() self._shape = None self.menu = self.buildMenu() UIGraphicsItem.__init__(self, parent=parent) self.setAcceptedMouseButtons(QtCore.Qt.NoButton) self.deletable = deletable if deletable: self.setAcceptedMouseButtons(QtCore.Qt.RightButton) #self.updateShape() self.setZValue(11) def connectROI(self, roi): ### roi is the "parent" roi, i is the index of the handle in roi.handles self.rois.append(roi) def disconnectROI(self, roi): self.rois.remove(roi) #for i, r in enumerate(self.roi): #if r[0] == roi: #self.roi.pop(i) #def close(self): #for r in self.roi: #r.removeHandle(self) def setDeletable(self, b): self.deletable = b if b: self.setAcceptedMouseButtons(self.acceptedMouseButtons() | QtCore.Qt.RightButton) else: self.setAcceptedMouseButtons(self.acceptedMouseButtons() & ~QtCore.Qt.RightButton) def removeClicked(self): self.sigRemoveRequested.emit(self) def hoverEvent(self, ev): hover = False if not ev.isExit(): if ev.acceptDrags(QtCore.Qt.LeftButton): hover=True for btn in [QtCore.Qt.LeftButton, QtCore.Qt.RightButton, QtCore.Qt.MidButton]: if int(self.acceptedMouseButtons() & btn) > 0 and ev.acceptClicks(btn): hover=True if hover: self.currentPen = fn.mkPen(255, 255,0) else: self.currentPen = self.pen self.update() #if (not ev.isExit()) and ev.acceptDrags(QtCore.Qt.LeftButton): #self.currentPen = fn.mkPen(255, 255,0) #else: #self.currentPen = self.pen #self.update() def mouseClickEvent(self, ev): ## right-click cancels drag if ev.button() == QtCore.Qt.RightButton and self.isMoving: self.isMoving = False ## prevents any further motion self.movePoint(self.startPos, finish=True) #for r in self.roi: #r[0].cancelMove() ev.accept() elif int(ev.button() & self.acceptedMouseButtons()) > 0: ev.accept() if ev.button() == QtCore.Qt.RightButton and self.deletable: self.raiseContextMenu(ev) self.sigClicked.emit(self, ev) else: ev.ignore() #elif self.deletable: #ev.accept() #self.raiseContextMenu(ev) #else: #ev.ignore() def buildMenu(self): menu = QtGui.QMenu() menu.setTitle("Handle") self.removeAction = menu.addAction("Remove handle", self.removeClicked) return menu def getMenu(self): return self.menu def raiseContextMenu(self, ev): menu = self.scene().addParentContextMenus(self, self.getMenu(), ev) ## Make sure it is still ok to remove this handle removeAllowed = all([r.checkRemoveHandle(self) for r in self.rois]) self.removeAction.setEnabled(removeAllowed) pos = ev.screenPos() menu.popup(QtCore.QPoint(pos.x(), pos.y())) def mouseDragEvent(self, ev): if ev.button() != QtCore.Qt.LeftButton: return ev.accept() ## Inform ROIs that a drag is happening ## note: the ROI is informed that the handle has moved using ROI.movePoint ## this is for other (more nefarious) purposes. #for r in self.roi: #r[0].pointDragEvent(r[1], ev) if ev.isFinish(): if self.isMoving: for r in self.rois: r.stateChangeFinished() self.isMoving = False elif ev.isStart(): for r in self.rois: r.handleMoveStarted() self.isMoving = True self.startPos = self.scenePos() self.cursorOffset = self.scenePos() - ev.buttonDownScenePos() if self.isMoving: ## note: isMoving may become False in mid-drag due to right-click. pos = ev.scenePos() + self.cursorOffset self.movePoint(pos, ev.modifiers(), finish=False) def movePoint(self, pos, modifiers=QtCore.Qt.KeyboardModifier(), finish=True): for r in self.rois: if not r.checkPointMove(self, pos, modifiers): return #print "point moved; inform %d ROIs" % len(self.roi) # A handle can be used by multiple ROIs; tell each to update its handle position for r in self.rois: r.movePoint(self, pos, modifiers, finish=finish, coords='scene') def buildPath(self): size = self.radius self.path = QtGui.QPainterPath() ang = self.startAng dt = 2*np.pi / self.sides for i in range(0, self.sides+1): x = size * cos(ang) y = size * sin(ang) ang += dt if i == 0: self.path.moveTo(x, y) else: self.path.lineTo(x, y) def paint(self, p, opt, widget): ### determine rotation of transform #m = self.sceneTransform() ##mi = m.inverted()[0] #v = m.map(QtCore.QPointF(1, 0)) - m.map(QtCore.QPointF(0, 0)) #va = np.arctan2(v.y(), v.x()) ### Determine length of unit vector in painter's coords ##size = mi.map(Point(self.radius, self.radius)) - mi.map(Point(0, 0)) ##size = (size.x()*size.x() + size.y() * size.y()) ** 0.5 #size = self.radius #bounds = QtCore.QRectF(-size, -size, size*2, size*2) #if bounds != self.bounds: #self.bounds = bounds #self.prepareGeometryChange() p.setRenderHints(p.Antialiasing, True) p.setPen(self.currentPen) #p.rotate(va * 180. / 3.1415926) #p.drawPath(self.path) p.drawPath(self.shape()) #ang = self.startAng + va #dt = 2*np.pi / self.sides #for i in range(0, self.sides): #x1 = size * cos(ang) #y1 = size * sin(ang) #x2 = size * cos(ang+dt) #y2 = size * sin(ang+dt) #ang += dt #p.drawLine(Point(x1, y1), Point(x2, y2)) def shape(self): if self._shape is None: s = self.generateShape() if s is None: return self.path self._shape = s self.prepareGeometryChange() ## beware--this can cause the view to adjust, which would immediately invalidate the shape. return self._shape def boundingRect(self): #print 'roi:', self.roi s1 = self.shape() #print " s1:", s1 #s2 = self.shape() #print " s2:", s2 return self.shape().boundingRect() def generateShape(self): ## determine rotation of transform #m = self.sceneTransform() ## Qt bug: do not access sceneTransform() until we know this object has a scene. #mi = m.inverted()[0] dt = self.deviceTransform() if dt is None: self._shape = self.path return None v = dt.map(QtCore.QPointF(1, 0)) - dt.map(QtCore.QPointF(0, 0)) va = np.arctan2(v.y(), v.x()) dti = fn.invertQTransform(dt) devPos = dt.map(QtCore.QPointF(0,0)) tr = QtGui.QTransform() tr.translate(devPos.x(), devPos.y()) tr.rotate(va * 180. / 3.1415926) return dti.map(tr.map(self.path)) def viewTransformChanged(self): GraphicsObject.viewTransformChanged(self) self._shape = None ## invalidate shape, recompute later if requested. self.update() #def itemChange(self, change, value): #if change == self.ItemScenePositionHasChanged: #self.updateShape() class TestROI(ROI): def __init__(self, pos, size, **args): #QtGui.QGraphicsRectItem.__init__(self, pos[0], pos[1], size[0], size[1]) ROI.__init__(self, pos, size, **args) #self.addTranslateHandle([0, 0]) self.addTranslateHandle([0.5, 0.5]) self.addScaleHandle([1, 1], [0, 0]) self.addScaleHandle([0, 0], [1, 1]) self.addScaleRotateHandle([1, 0.5], [0.5, 0.5]) self.addScaleHandle([0.5, 1], [0.5, 0.5]) self.addRotateHandle([1, 0], [0, 0]) self.addRotateHandle([0, 1], [1, 1]) class RectROI(ROI): """ Rectangular ROI subclass with a single scale handle at the top-right corner. ============== ============================================================= **Arguments** pos (length-2 sequence) The position of the ROI origin. See ROI(). size (length-2 sequence) The size of the ROI. See ROI(). centered (bool) If True, scale handles affect the ROI relative to its center, rather than its origin. sideScalers (bool) If True, extra scale handles are added at the top and right edges. \**args All extra keyword arguments are passed to ROI() ============== ============================================================= """ def __init__(self, pos, size, centered=False, sideScalers=False, **args): #QtGui.QGraphicsRectItem.__init__(self, 0, 0, size[0], size[1]) ROI.__init__(self, pos, size, **args) if centered: center = [0.5, 0.5] else: center = [0, 0] #self.addTranslateHandle(center) self.addScaleHandle([1, 1], center) if sideScalers: self.addScaleHandle([1, 0.5], [center[0], 0.5]) self.addScaleHandle([0.5, 1], [0.5, center[1]]) class LineROI(ROI): """ Rectangular ROI subclass with scale-rotate handles on either side. This allows the ROI to be positioned as if moving the ends of a line segment. A third handle controls the width of the ROI orthogonal to its "line" axis. ============== ============================================================= **Arguments** pos1 (length-2 sequence) The position of the center of the ROI's left edge. pos2 (length-2 sequence) The position of the center of the ROI's right edge. width (float) The width of the ROI. \**args All extra keyword arguments are passed to ROI() ============== ============================================================= """ def __init__(self, pos1, pos2, width, **args): pos1 = Point(pos1) pos2 = Point(pos2) d = pos2-pos1 l = d.length() ang = Point(1, 0).angle(d) ra = ang * np.pi / 180. c = Point(-width/2. * sin(ra), -width/2. * cos(ra)) pos1 = pos1 + c ROI.__init__(self, pos1, size=Point(l, width), angle=ang, **args) self.addScaleRotateHandle([0, 0.5], [1, 0.5]) self.addScaleRotateHandle([1, 0.5], [0, 0.5]) self.addScaleHandle([0.5, 1], [0.5, 0.5]) class MultiRectROI(QtGui.QGraphicsObject): """ Chain of rectangular ROIs connected by handles. This is generally used to mark a curved path through an image similarly to PolyLineROI. It differs in that each segment of the chain is rectangular instead of linear and thus has width. ============== ============================================================= **Arguments** points (list of length-2 sequences) The list of points in the path. width (float) The width of the ROIs orthogonal to the path. \**args All extra keyword arguments are passed to ROI() ============== ============================================================= """ sigRegionChangeFinished = QtCore.Signal(object) sigRegionChangeStarted = QtCore.Signal(object) sigRegionChanged = QtCore.Signal(object) def __init__(self, points, width, pen=None, **args): QtGui.QGraphicsObject.__init__(self) self.pen = pen self.roiArgs = args self.lines = [] if len(points) < 2: raise Exception("Must start with at least 2 points") ## create first segment self.addSegment(points[1], connectTo=points[0], scaleHandle=True) ## create remaining segments for p in points[2:]: self.addSegment(p) def paint(self, *args): pass def boundingRect(self): return QtCore.QRectF() def roiChangedEvent(self): w = self.lines[0].state['size'][1] for l in self.lines[1:]: w0 = l.state['size'][1] if w == w0: continue l.scale([1.0, w/w0], center=[0.5,0.5]) self.sigRegionChanged.emit(self) def roiChangeStartedEvent(self): self.sigRegionChangeStarted.emit(self) def roiChangeFinishedEvent(self): self.sigRegionChangeFinished.emit(self) def getHandlePositions(self): """Return the positions of all handles in local coordinates.""" pos = [self.mapFromScene(self.lines[0].getHandles()[0].scenePos())] for l in self.lines: pos.append(self.mapFromScene(l.getHandles()[1].scenePos())) return pos def getArrayRegion(self, arr, img=None, axes=(0,1)): rgns = [] for l in self.lines: rgn = l.getArrayRegion(arr, img, axes=axes) if rgn is None: continue #return None rgns.append(rgn) #print l.state['size'] ## make sure orthogonal axis is the same size ## (sometimes fp errors cause differences) ms = min([r.shape[axes[1]] for r in rgns]) sl = [slice(None)] * rgns[0].ndim sl[axes[1]] = slice(0,ms) rgns = [r[sl] for r in rgns] #print [r.shape for r in rgns], axes return np.concatenate(rgns, axis=axes[0]) def addSegment(self, pos=(0,0), scaleHandle=False, connectTo=None): """ Add a new segment to the ROI connecting from the previous endpoint to *pos*. (pos is specified in the parent coordinate system of the MultiRectROI) """ ## by default, connect to the previous endpoint if connectTo is None: connectTo = self.lines[-1].getHandles()[1] ## create new ROI newRoi = ROI((0,0), [1, 5], parent=self, pen=self.pen, **self.roiArgs) self.lines.append(newRoi) ## Add first SR handle if isinstance(connectTo, Handle): self.lines[-1].addScaleRotateHandle([0, 0.5], [1, 0.5], item=connectTo) newRoi.movePoint(connectTo, connectTo.scenePos(), coords='scene') else: h = self.lines[-1].addScaleRotateHandle([0, 0.5], [1, 0.5]) newRoi.movePoint(h, connectTo, coords='scene') ## add second SR handle h = self.lines[-1].addScaleRotateHandle([1, 0.5], [0, 0.5]) newRoi.movePoint(h, pos) ## optionally add scale handle (this MUST come after the two SR handles) if scaleHandle: newRoi.addScaleHandle([0.5, 1], [0.5, 0.5]) newRoi.translatable = False newRoi.sigRegionChanged.connect(self.roiChangedEvent) newRoi.sigRegionChangeStarted.connect(self.roiChangeStartedEvent) newRoi.sigRegionChangeFinished.connect(self.roiChangeFinishedEvent) self.sigRegionChanged.emit(self) def removeSegment(self, index=-1): """Remove a segment from the ROI.""" roi = self.lines[index] self.lines.pop(index) self.scene().removeItem(roi) roi.sigRegionChanged.disconnect(self.roiChangedEvent) roi.sigRegionChangeStarted.disconnect(self.roiChangeStartedEvent) roi.sigRegionChangeFinished.disconnect(self.roiChangeFinishedEvent) self.sigRegionChanged.emit(self) class MultiLineROI(MultiRectROI): def __init__(self, *args, **kwds): MultiRectROI.__init__(self, *args, **kwds) print("Warning: MultiLineROI has been renamed to MultiRectROI. (and MultiLineROI may be redefined in the future)") class EllipseROI(ROI): """ Elliptical ROI subclass with one scale handle and one rotation handle. ============== ============================================================= **Arguments** pos (length-2 sequence) The position of the ROI's origin. size (length-2 sequence) The size of the ROI's bounding rectangle. \**args All extra keyword arguments are passed to ROI() ============== ============================================================= """ def __init__(self, pos, size, **args): #QtGui.QGraphicsRectItem.__init__(self, 0, 0, size[0], size[1]) ROI.__init__(self, pos, size, **args) self.addRotateHandle([1.0, 0.5], [0.5, 0.5]) self.addScaleHandle([0.5*2.**-0.5 + 0.5, 0.5*2.**-0.5 + 0.5], [0.5, 0.5]) def paint(self, p, opt, widget): r = self.boundingRect() p.setRenderHint(QtGui.QPainter.Antialiasing) p.setPen(self.currentPen) p.scale(r.width(), r.height())## workaround for GL bug r = QtCore.QRectF(r.x()/r.width(), r.y()/r.height(), 1,1) p.drawEllipse(r) def getArrayRegion(self, arr, img=None): """ Return the result of ROI.getArrayRegion() masked by the elliptical shape of the ROI. Regions outside the ellipse are set to 0. """ arr = ROI.getArrayRegion(self, arr, img) if arr is None or arr.shape[0] == 0 or arr.shape[1] == 0: return None w = arr.shape[0] h = arr.shape[1] ## generate an ellipsoidal mask mask = np.fromfunction(lambda x,y: (((x+0.5)/(w/2.)-1)**2+ ((y+0.5)/(h/2.)-1)**2)**0.5 < 1, (w, h)) return arr * mask def shape(self): self.path = QtGui.QPainterPath() self.path.addEllipse(self.boundingRect()) return self.path class CircleROI(EllipseROI): """ Circular ROI subclass. Behaves exactly as EllipseROI, but may only be scaled proportionally to maintain its aspect ratio. ============== ============================================================= **Arguments** pos (length-2 sequence) The position of the ROI's origin. size (length-2 sequence) The size of the ROI's bounding rectangle. \**args All extra keyword arguments are passed to ROI() ============== ============================================================= """ def __init__(self, pos, size, **args): ROI.__init__(self, pos, size, **args) self.aspectLocked = True #self.addTranslateHandle([0.5, 0.5]) self.addScaleHandle([0.5*2.**-0.5 + 0.5, 0.5*2.**-0.5 + 0.5], [0.5, 0.5]) class PolygonROI(ROI): ## deprecated. Use PloyLineROI instead. def __init__(self, positions, pos=None, **args): if pos is None: pos = [0,0] ROI.__init__(self, pos, [1,1], **args) #ROI.__init__(self, positions[0]) for p in positions: self.addFreeHandle(p) self.setZValue(1000) print("Warning: PolygonROI is deprecated. Use PolyLineROI instead.") def listPoints(self): return [p['item'].pos() for p in self.handles] #def movePoint(self, *args, **kargs): #ROI.movePoint(self, *args, **kargs) #self.prepareGeometryChange() #for h in self.handles: #h['pos'] = h['item'].pos() def paint(self, p, *args): p.setRenderHint(QtGui.QPainter.Antialiasing) p.setPen(self.currentPen) for i in range(len(self.handles)): h1 = self.handles[i]['item'].pos() h2 = self.handles[i-1]['item'].pos() p.drawLine(h1, h2) def boundingRect(self): r = QtCore.QRectF() for h in self.handles: r |= self.mapFromItem(h['item'], h['item'].boundingRect()).boundingRect() ## |= gives the union of the two QRectFs return r def shape(self): p = QtGui.QPainterPath() p.moveTo(self.handles[0]['item'].pos()) for i in range(len(self.handles)): p.lineTo(self.handles[i]['item'].pos()) return p def stateCopy(self): sc = {} sc['pos'] = Point(self.state['pos']) sc['size'] = Point(self.state['size']) sc['angle'] = self.state['angle'] #sc['handles'] = self.handles return sc class PolyLineROI(ROI): """ Container class for multiple connected LineSegmentROIs. This class allows the user to draw paths of multiple line segments. ============== ============================================================= **Arguments** positions (list of length-2 sequences) The list of points in the path. Note that, unlike the handle positions specified in other ROIs, these positions must be expressed in the normal coordinate system of the ROI, rather than (0 to 1) relative to the size of the ROI. closed (bool) if True, an extra LineSegmentROI is added connecting the beginning and end points. \**args All extra keyword arguments are passed to ROI() ============== ============================================================= """ def __init__(self, positions, closed=False, pos=None, **args): if pos is None: pos = [0,0] self.closed = closed self.segments = [] ROI.__init__(self, pos, size=[1,1], **args) self.setPoints(positions) #for p in positions: #self.addFreeHandle(p) #start = -1 if self.closed else 0 #for i in range(start, len(self.handles)-1): #self.addSegment(self.handles[i]['item'], self.handles[i+1]['item']) def setPoints(self, points, closed=None): """ Set the complete sequence of points displayed by this ROI. ============= ========================================================= **Arguments** points List of (x,y) tuples specifying handle locations to set. closed If bool, then this will set whether the ROI is closed (the last point is connected to the first point). If None, then the closed mode is left unchanged. ============= ========================================================= """ if closed is not None: self.closed = closed for p in points: self.addFreeHandle(p) start = -1 if self.closed else 0 for i in range(start, len(self.handles)-1): self.addSegment(self.handles[i]['item'], self.handles[i+1]['item']) def clearPoints(self): """ Remove all handles and segments. """ while len(self.handles) > 0: self.removeHandle(self.handles[0]['item']) def saveState(self): state = ROI.saveState(self) state['closed'] = self.closed state['points'] = [tuple(h.pos()) for h in self.getHandles()] return state def setState(self, state): ROI.setState(self, state) self.clearPoints() self.setPoints(state['points'], closed=state['closed']) def addSegment(self, h1, h2, index=None): seg = LineSegmentROI(handles=(h1, h2), pen=self.pen, parent=self, movable=False) if index is None: self.segments.append(seg) else: self.segments.insert(index, seg) seg.sigClicked.connect(self.segmentClicked) seg.setAcceptedMouseButtons(QtCore.Qt.LeftButton) seg.setZValue(self.zValue()+1) for h in seg.handles: h['item'].setDeletable(True) h['item'].setAcceptedMouseButtons(h['item'].acceptedMouseButtons() | QtCore.Qt.LeftButton) ## have these handles take left clicks too, so that handles cannot be added on top of other handles def setMouseHover(self, hover): ## Inform all the ROI's segments that the mouse is(not) hovering over it ROI.setMouseHover(self, hover) for s in self.segments: s.setMouseHover(hover) def addHandle(self, info, index=None): h = ROI.addHandle(self, info, index=index) h.sigRemoveRequested.connect(self.removeHandle) return h def segmentClicked(self, segment, ev=None, pos=None): ## pos should be in this item's coordinate system if ev != None: pos = segment.mapToParent(ev.pos()) elif pos != None: pos = pos else: raise Exception("Either an event or a position must be given.") h1 = segment.handles[0]['item'] h2 = segment.handles[1]['item'] i = self.segments.index(segment) h3 = self.addFreeHandle(pos, index=self.indexOfHandle(h2)) self.addSegment(h3, h2, index=i+1) segment.replaceHandle(h2, h3) def removeHandle(self, handle, updateSegments=True): ROI.removeHandle(self, handle) handle.sigRemoveRequested.disconnect(self.removeHandle) if not updateSegments: return segments = handle.rois[:] if len(segments) == 1: self.removeSegment(segments[0]) else: handles = [h['item'] for h in segments[1].handles] handles.remove(handle) segments[0].replaceHandle(handle, handles[0]) self.removeSegment(segments[1]) def removeSegment(self, seg): for handle in seg.handles[:]: seg.removeHandle(handle['item']) self.segments.remove(seg) seg.sigClicked.disconnect(self.segmentClicked) self.scene().removeItem(seg) def checkRemoveHandle(self, h): ## called when a handle is about to display its context menu if self.closed: return len(self.handles) > 3 else: return len(self.handles) > 2 def paint(self, p, *args): #for s in self.segments: #s.update() #p.setPen(self.currentPen) #p.setPen(fn.mkPen('w')) #p.drawRect(self.boundingRect()) #p.drawPath(self.shape()) pass def boundingRect(self): return self.shape().boundingRect() #r = QtCore.QRectF() #for h in self.handles: #r |= self.mapFromItem(h['item'], h['item'].boundingRect()).boundingRect() ## |= gives the union of the two QRectFs #return r def shape(self): p = QtGui.QPainterPath() if len(self.handles) == 0: return p p.moveTo(self.handles[0]['item'].pos()) for i in range(len(self.handles)): p.lineTo(self.handles[i]['item'].pos()) p.lineTo(self.handles[0]['item'].pos()) return p def getArrayRegion(self, data, img, axes=(0,1), returnMappedCoords=False, **kwds): """ Return the result of ROI.getArrayRegion(), masked by the shape of the ROI. Values outside the ROI shape are set to 0. """ sl = self.getArraySlice(data, img, axes=(0,1)) if sl is None: return None sliced = data[sl[0]] im = QtGui.QImage(sliced.shape[axes[0]], sliced.shape[axes[1]], QtGui.QImage.Format_ARGB32) im.fill(0x0) p = QtGui.QPainter(im) p.setPen(fn.mkPen(None)) p.setBrush(fn.mkBrush('w')) p.setTransform(self.itemTransform(img)[0]) bounds = self.mapRectToItem(img, self.boundingRect()) p.translate(-bounds.left(), -bounds.top()) p.drawPath(self.shape()) p.end() mask = fn.imageToArray(im)[:,:,0].astype(float) / 255. shape = [1] * data.ndim shape[axes[0]] = sliced.shape[axes[0]] shape[axes[1]] = sliced.shape[axes[1]] return sliced * mask.reshape(shape) def setPen(self, *args, **kwds): ROI.setPen(self, *args, **kwds) for seg in self.segments: seg.setPen(*args, **kwds) class LineSegmentROI(ROI): """ ROI subclass with two freely-moving handles defining a line. ============== ============================================================= **Arguments** positions (list of two length-2 sequences) The endpoints of the line segment. Note that, unlike the handle positions specified in other ROIs, these positions must be expressed in the normal coordinate system of the ROI, rather than (0 to 1) relative to the size of the ROI. \**args All extra keyword arguments are passed to ROI() ============== ============================================================= """ def __init__(self, positions=(None, None), pos=None, handles=(None,None), **args): if pos is None: pos = [0,0] ROI.__init__(self, pos, [1,1], **args) #ROI.__init__(self, positions[0]) if len(positions) > 2: raise Exception("LineSegmentROI must be defined by exactly 2 positions. For more points, use PolyLineROI.") for i, p in enumerate(positions): self.addFreeHandle(p, item=handles[i]) def listPoints(self): return [p['item'].pos() for p in self.handles] def paint(self, p, *args): p.setRenderHint(QtGui.QPainter.Antialiasing) p.setPen(self.currentPen) h1 = self.handles[0]['item'].pos() h2 = self.handles[1]['item'].pos() p.drawLine(h1, h2) def boundingRect(self): return self.shape().boundingRect() def shape(self): p = QtGui.QPainterPath() h1 = self.handles[0]['item'].pos() h2 = self.handles[1]['item'].pos() dh = h2-h1 if dh.length() == 0: return p pxv = self.pixelVectors(dh)[1] if pxv is None: return p pxv *= 4 p.moveTo(h1+pxv) p.lineTo(h2+pxv) p.lineTo(h2-pxv) p.lineTo(h1-pxv) p.lineTo(h1+pxv) return p def getArrayRegion(self, data, img, axes=(0,1)): """ Use the position of this ROI relative to an imageItem to pull a slice from an array. Since this pulls 1D data from a 2D coordinate system, the return value will have ndim = data.ndim-1 See ROI.getArrayRegion() for a description of the arguments. """ imgPts = [self.mapToItem(img, h['item'].pos()) for h in self.handles] rgns = [] for i in range(len(imgPts)-1): d = Point(imgPts[i+1] - imgPts[i]) o = Point(imgPts[i]) r = fn.affineSlice(data, shape=(int(d.length()),), vectors=[Point(d.norm())], origin=o, axes=axes, order=1) rgns.append(r) return np.concatenate(rgns, axis=axes[0]) class SpiralROI(ROI): def __init__(self, pos=None, size=None, **args): if size == None: size = [100e-6,100e-6] if pos == None: pos = [0,0] ROI.__init__(self, pos, size, **args) self.translateSnap = False self.addFreeHandle([0.25,0], name='a') self.addRotateFreeHandle([1,0], [0,0], name='r') #self.getRadius() #QtCore.connect(self, QtCore.SIGNAL('regionChanged'), self. def getRadius(self): radius = Point(self.handles[1]['item'].pos()).length() #r2 = radius[1] #r3 = r2[0] return radius def boundingRect(self): r = self.getRadius() return QtCore.QRectF(-r*1.1, -r*1.1, 2.2*r, 2.2*r) #return self.bounds #def movePoint(self, *args, **kargs): #ROI.movePoint(self, *args, **kargs) #self.prepareGeometryChange() #for h in self.handles: #h['pos'] = h['item'].pos()/self.state['size'][0] def stateChanged(self, finish=True): ROI.stateChanged(self, finish=finish) if len(self.handles) > 1: self.path = QtGui.QPainterPath() h0 = Point(self.handles[0]['item'].pos()).length() a = h0/(2.0*np.pi) theta = 30.0*(2.0*np.pi)/360.0 self.path.moveTo(QtCore.QPointF(a*theta*cos(theta), a*theta*sin(theta))) x0 = a*theta*cos(theta) y0 = a*theta*sin(theta) radius = self.getRadius() theta += 20.0*(2.0*np.pi)/360.0 i = 0 while Point(x0, y0).length() < radius and i < 1000: x1 = a*theta*cos(theta) y1 = a*theta*sin(theta) self.path.lineTo(QtCore.QPointF(x1,y1)) theta += 20.0*(2.0*np.pi)/360.0 x0 = x1 y0 = y1 i += 1 return self.path def shape(self): p = QtGui.QPainterPath() p.addEllipse(self.boundingRect()) return p def paint(self, p, *args): p.setRenderHint(QtGui.QPainter.Antialiasing) #path = self.shape() p.setPen(self.currentPen) p.drawPath(self.path) p.setPen(QtGui.QPen(QtGui.QColor(255,0,0))) p.drawPath(self.shape()) p.setPen(QtGui.QPen(QtGui.QColor(0,0,255))) p.drawRect(self.boundingRect()) class CrosshairROI(ROI): """A crosshair ROI whose position is at the center of the crosshairs. By default, it is scalable, rotatable and translatable.""" def __init__(self, pos=None, size=None, **kargs): if size == None: #size = [100e-6,100e-6] size=[1,1] if pos == None: pos = [0,0] self._shape = None ROI.__init__(self, pos, size, **kargs) self.sigRegionChanged.connect(self.invalidate) self.addScaleRotateHandle(Point(1, 0), Point(0, 0)) self.aspectLocked = True def invalidate(self): self._shape = None self.prepareGeometryChange() def boundingRect(self): #size = self.size() #return QtCore.QRectF(-size[0]/2., -size[1]/2., size[0], size[1]).normalized() return self.shape().boundingRect() #def getRect(self): ### same as boundingRect -- for internal use so that boundingRect can be re-implemented in subclasses #size = self.size() #return QtCore.QRectF(-size[0]/2., -size[1]/2., size[0], size[1]).normalized() def shape(self): if self._shape is None: radius = self.getState()['size'][1] p = QtGui.QPainterPath() p.moveTo(Point(0, -radius)) p.lineTo(Point(0, radius)) p.moveTo(Point(-radius, 0)) p.lineTo(Point(radius, 0)) p = self.mapToDevice(p) stroker = QtGui.QPainterPathStroker() stroker.setWidth(10) outline = stroker.createStroke(p) self._shape = self.mapFromDevice(outline) ##h1 = self.handles[0]['item'].pos() ##h2 = self.handles[1]['item'].pos() #w1 = Point(-0.5, 0)*self.size() #w2 = Point(0.5, 0)*self.size() #h1 = Point(0, -0.5)*self.size() #h2 = Point(0, 0.5)*self.size() #dh = h2-h1 #dw = w2-w1 #if dh.length() == 0 or dw.length() == 0: #return p #pxv = self.pixelVectors(dh)[1] #if pxv is None: #return p #pxv *= 4 #p.moveTo(h1+pxv) #p.lineTo(h2+pxv) #p.lineTo(h2-pxv) #p.lineTo(h1-pxv) #p.lineTo(h1+pxv) #pxv = self.pixelVectors(dw)[1] #if pxv is None: #return p #pxv *= 4 #p.moveTo(w1+pxv) #p.lineTo(w2+pxv) #p.lineTo(w2-pxv) #p.lineTo(w1-pxv) #p.lineTo(w1+pxv) return self._shape def paint(self, p, *args): #p.save() #r = self.getRect() radius = self.getState()['size'][1] p.setRenderHint(QtGui.QPainter.Antialiasing) p.setPen(self.currentPen) #p.translate(r.left(), r.top()) #p.scale(r.width()/10., r.height()/10.) ## need to scale up a little because drawLine has trouble dealing with 0.5 #p.drawLine(0,5, 10,5) #p.drawLine(5,0, 5,10) #p.restore() p.drawLine(Point(0, -radius), Point(0, radius)) p.drawLine(Point(-radius, 0), Point(radius, 0))
#import PySide import pyqtgraph as pg import pytest app = pg.mkQApp() qtest = pg.Qt.QtTest.QTest QRectF = pg.QtCore.QRectF def assertMapping(vb, r1, r2): assert vb.mapFromView(r1.topLeft()) == r2.topLeft() assert vb.mapFromView(r1.bottomLeft()) == r2.bottomLeft() assert vb.mapFromView(r1.topRight()) == r2.topRight() assert vb.mapFromView(r1.bottomRight()) == r2.bottomRight() def init_viewbox(): """Helper function to init the ViewBox """ global win, vb win = pg.GraphicsWindow() win.ci.layout.setContentsMargins(0,0,0,0) win.resize(200, 200) win.show() vb = win.addViewBox() # set range before viewbox is shown vb.setRange(xRange=[0, 10], yRange=[0, 10], padding=0) # required to make mapFromView work properly. qtest.qWaitForWindowShown(win) g = pg.GridItem() vb.addItem(g) app.processEvents() def test_ViewBox(): init_viewbox() w = vb.geometry().width() h = vb.geometry().height() view1 = QRectF(0, 0, 10, 10) size1 = QRectF(0, h, w, -h) assertMapping(vb, view1, size1) # test resize win.resize(400, 400) app.processEvents() w = vb.geometry().width() h = vb.geometry().height() size1 = QRectF(0, h, w, -h) assertMapping(vb, view1, size1) # now lock aspect vb.setAspectLocked() # test wide resize win.resize(800, 400) app.processEvents() w = vb.geometry().width() h = vb.geometry().height() view1 = QRectF(-5, 0, 20, 10) size1 = QRectF(0, h, w, -h) assertMapping(vb, view1, size1) # test tall resize win.resize(400, 800) app.processEvents() w = vb.geometry().width() h = vb.geometry().height() view1 = QRectF(0, -5, 10, 20) size1 = QRectF(0, h, w, -h) assertMapping(vb, view1, size1) skipreason = "Skipping this test until someone has time to fix it." @pytest.mark.skipif(True, reason=skipreason) def test_limits_and_resize(): init_viewbox() # now lock aspect vb.setAspectLocked() # test limits + resize (aspect ratio constraint has priority over limits win.resize(400, 400) app.processEvents() vb.setLimits(xMin=0, xMax=10, yMin=0, yMax=10) win.resize(800, 400) app.processEvents() w = vb.geometry().width() h = vb.geometry().height() view1 = QRectF(-5, 0, 20, 10) size1 = QRectF(0, h, w, -h) assertMapping(vb, view1, size1)
ng110/pyqtgraph
pyqtgraph/graphicsItems/ViewBox/tests/test_ViewBox.py
pyqtgraph/graphicsItems/ROI.py
import asyncio import time from asyncio.coroutines import CoroWrapper from inspect import isawaitable from typing import Callable, TypeVar, Optional, Iterable import psutil from common.exceptions import PlenumValueError from stp_core.common.log import getlogger from stp_core.common.util import get_func_name, get_func_args from stp_core.loop.exceptions import EventuallyTimeoutException from stp_core.ratchet import Ratchet # TODO: move it to plenum-util repo T = TypeVar('T') logger = getlogger() FlexFunc = TypeVar('flexFunc', CoroWrapper, Callable[[], T]) def isMinimalConfiguration(): mem = psutil.virtual_memory() memAvailableGb = mem.available / (1024 * 1024 * 1024) # cpuCount = psutil.cpu_count() # we can have a 8 cpu but 100Mb free RAM and the tests will be slow return memAvailableGb <= 1.5 # and cpuCount == 1 # increase this number to allow eventually to change timeouts proportionatly def getSlowFactor(): if isMinimalConfiguration(): return 1.5 else: return 1 slowFactor = getSlowFactor() async def eventuallySoon(coroFunc: FlexFunc, *args): return await eventually(coroFunc, *args, retryWait=0.1, timeout=3, ratchetSteps=10) async def eventuallyAll(*coroFuncs: FlexFunc, # (use functools.partials if needed) totalTimeout: float, retryWait: float=0.1, acceptableExceptions=None, acceptableFails: int=0, override_timeout_limit=False): # TODO: Bug when `acceptableFails` > 0 if the first check fails, it will # exhaust the entire timeout. """ :param coroFuncs: iterable of no-arg functions :param totalTimeout: :param retryWait: :param acceptableExceptions: :param acceptableFails: how many of the passed in coroutines can ultimately fail and still be ok :return: """ start = time.perf_counter() def remaining(): return totalTimeout + start - time.perf_counter() funcNames = [] others = 0 fails = 0 rem = None for cf in coroFuncs: if len(funcNames) < 2: funcNames.append(get_func_name(cf)) else: others += 1 # noinspection PyBroadException try: rem = remaining() if rem <= 0: break await eventually(cf, retryWait=retryWait, timeout=rem, acceptableExceptions=acceptableExceptions, verbose=True, override_timeout_limit=override_timeout_limit) except Exception as ex: if acceptableExceptions and type(ex) not in acceptableExceptions: raise fails += 1 logger.debug("a coro {} with args {} timed out without succeeding; fail count: " "{}, acceptable: {}". format(get_func_name(cf), get_func_args(cf), fails, acceptableFails)) if fails > acceptableFails: raise if rem is not None and rem <= 0: fails += 1 if fails > acceptableFails: err = 'All checks could not complete successfully since total timeout ' \ 'expired {} sec ago'.format(-1 * rem if rem < 0 else 0) raise EventuallyTimeoutException(err) if others: funcNames.append("and {} others".format(others)) desc = ", ".join(funcNames) logger.debug("{} succeeded with {:.2f} seconds to spare". format(desc, remaining())) def recordFail(fname, timeout): pass def recordSuccess(fname, timeout, param, remain): pass async def eventually(coroFunc: FlexFunc, *args, retryWait: float=0.1, timeout: Optional[float] = None, ratchetSteps: Optional[int] = None, acceptableExceptions=None, verbose=True, override_timeout_limit=False) -> T: if timeout is None: timeout = 5 if not timeout > 0: raise PlenumValueError('timeout', timeout, '> 0') if not override_timeout_limit: if timeout > 240: raise PlenumValueError( 'timeout', timeout, "< 240 or override_timeout_limit=True" ) else: logger.debug('Overriding timeout limit to {} for evaluating {}' .format(timeout, coroFunc)) if acceptableExceptions and not isinstance(acceptableExceptions, Iterable): acceptableExceptions = [acceptableExceptions] start = time.perf_counter() ratchet = Ratchet.fromGoalDuration(retryWait * slowFactor, ratchetSteps, timeout * slowFactor).gen() \ if ratchetSteps else None fname = get_func_name(coroFunc) while True: remain = 0 try: remain = start + timeout * slowFactor - time.perf_counter() if remain < 0: # this provides a convenient breakpoint for a debugger logger.debug("{} last try...".format(fname), extra={"cli": False}) # noinspection PyCallingNonCallable res = coroFunc(*args) if isawaitable(res): result = await res else: result = res if verbose: recordSuccess(fname, timeout, timeout * slowFactor, remain) logger.debug("{} succeeded with {:.2f} seconds to spare". format(fname, remain)) return result except Exception as ex: if acceptableExceptions and type(ex) not in acceptableExceptions: raise if remain >= 0: sleep_dur = next(ratchet) if ratchet else retryWait if verbose: logger.trace("{} not succeeded yet, {:.2f} seconds " "remaining..., will sleep for {}".format(fname, remain, sleep_dur)) await asyncio.sleep(sleep_dur) else: recordFail(fname, timeout) logger.error("{} failed; not trying any more because {} " "seconds have passed; args were {}". format(fname, timeout, args)) raise ex
import types import pytest from plenum.test.node_catchup.helper import waitNodeDataEquality from plenum.test.test_node import getNonPrimaryReplicas, get_master_primary_node from plenum.test.view_change.helper import node_received_instance_changes_count from stp_core.loop.eventually import eventually from plenum.test.helper import checkViewNoForNodes, sdk_send_random_and_check def node_primary_disconnected_calls(node): pcm_service = node.master_replica._primary_connection_monitor_service return pcm_service.spylog.count(pcm_service._primary_disconnected) def test_view_not_changed_when_primary_disconnected_from_less_than_quorum( txnPoolNodeSet, looper, sdk_pool_handle, sdk_wallet_client): """ Less than quorum nodes lose connection with primary, this should not trigger view change as the protocol can move ahead """ pr_node = get_master_primary_node(txnPoolNodeSet) npr = getNonPrimaryReplicas(txnPoolNodeSet, 0) partitioned_rep = npr[0] partitioned_node = partitioned_rep.node primary_disconnected_calls = node_primary_disconnected_calls(partitioned_node) recv_inst_chg_calls = {node.name: node_received_instance_changes_count(node) for node in txnPoolNodeSet if node != partitioned_node and node != pr_node} view_no = checkViewNoForNodes(txnPoolNodeSet) def wont_retry(self, exclude=None): # Do not attempt to retry connection pass # simulating a partition here # Disconnect a node from only the primary of the master and dont retry to # connect to it partitioned_node.nodestack.retryDisconnected = types.MethodType( wont_retry, partitioned_node.nodestack) r = partitioned_node.nodestack.getRemote(pr_node.nodestack.name) r.disconnect() def chk1(): # Check that the partitioned node detects losing connection with # primary and sends an instance change which is received by other # nodes except the primary (since its disconnected from primary) assert node_primary_disconnected_calls(partitioned_node) > primary_disconnected_calls for node in txnPoolNodeSet: if node != partitioned_node and node != pr_node: assert node_received_instance_changes_count(node) > recv_inst_chg_calls[node.name] looper.run(eventually(chk1, retryWait=1, timeout=10)) def chk2(): # Check the view does not change with pytest.raises(AssertionError): assert checkViewNoForNodes(txnPoolNodeSet) == view_no + 1 looper.run(eventually(chk2, retryWait=1, timeout=10)) # Send some requests and make sure the request execute sdk_send_random_and_check(looper, txnPoolNodeSet, sdk_pool_handle, sdk_wallet_client, 5) # Partitioned node should have the same ledger and state as others as it gets reqs from all nodes waitNodeDataEquality(looper, partitioned_node, *[n for n in txnPoolNodeSet if n != partitioned_node], exclude_from_check=['check_last_ordered_3pc_backup'])
evernym/plenum
plenum/test/view_change/test_view_not_changed_when_primary_disconnected_from_less_than_quorum.py
stp_core/loop/eventually.py
from sqlobject.dbconnection import registerConnection def builder(): from . import firebirdconnection return firebirdconnection.FirebirdConnection registerConnection(['firebird', 'interbase'], builder)
import math import threading import pytest from sqlobject import SQLObject, StringCol, FloatCol from sqlobject.compat import string_type from sqlobject.sqlbuilder import Select from sqlobject.tests.dbtest import getConnection, setupClass, supports from sqlobject.tests.dbtest import setSQLiteConnectionFactory from .test_basic import SOTestSO1 try: connection = getConnection() except (AttributeError, NameError): # The module was imported during documentation building pass else: if connection.dbName != "sqlite": pytestmark = pytest.mark.skip("These tests require SQLite") class SQLiteFactoryTest(SQLObject): name = StringCol() def test_sqlite_factory(): setupClass(SQLiteFactoryTest) if not SQLiteFactoryTest._connection.using_sqlite2: pytest.skip("These tests require SQLite v2+") factory = [None] def SQLiteConnectionFactory(sqlite): class MyConnection(sqlite.Connection): pass factory[0] = MyConnection return MyConnection setSQLiteConnectionFactory(SQLiteFactoryTest, SQLiteConnectionFactory) conn = SQLiteFactoryTest._connection.makeConnection() assert factory[0] assert isinstance(conn, factory[0]) def test_sqlite_factory_str(): setupClass(SQLiteFactoryTest) if not SQLiteFactoryTest._connection.using_sqlite2: pytest.skip("These tests require SQLite v2+") factory = [None] def SQLiteConnectionFactory(sqlite): class MyConnection(sqlite.Connection): pass factory[0] = MyConnection return MyConnection from sqlobject.sqlite import sqliteconnection sqliteconnection.SQLiteConnectionFactory = SQLiteConnectionFactory setSQLiteConnectionFactory(SQLiteFactoryTest, "SQLiteConnectionFactory") conn = SQLiteFactoryTest._connection.makeConnection() assert factory[0] assert isinstance(conn, factory[0]) del sqliteconnection.SQLiteConnectionFactory def test_sqlite_aggregate(): setupClass(SQLiteFactoryTest) if not SQLiteFactoryTest._connection.using_sqlite2: pytest.skip("These tests require SQLite v2+") def SQLiteConnectionFactory(sqlite): class MyConnection(sqlite.Connection): def __init__(self, *args, **kwargs): super(MyConnection, self).__init__(*args, **kwargs) self.create_aggregate("group_concat", 1, self.group_concat) class group_concat: def __init__(self): self.acc = [] def step(self, value): if isinstance(value, string_type): self.acc.append(value) else: self.acc.append(str(value)) def finalize(self): self.acc.sort() return ", ".join(self.acc) return MyConnection setSQLiteConnectionFactory(SQLiteFactoryTest, SQLiteConnectionFactory) SQLiteFactoryTest(name='sqlobject') SQLiteFactoryTest(name='sqlbuilder') assert SQLiteFactoryTest.select(orderBy="name").\ accumulateOne("group_concat", "name") == \ "sqlbuilder, sqlobject" def do_select(): list(SOTestSO1.select()) def test_sqlite_threaded(): setupClass(SOTestSO1) t = threading.Thread(target=do_select) t.start() t.join() # This should reuse the same connection as the connection # made above (at least will with most database drivers, but # this will cause an error in SQLite): do_select() def test_empty_string(): setupClass(SOTestSO1) test = SOTestSO1(name=None, passwd='') assert test.name is None assert test.passwd == '' def test_memorydb(): if not supports("memorydb"): pytest.skip("memorydb isn't supported") if not connection._memory: pytest.skip("The connection isn't memorydb") setupClass(SOTestSO1) connection.close() # create a new connection to an in-memory database SOTestSO1.setConnection(connection) SOTestSO1.createTable() def test_list_databases(): assert 'main' in connection.listDatabases() def test_list_tables(): setupClass(SOTestSO1) assert SOTestSO1.sqlmeta.table in connection.listTables() class SQLiteTruedivTest(SQLObject): value = FloatCol() def test_truediv(): setupClass(SQLiteTruedivTest) if SQLiteTruedivTest._connection.dbName == "sqlite": if not SQLiteTruedivTest._connection.using_sqlite2: pytest.skip("These tests require SQLite v2+") def SQLiteConnectionFactory(sqlite): class MyConnection(sqlite.Connection): def __init__(self, *args, **kwargs): super(MyConnection, self).__init__(*args, **kwargs) self.create_function("floor", 1, math.floor) return MyConnection setSQLiteConnectionFactory(SQLiteTruedivTest, SQLiteConnectionFactory) SQLiteTruedivTest(value=-5.0) assert SQLiteTruedivTest._connection.queryAll( SQLiteTruedivTest._connection.sqlrepr( Select(SQLiteTruedivTest.q.value // 4)))[0][0] == -2
drnlm/sqlobject
sqlobject/tests/test_sqlite.py
sqlobject/firebird/__init__.py
from sqlobject import IntCol, SQLObject from sqlobject.tests.dbtest import getConnection, setupClass ######################################## # Identity (MS SQL) ######################################## class SOTestIdentity(SQLObject): n = IntCol() def test_identity(): # (re)create table SOTestIdentity.dropTable(connection=getConnection(), ifExists=True) setupClass(SOTestIdentity) # insert without giving identity SOTestIdentity(n=100) # i1 # verify result i1get = SOTestIdentity.get(1) assert(i1get.n == 100) # insert while giving identity SOTestIdentity(id=2, n=200) # i2 # verify result i2get = SOTestIdentity.get(2) assert(i2get.n == 200)
import math import threading import pytest from sqlobject import SQLObject, StringCol, FloatCol from sqlobject.compat import string_type from sqlobject.sqlbuilder import Select from sqlobject.tests.dbtest import getConnection, setupClass, supports from sqlobject.tests.dbtest import setSQLiteConnectionFactory from .test_basic import SOTestSO1 try: connection = getConnection() except (AttributeError, NameError): # The module was imported during documentation building pass else: if connection.dbName != "sqlite": pytestmark = pytest.mark.skip("These tests require SQLite") class SQLiteFactoryTest(SQLObject): name = StringCol() def test_sqlite_factory(): setupClass(SQLiteFactoryTest) if not SQLiteFactoryTest._connection.using_sqlite2: pytest.skip("These tests require SQLite v2+") factory = [None] def SQLiteConnectionFactory(sqlite): class MyConnection(sqlite.Connection): pass factory[0] = MyConnection return MyConnection setSQLiteConnectionFactory(SQLiteFactoryTest, SQLiteConnectionFactory) conn = SQLiteFactoryTest._connection.makeConnection() assert factory[0] assert isinstance(conn, factory[0]) def test_sqlite_factory_str(): setupClass(SQLiteFactoryTest) if not SQLiteFactoryTest._connection.using_sqlite2: pytest.skip("These tests require SQLite v2+") factory = [None] def SQLiteConnectionFactory(sqlite): class MyConnection(sqlite.Connection): pass factory[0] = MyConnection return MyConnection from sqlobject.sqlite import sqliteconnection sqliteconnection.SQLiteConnectionFactory = SQLiteConnectionFactory setSQLiteConnectionFactory(SQLiteFactoryTest, "SQLiteConnectionFactory") conn = SQLiteFactoryTest._connection.makeConnection() assert factory[0] assert isinstance(conn, factory[0]) del sqliteconnection.SQLiteConnectionFactory def test_sqlite_aggregate(): setupClass(SQLiteFactoryTest) if not SQLiteFactoryTest._connection.using_sqlite2: pytest.skip("These tests require SQLite v2+") def SQLiteConnectionFactory(sqlite): class MyConnection(sqlite.Connection): def __init__(self, *args, **kwargs): super(MyConnection, self).__init__(*args, **kwargs) self.create_aggregate("group_concat", 1, self.group_concat) class group_concat: def __init__(self): self.acc = [] def step(self, value): if isinstance(value, string_type): self.acc.append(value) else: self.acc.append(str(value)) def finalize(self): self.acc.sort() return ", ".join(self.acc) return MyConnection setSQLiteConnectionFactory(SQLiteFactoryTest, SQLiteConnectionFactory) SQLiteFactoryTest(name='sqlobject') SQLiteFactoryTest(name='sqlbuilder') assert SQLiteFactoryTest.select(orderBy="name").\ accumulateOne("group_concat", "name") == \ "sqlbuilder, sqlobject" def do_select(): list(SOTestSO1.select()) def test_sqlite_threaded(): setupClass(SOTestSO1) t = threading.Thread(target=do_select) t.start() t.join() # This should reuse the same connection as the connection # made above (at least will with most database drivers, but # this will cause an error in SQLite): do_select() def test_empty_string(): setupClass(SOTestSO1) test = SOTestSO1(name=None, passwd='') assert test.name is None assert test.passwd == '' def test_memorydb(): if not supports("memorydb"): pytest.skip("memorydb isn't supported") if not connection._memory: pytest.skip("The connection isn't memorydb") setupClass(SOTestSO1) connection.close() # create a new connection to an in-memory database SOTestSO1.setConnection(connection) SOTestSO1.createTable() def test_list_databases(): assert 'main' in connection.listDatabases() def test_list_tables(): setupClass(SOTestSO1) assert SOTestSO1.sqlmeta.table in connection.listTables() class SQLiteTruedivTest(SQLObject): value = FloatCol() def test_truediv(): setupClass(SQLiteTruedivTest) if SQLiteTruedivTest._connection.dbName == "sqlite": if not SQLiteTruedivTest._connection.using_sqlite2: pytest.skip("These tests require SQLite v2+") def SQLiteConnectionFactory(sqlite): class MyConnection(sqlite.Connection): def __init__(self, *args, **kwargs): super(MyConnection, self).__init__(*args, **kwargs) self.create_function("floor", 1, math.floor) return MyConnection setSQLiteConnectionFactory(SQLiteTruedivTest, SQLiteConnectionFactory) SQLiteTruedivTest(value=-5.0) assert SQLiteTruedivTest._connection.queryAll( SQLiteTruedivTest._connection.sqlrepr( Select(SQLiteTruedivTest.q.value // 4)))[0][0] == -2
drnlm/sqlobject
sqlobject/tests/test_sqlite.py
sqlobject/tests/test_identity.py
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2014-2018 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # qutebrowser is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with qutebrowser. If not, see <http://www.gnu.org/licenses/>. """Parsing functions for various HTTP headers.""" import os.path from PyQt5.QtNetwork import QNetworkRequest from qutebrowser.utils import log from qutebrowser.browser.webkit import rfc6266 def parse_content_disposition(reply): """Parse a content_disposition header. Args: reply: The QNetworkReply to get a filename for. Return: A (is_inline, filename) tuple. """ is_inline = True filename = None content_disposition_header = 'Content-Disposition'.encode('iso-8859-1') # First check if the Content-Disposition header has a filename # attribute. if reply.hasRawHeader(content_disposition_header): # We use the unsafe variant of the filename as we sanitize it via # os.path.basename later. try: value = bytes(reply.rawHeader(content_disposition_header)) log.rfc6266.debug("Parsing Content-Disposition: {!r}".format( value)) content_disposition = rfc6266.parse_headers(value) filename = content_disposition.filename() except (SyntaxError, UnicodeDecodeError, rfc6266.Error): log.rfc6266.exception("Error while parsing filename") else: is_inline = content_disposition.is_inline() # Then try to get filename from url if not filename: filename = reply.url().path().rstrip('/') # If that fails as well, use a fallback if not filename: filename = 'qutebrowser-download' return is_inline, os.path.basename(filename) def parse_content_type(reply): """Parse a Content-Type header. The parsing done here is very cheap, as we really only want to get the Mimetype. Parameters aren't parsed specially. Args: reply: The QNetworkReply to handle. Return: A [mimetype, rest] list, or [None, None] if unset. Rest can be None. """ content_type = reply.header(QNetworkRequest.ContentTypeHeader) if content_type is None: return [None, None] if ';' in content_type: ret = content_type.split(';', maxsplit=1) else: ret = [content_type, None] ret[0] = ret[0].strip() return ret
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015-2018 Alexander Cogneau (acogneau) <alexander.cogneau@gmail.com>: # # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # qutebrowser is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with qutebrowser. If not, see <http://www.gnu.org/licenses/>. from PyQt5.QtNetwork import QNetworkCookie from PyQt5.QtCore import QUrl import pytest from qutebrowser.browser.webkit import cookies from qutebrowser.utils import usertypes from qutebrowser.misc import lineparser, objects pytestmark = pytest.mark.usefixtures('data_tmpdir') COOKIE1 = b'foo1=bar; expires=Tue, 01-Jan-2036 08:00:01 GMT' COOKIE2 = b'foo2=bar; expires=Tue, 01-Jan-2036 08:00:01 GMT' SESSION_COOKIE = b'foo3=bar' EXPIRED_COOKIE = b'foo4=bar; expires=Sat, 01-Jan-2000 08:00:01 GMT' class LineparserSaveStub(lineparser.BaseLineParser): """A stub for LineParser's save(). Attributes: data: The data before the write saved: The .data before save() """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.saved = [] self.data = [] def save(self): self.saved = self.data def clear(self): pass def __iter__(self): return iter(self.data) def __getitem__(self, key): return self.data[key] def test_set_cookies_accept(config_stub, qtbot, monkeypatch): """Test setCookiesFromUrl with cookies enabled.""" monkeypatch.setattr(objects, 'backend', usertypes.Backend.QtWebKit) config_stub.val.content.cookies.accept = 'all' ram_jar = cookies.RAMCookieJar() cookie = QNetworkCookie(b'foo', b'bar') url = QUrl('http://example.com/') with qtbot.waitSignal(ram_jar.changed): assert ram_jar.setCookiesFromUrl([cookie], url) # assert the cookies are added correctly all_cookies = ram_jar.cookiesForUrl(url) assert len(all_cookies) == 1 saved_cookie = all_cookies[0] expected = cookie.name(), cookie.value() assert saved_cookie.name(), saved_cookie.value() == expected def test_set_cookies_never_accept(qtbot, config_stub, monkeypatch): """Test setCookiesFromUrl when cookies are not accepted.""" monkeypatch.setattr(objects, 'backend', usertypes.Backend.QtWebKit) config_stub.val.content.cookies.accept = 'never' ram_jar = cookies.RAMCookieJar() url = QUrl('http://example.com/') with qtbot.assertNotEmitted(ram_jar.changed): assert not ram_jar.setCookiesFromUrl('test', url) assert not ram_jar.cookiesForUrl(url) def test_cookie_jar_init(config_stub, fake_save_manager): """Test the CookieJar constructor.""" line_parser_stub = [COOKIE1, COOKIE2] jar = cookies.CookieJar(line_parser=line_parser_stub) assert fake_save_manager.add_saveable.called # Test that cookies are added to the jar assert len(jar.allCookies()) == 2 raw_cookies = [c.toRawForm().data() for c in jar.allCookies()] assert raw_cookies == [COOKIE1, COOKIE2] def test_purge_old_cookies(config_stub, fake_save_manager): """Test that expired cookies are deleted.""" line_parser_stub = [COOKIE1, COOKIE2, SESSION_COOKIE, EXPIRED_COOKIE] jar = cookies.CookieJar(line_parser=line_parser_stub) assert len(jar.allCookies()) == 4 jar.purge_old_cookies() # Test that old cookies are gone raw_cookies = [cookie.toRawForm().data() for cookie in jar.allCookies()] assert raw_cookies == [COOKIE1, COOKIE2, SESSION_COOKIE] def test_save(config_stub, fake_save_manager, monkeypatch, qapp): """Test that expired and session cookies are not saved.""" monkeypatch.setattr(lineparser, 'LineParser', LineparserSaveStub) jar = cookies.CookieJar() jar._lineparser.data = [COOKIE1, COOKIE2, SESSION_COOKIE, EXPIRED_COOKIE] # Update the cookies on the jar itself jar.parse_cookies() jar.save() saved_cookies = [cookie.data() for cookie in jar._lineparser.saved] assert saved_cookies == [COOKIE1, COOKIE2] def test_cookies_changed_emit(config_stub, fake_save_manager, monkeypatch, qtbot): """Test that self.changed is emitted.""" monkeypatch.setattr(lineparser, 'LineParser', LineparserSaveStub) jar = cookies.CookieJar() with qtbot.waitSignal(jar.changed): config_stub.val.content.cookies.store = False @pytest.mark.parametrize('store_cookies,empty', [(True, False), (False, True)]) def test_cookies_changed(config_stub, fake_save_manager, monkeypatch, qtbot, store_cookies, empty): """Test that cookies are saved correctly.""" monkeypatch.setattr(lineparser, 'LineParser', LineparserSaveStub) jar = cookies.CookieJar() jar._lineparser.data = [COOKIE1, COOKIE2] jar.parse_cookies() config_stub.val.content.cookies.store = store_cookies if empty: assert not jar._lineparser.data assert not jar._lineparser.saved else: assert jar._lineparser.data
kmarius/qutebrowser
tests/unit/browser/webkit/test_cookies.py
qutebrowser/browser/webkit/http.py
# -*- coding: utf-8 -*- """ flask.globals ~~~~~~~~~~~~~ Defines all the global objects that are proxies to the current active context. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ from functools import partial from werkzeug.local import LocalStack, LocalProxy _request_ctx_err_msg = '''\ Working outside of request context. This typically means that you attempted to use functionality that needed an active HTTP request. Consult the documentation on testing for information about how to avoid this problem.\ ''' _app_ctx_err_msg = '''\ Working outside of application context. This typically means that you attempted to use functionality that needed to interface with the current application object in a way. To solve this set up an application context with app.app_context(). See the documentation for more information.\ ''' def _lookup_req_object(name): top = _request_ctx_stack.top if top is None: raise RuntimeError(_request_ctx_err_msg) return getattr(top, name) def _lookup_app_object(name): top = _app_ctx_stack.top if top is None: raise RuntimeError(_app_ctx_err_msg) return getattr(top, name) def _find_app(): top = _app_ctx_stack.top if top is None: raise RuntimeError(_app_ctx_err_msg) return top.app # context locals _request_ctx_stack = LocalStack() _app_ctx_stack = LocalStack() current_app = LocalProxy(_find_app) request = LocalProxy(partial(_lookup_req_object, 'request')) session = LocalProxy(partial(_lookup_req_object, 'session')) g = LocalProxy(partial(_lookup_app_object, 'g'))
# -*- coding: utf-8 -*- """ tests.ext ~~~~~~~~~~~~~~~~~~~ Tests the extension import thing. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import sys import pytest try: from imp import reload as reload_module except ImportError: reload_module = reload from flask._compat import PY2 @pytest.fixture(autouse=True) def disable_extwarnings(request, recwarn): from flask.exthook import ExtDeprecationWarning def inner(): assert set(w.category for w in recwarn.list) \ <= set([ExtDeprecationWarning]) recwarn.clear() request.addfinalizer(inner) @pytest.fixture(autouse=True) def importhook_setup(monkeypatch, request): # we clear this out for various reasons. The most important one is # that a real flaskext could be in there which would disable our # fake package. Secondly we want to make sure that the flaskext # import hook does not break on reloading. for entry, value in list(sys.modules.items()): if ( entry.startswith('flask.ext.') or entry.startswith('flask_') or entry.startswith('flaskext.') or entry == 'flaskext' ) and value is not None: monkeypatch.delitem(sys.modules, entry) from flask import ext reload_module(ext) # reloading must not add more hooks import_hooks = 0 for item in sys.meta_path: cls = type(item) if cls.__module__ == 'flask.exthook' and \ cls.__name__ == 'ExtensionImporter': import_hooks += 1 assert import_hooks == 1 def teardown(): from flask import ext for key in ext.__dict__: assert '.' not in key request.addfinalizer(teardown) @pytest.fixture def newext_simple(modules_tmpdir): x = modules_tmpdir.join('flask_newext_simple.py') x.write('ext_id = "newext_simple"') @pytest.fixture def oldext_simple(modules_tmpdir): flaskext = modules_tmpdir.mkdir('flaskext') flaskext.join('__init__.py').write('\n') flaskext.join('oldext_simple.py').write('ext_id = "oldext_simple"') @pytest.fixture def newext_package(modules_tmpdir): pkg = modules_tmpdir.mkdir('flask_newext_package') pkg.join('__init__.py').write('ext_id = "newext_package"') pkg.join('submodule.py').write('def test_function():\n return 42\n') @pytest.fixture def oldext_package(modules_tmpdir): flaskext = modules_tmpdir.mkdir('flaskext') flaskext.join('__init__.py').write('\n') oldext = flaskext.mkdir('oldext_package') oldext.join('__init__.py').write('ext_id = "oldext_package"') oldext.join('submodule.py').write('def test_function():\n' ' return 42') @pytest.fixture def flaskext_broken(modules_tmpdir): ext = modules_tmpdir.mkdir('flask_broken') ext.join('b.py').write('\n') ext.join('__init__.py').write('import flask.ext.broken.b\n' 'import missing_module') def test_flaskext_new_simple_import_normal(newext_simple): from flask.ext.newext_simple import ext_id assert ext_id == 'newext_simple' def test_flaskext_new_simple_import_module(newext_simple): from flask.ext import newext_simple assert newext_simple.ext_id == 'newext_simple' assert newext_simple.__name__ == 'flask_newext_simple' def test_flaskext_new_package_import_normal(newext_package): from flask.ext.newext_package import ext_id assert ext_id == 'newext_package' def test_flaskext_new_package_import_module(newext_package): from flask.ext import newext_package assert newext_package.ext_id == 'newext_package' assert newext_package.__name__ == 'flask_newext_package' def test_flaskext_new_package_import_submodule_function(newext_package): from flask.ext.newext_package.submodule import test_function assert test_function() == 42 def test_flaskext_new_package_import_submodule(newext_package): from flask.ext.newext_package import submodule assert submodule.__name__ == 'flask_newext_package.submodule' assert submodule.test_function() == 42 def test_flaskext_old_simple_import_normal(oldext_simple): from flask.ext.oldext_simple import ext_id assert ext_id == 'oldext_simple' def test_flaskext_old_simple_import_module(oldext_simple): from flask.ext import oldext_simple assert oldext_simple.ext_id == 'oldext_simple' assert oldext_simple.__name__ == 'flaskext.oldext_simple' def test_flaskext_old_package_import_normal(oldext_package): from flask.ext.oldext_package import ext_id assert ext_id == 'oldext_package' def test_flaskext_old_package_import_module(oldext_package): from flask.ext import oldext_package assert oldext_package.ext_id == 'oldext_package' assert oldext_package.__name__ == 'flaskext.oldext_package' def test_flaskext_old_package_import_submodule(oldext_package): from flask.ext.oldext_package import submodule assert submodule.__name__ == 'flaskext.oldext_package.submodule' assert submodule.test_function() == 42 def test_flaskext_old_package_import_submodule_function(oldext_package): from flask.ext.oldext_package.submodule import test_function assert test_function() == 42 def test_flaskext_broken_package_no_module_caching(flaskext_broken): for x in range(2): with pytest.raises(ImportError): import flask.ext.broken def test_no_error_swallowing(flaskext_broken): with pytest.raises(ImportError) as excinfo: import flask.ext.broken # python3.6 raises a subclass of ImportError: 'ModuleNotFoundError' assert issubclass(excinfo.type, ImportError) if PY2: message = 'No module named missing_module' else: message = 'No module named \'missing_module\'' assert str(excinfo.value) == message assert excinfo.tb.tb_frame.f_globals is globals() # reraise() adds a second frame so we need to skip that one too. # On PY3 we even have another one :( next = excinfo.tb.tb_next.tb_next if not PY2: next = next.tb_next import os.path assert os.path.join('flask_broken', '__init__.py') in \ next.tb_frame.f_code.co_filename
auready/flask
tests/test_ext.py
flask/globals.py
from numpy.distutils.fcompiler import FCompiler compilers = ['HPUXFCompiler'] class HPUXFCompiler(FCompiler): compiler_type = 'hpux' description = 'HP Fortran 90 Compiler' version_pattern = r'HP F90 (?P<version>[^\s*,]*)' executables = { 'version_cmd' : ["f90", "+version"], 'compiler_f77' : ["f90"], 'compiler_fix' : ["f90"], 'compiler_f90' : ["f90"], 'linker_so' : ["ld", "-b"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } module_dir_switch = None #XXX: fix me module_include_switch = None #XXX: fix me pic_flags = ['+Z'] def get_flags(self): return self.pic_flags + ['+ppu', '+DD64'] def get_flags_opt(self): return ['-O3'] def get_libraries(self): return ['m'] def get_library_dirs(self): opt = ['/usr/lib/hpux64'] return opt def get_version(self, force=0, ok_status=[256, 0, 1]): # XXX status==256 may indicate 'unrecognized option' or # 'no input file'. So, version_cmd needs more work. return FCompiler.get_version(self, force, ok_status) if __name__ == '__main__': from distutils import log log.set_verbosity(10) from numpy.distutils import customized_fcompiler print(customized_fcompiler(compiler='hpux').get_version())
import inspect import sys import tempfile from io import StringIO from unittest import mock import numpy as np from numpy.testing import ( assert_, assert_equal, assert_raises, assert_raises_regex) from numpy.core.overrides import ( _get_implementing_args, array_function_dispatch, verify_matching_signatures, ARRAY_FUNCTION_ENABLED) from numpy.compat import pickle import pytest requires_array_function = pytest.mark.skipif( not ARRAY_FUNCTION_ENABLED, reason="__array_function__ dispatch not enabled.") def _return_not_implemented(self, *args, **kwargs): return NotImplemented # need to define this at the top level to test pickling @array_function_dispatch(lambda array: (array,)) def dispatched_one_arg(array): """Docstring.""" return 'original' @array_function_dispatch(lambda array1, array2: (array1, array2)) def dispatched_two_arg(array1, array2): """Docstring.""" return 'original' class TestGetImplementingArgs: def test_ndarray(self): array = np.array(1) args = _get_implementing_args([array]) assert_equal(list(args), [array]) args = _get_implementing_args([array, array]) assert_equal(list(args), [array]) args = _get_implementing_args([array, 1]) assert_equal(list(args), [array]) args = _get_implementing_args([1, array]) assert_equal(list(args), [array]) def test_ndarray_subclasses(self): class OverrideSub(np.ndarray): __array_function__ = _return_not_implemented class NoOverrideSub(np.ndarray): pass array = np.array(1).view(np.ndarray) override_sub = np.array(1).view(OverrideSub) no_override_sub = np.array(1).view(NoOverrideSub) args = _get_implementing_args([array, override_sub]) assert_equal(list(args), [override_sub, array]) args = _get_implementing_args([array, no_override_sub]) assert_equal(list(args), [no_override_sub, array]) args = _get_implementing_args( [override_sub, no_override_sub]) assert_equal(list(args), [override_sub, no_override_sub]) def test_ndarray_and_duck_array(self): class Other: __array_function__ = _return_not_implemented array = np.array(1) other = Other() args = _get_implementing_args([other, array]) assert_equal(list(args), [other, array]) args = _get_implementing_args([array, other]) assert_equal(list(args), [array, other]) def test_ndarray_subclass_and_duck_array(self): class OverrideSub(np.ndarray): __array_function__ = _return_not_implemented class Other: __array_function__ = _return_not_implemented array = np.array(1) subarray = np.array(1).view(OverrideSub) other = Other() assert_equal(_get_implementing_args([array, subarray, other]), [subarray, array, other]) assert_equal(_get_implementing_args([array, other, subarray]), [subarray, array, other]) def test_many_duck_arrays(self): class A: __array_function__ = _return_not_implemented class B(A): __array_function__ = _return_not_implemented class C(A): __array_function__ = _return_not_implemented class D: __array_function__ = _return_not_implemented a = A() b = B() c = C() d = D() assert_equal(_get_implementing_args([1]), []) assert_equal(_get_implementing_args([a]), [a]) assert_equal(_get_implementing_args([a, 1]), [a]) assert_equal(_get_implementing_args([a, a, a]), [a]) assert_equal(_get_implementing_args([a, d, a]), [a, d]) assert_equal(_get_implementing_args([a, b]), [b, a]) assert_equal(_get_implementing_args([b, a]), [b, a]) assert_equal(_get_implementing_args([a, b, c]), [b, c, a]) assert_equal(_get_implementing_args([a, c, b]), [c, b, a]) def test_too_many_duck_arrays(self): namespace = dict(__array_function__=_return_not_implemented) types = [type('A' + str(i), (object,), namespace) for i in range(33)] relevant_args = [t() for t in types] actual = _get_implementing_args(relevant_args[:32]) assert_equal(actual, relevant_args[:32]) with assert_raises_regex(TypeError, 'distinct argument types'): _get_implementing_args(relevant_args) class TestNDArrayArrayFunction: @requires_array_function def test_method(self): class Other: __array_function__ = _return_not_implemented class NoOverrideSub(np.ndarray): pass class OverrideSub(np.ndarray): __array_function__ = _return_not_implemented array = np.array([1]) other = Other() no_override_sub = array.view(NoOverrideSub) override_sub = array.view(OverrideSub) result = array.__array_function__(func=dispatched_two_arg, types=(np.ndarray,), args=(array, 1.), kwargs={}) assert_equal(result, 'original') result = array.__array_function__(func=dispatched_two_arg, types=(np.ndarray, Other), args=(array, other), kwargs={}) assert_(result is NotImplemented) result = array.__array_function__(func=dispatched_two_arg, types=(np.ndarray, NoOverrideSub), args=(array, no_override_sub), kwargs={}) assert_equal(result, 'original') result = array.__array_function__(func=dispatched_two_arg, types=(np.ndarray, OverrideSub), args=(array, override_sub), kwargs={}) assert_equal(result, 'original') with assert_raises_regex(TypeError, 'no implementation found'): np.concatenate((array, other)) expected = np.concatenate((array, array)) result = np.concatenate((array, no_override_sub)) assert_equal(result, expected.view(NoOverrideSub)) result = np.concatenate((array, override_sub)) assert_equal(result, expected.view(OverrideSub)) def test_no_wrapper(self): # This shouldn't happen unless a user intentionally calls # __array_function__ with invalid arguments, but check that we raise # an appropriate error all the same. array = np.array(1) func = lambda x: x with assert_raises_regex(AttributeError, '_implementation'): array.__array_function__(func=func, types=(np.ndarray,), args=(array,), kwargs={}) @requires_array_function class TestArrayFunctionDispatch: def test_pickle(self): for proto in range(2, pickle.HIGHEST_PROTOCOL + 1): roundtripped = pickle.loads( pickle.dumps(dispatched_one_arg, protocol=proto)) assert_(roundtripped is dispatched_one_arg) def test_name_and_docstring(self): assert_equal(dispatched_one_arg.__name__, 'dispatched_one_arg') if sys.flags.optimize < 2: assert_equal(dispatched_one_arg.__doc__, 'Docstring.') def test_interface(self): class MyArray: def __array_function__(self, func, types, args, kwargs): return (self, func, types, args, kwargs) original = MyArray() (obj, func, types, args, kwargs) = dispatched_one_arg(original) assert_(obj is original) assert_(func is dispatched_one_arg) assert_equal(set(types), {MyArray}) # assert_equal uses the overloaded np.iscomplexobj() internally assert_(args == (original,)) assert_equal(kwargs, {}) def test_not_implemented(self): class MyArray: def __array_function__(self, func, types, args, kwargs): return NotImplemented array = MyArray() with assert_raises_regex(TypeError, 'no implementation found'): dispatched_one_arg(array) @requires_array_function class TestVerifyMatchingSignatures: def test_verify_matching_signatures(self): verify_matching_signatures(lambda x: 0, lambda x: 0) verify_matching_signatures(lambda x=None: 0, lambda x=None: 0) verify_matching_signatures(lambda x=1: 0, lambda x=None: 0) with assert_raises(RuntimeError): verify_matching_signatures(lambda a: 0, lambda b: 0) with assert_raises(RuntimeError): verify_matching_signatures(lambda x: 0, lambda x=None: 0) with assert_raises(RuntimeError): verify_matching_signatures(lambda x=None: 0, lambda y=None: 0) with assert_raises(RuntimeError): verify_matching_signatures(lambda x=1: 0, lambda y=1: 0) def test_array_function_dispatch(self): with assert_raises(RuntimeError): @array_function_dispatch(lambda x: (x,)) def f(y): pass # should not raise @array_function_dispatch(lambda x: (x,), verify=False) def f(y): pass def _new_duck_type_and_implements(): """Create a duck array type and implements functions.""" HANDLED_FUNCTIONS = {} class MyArray: def __array_function__(self, func, types, args, kwargs): if func not in HANDLED_FUNCTIONS: return NotImplemented if not all(issubclass(t, MyArray) for t in types): return NotImplemented return HANDLED_FUNCTIONS[func](*args, **kwargs) def implements(numpy_function): """Register an __array_function__ implementations.""" def decorator(func): HANDLED_FUNCTIONS[numpy_function] = func return func return decorator return (MyArray, implements) @requires_array_function class TestArrayFunctionImplementation: def test_one_arg(self): MyArray, implements = _new_duck_type_and_implements() @implements(dispatched_one_arg) def _(array): return 'myarray' assert_equal(dispatched_one_arg(1), 'original') assert_equal(dispatched_one_arg(MyArray()), 'myarray') def test_optional_args(self): MyArray, implements = _new_duck_type_and_implements() @array_function_dispatch(lambda array, option=None: (array,)) def func_with_option(array, option='default'): return option @implements(func_with_option) def my_array_func_with_option(array, new_option='myarray'): return new_option # we don't need to implement every option on __array_function__ # implementations assert_equal(func_with_option(1), 'default') assert_equal(func_with_option(1, option='extra'), 'extra') assert_equal(func_with_option(MyArray()), 'myarray') with assert_raises(TypeError): func_with_option(MyArray(), option='extra') # but new options on implementations can't be used result = my_array_func_with_option(MyArray(), new_option='yes') assert_equal(result, 'yes') with assert_raises(TypeError): func_with_option(MyArray(), new_option='no') def test_not_implemented(self): MyArray, implements = _new_duck_type_and_implements() @array_function_dispatch(lambda array: (array,), module='my') def func(array): return array array = np.array(1) assert_(func(array) is array) assert_equal(func.__module__, 'my') with assert_raises_regex( TypeError, "no implementation found for 'my.func'"): func(MyArray()) class TestNDArrayMethods: def test_repr(self): # gh-12162: should still be defined even if __array_function__ doesn't # implement np.array_repr() class MyArray(np.ndarray): def __array_function__(*args, **kwargs): return NotImplemented array = np.array(1).view(MyArray) assert_equal(repr(array), 'MyArray(1)') assert_equal(str(array), '1') class TestNumPyFunctions: def test_set_module(self): assert_equal(np.sum.__module__, 'numpy') assert_equal(np.char.equal.__module__, 'numpy.char') assert_equal(np.fft.fft.__module__, 'numpy.fft') assert_equal(np.linalg.solve.__module__, 'numpy.linalg') def test_inspect_sum(self): signature = inspect.signature(np.sum) assert_('axis' in signature.parameters) @requires_array_function def test_override_sum(self): MyArray, implements = _new_duck_type_and_implements() @implements(np.sum) def _(array): return 'yes' assert_equal(np.sum(MyArray()), 'yes') @requires_array_function def test_sum_on_mock_array(self): # We need a proxy for mocks because __array_function__ is only looked # up in the class dict class ArrayProxy: def __init__(self, value): self.value = value def __array_function__(self, *args, **kwargs): return self.value.__array_function__(*args, **kwargs) def __array__(self, *args, **kwargs): return self.value.__array__(*args, **kwargs) proxy = ArrayProxy(mock.Mock(spec=ArrayProxy)) proxy.value.__array_function__.return_value = 1 result = np.sum(proxy) assert_equal(result, 1) proxy.value.__array_function__.assert_called_once_with( np.sum, (ArrayProxy,), (proxy,), {}) proxy.value.__array__.assert_not_called() @requires_array_function def test_sum_forwarding_implementation(self): class MyArray(np.ndarray): def sum(self, axis, out): return 'summed' def __array_function__(self, func, types, args, kwargs): return super().__array_function__(func, types, args, kwargs) # note: the internal implementation of np.sum() calls the .sum() method array = np.array(1).view(MyArray) assert_equal(np.sum(array), 'summed') class TestArrayLike: def setup(self): class MyArray(): def __init__(self, function=None): self.function = function def __array_function__(self, func, types, args, kwargs): try: my_func = getattr(self, func.__name__) except AttributeError: return NotImplemented return my_func(*args, **kwargs) self.MyArray = MyArray class MyNoArrayFunctionArray(): def __init__(self, function=None): self.function = function self.MyNoArrayFunctionArray = MyNoArrayFunctionArray def add_method(self, name, arr_class, enable_value_error=False): def _definition(*args, **kwargs): # Check that `like=` isn't propagated downstream assert 'like' not in kwargs if enable_value_error and 'value_error' in kwargs: raise ValueError return arr_class(getattr(arr_class, name)) setattr(arr_class, name, _definition) def func_args(*args, **kwargs): return args, kwargs @requires_array_function def test_array_like_not_implemented(self): self.add_method('array', self.MyArray) ref = self.MyArray.array() with assert_raises_regex(TypeError, 'no implementation found'): array_like = np.asarray(1, like=ref) _array_tests = [ ('array', *func_args((1,))), ('asarray', *func_args((1,))), ('asanyarray', *func_args((1,))), ('ascontiguousarray', *func_args((2, 3))), ('asfortranarray', *func_args((2, 3))), ('require', *func_args((np.arange(6).reshape(2, 3),), requirements=['A', 'F'])), ('empty', *func_args((1,))), ('full', *func_args((1,), 2)), ('ones', *func_args((1,))), ('zeros', *func_args((1,))), ('arange', *func_args(3)), ('frombuffer', *func_args(b'\x00' * 8, dtype=int)), ('fromiter', *func_args(range(3), dtype=int)), ('fromstring', *func_args('1,2', dtype=int, sep=',')), ('loadtxt', *func_args(lambda: StringIO('0 1\n2 3'))), ('genfromtxt', *func_args(lambda: StringIO(u'1,2.1'), dtype=[('int', 'i8'), ('float', 'f8')], delimiter=',')), ] @pytest.mark.parametrize('function, args, kwargs', _array_tests) @pytest.mark.parametrize('numpy_ref', [True, False]) @requires_array_function def test_array_like(self, function, args, kwargs, numpy_ref): self.add_method('array', self.MyArray) self.add_method(function, self.MyArray) np_func = getattr(np, function) my_func = getattr(self.MyArray, function) if numpy_ref is True: ref = np.array(1) else: ref = self.MyArray.array() like_args = tuple(a() if callable(a) else a for a in args) array_like = np_func(*like_args, **kwargs, like=ref) if numpy_ref is True: assert type(array_like) is np.ndarray np_args = tuple(a() if callable(a) else a for a in args) np_arr = np_func(*np_args, **kwargs) # Special-case np.empty to ensure values match if function == "empty": np_arr.fill(1) array_like.fill(1) assert_equal(array_like, np_arr) else: assert type(array_like) is self.MyArray assert array_like.function is my_func @pytest.mark.parametrize('function, args, kwargs', _array_tests) @pytest.mark.parametrize('ref', [1, [1], "MyNoArrayFunctionArray"]) @requires_array_function def test_no_array_function_like(self, function, args, kwargs, ref): self.add_method('array', self.MyNoArrayFunctionArray) self.add_method(function, self.MyNoArrayFunctionArray) np_func = getattr(np, function) # Instantiate ref if it's the MyNoArrayFunctionArray class if ref == "MyNoArrayFunctionArray": ref = self.MyNoArrayFunctionArray.array() like_args = tuple(a() if callable(a) else a for a in args) with assert_raises_regex(TypeError, 'The `like` argument must be an array-like that implements'): np_func(*like_args, **kwargs, like=ref) @pytest.mark.parametrize('numpy_ref', [True, False]) def test_array_like_fromfile(self, numpy_ref): self.add_method('array', self.MyArray) self.add_method("fromfile", self.MyArray) if numpy_ref is True: ref = np.array(1) else: ref = self.MyArray.array() data = np.random.random(5) fname = tempfile.mkstemp()[1] data.tofile(fname) array_like = np.fromfile(fname, like=ref) if numpy_ref is True: assert type(array_like) is np.ndarray np_res = np.fromfile(fname, like=ref) assert_equal(np_res, data) assert_equal(array_like, np_res) else: assert type(array_like) is self.MyArray assert array_like.function is self.MyArray.fromfile @requires_array_function def test_exception_handling(self): self.add_method('array', self.MyArray, enable_value_error=True) ref = self.MyArray.array() with assert_raises(ValueError): np.array(1, value_error=True, like=ref)
madphysicist/numpy
numpy/core/tests/test_overrides.py
numpy/distutils/fcompiler/hpux.py
"""Config flow to configure IPMA component.""" import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_MODE, CONF_NAME import homeassistant.helpers.config_validation as cv from .const import DOMAIN, HOME_LOCATION_NAME from .weather import FORECAST_MODE @config_entries.HANDLERS.register(DOMAIN) class IpmaFlowHandler(config_entries.ConfigFlow): """Config flow for IPMA component.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL def __init__(self): """Init IpmaFlowHandler.""" self._errors = {} async def async_step_user(self, user_input=None): """Handle a flow initialized by the user.""" self._errors = {} if user_input is not None: if user_input[CONF_NAME] not in self.hass.config_entries.async_entries( DOMAIN ): return self.async_create_entry( title=user_input[CONF_NAME], data=user_input ) self._errors[CONF_NAME] = "name_exists" # default location is set hass configuration return await self._show_config_form( name=HOME_LOCATION_NAME, latitude=self.hass.config.latitude, longitude=self.hass.config.longitude, ) async def _show_config_form(self, name=None, latitude=None, longitude=None): """Show the configuration form to edit location data.""" return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Required(CONF_NAME, default=name): str, vol.Required(CONF_LATITUDE, default=latitude): cv.latitude, vol.Required(CONF_LONGITUDE, default=longitude): cv.longitude, vol.Required(CONF_MODE, default="daily"): vol.In(FORECAST_MODE), } ), errors=self._errors, )
"""Define tests for the PlayStation 4 config flow.""" from pyps4_2ndscreen.errors import CredentialTimeout import pytest from homeassistant import data_entry_flow from homeassistant.components import ps4 from homeassistant.components.ps4.const import ( DEFAULT_ALIAS, DEFAULT_NAME, DEFAULT_REGION, DOMAIN, ) from homeassistant.const import ( CONF_CODE, CONF_HOST, CONF_IP_ADDRESS, CONF_NAME, CONF_REGION, CONF_TOKEN, ) from homeassistant.util import location from tests.async_mock import patch from tests.common import MockConfigEntry MOCK_TITLE = "PlayStation 4" MOCK_CODE = 12345678 MOCK_CODE_LEAD_0 = 1234567 MOCK_CODE_LEAD_0_STR = "01234567" MOCK_CREDS = "000aa000" MOCK_HOST = "192.0.0.0" MOCK_HOST_ADDITIONAL = "192.0.0.1" MOCK_DEVICE = { CONF_HOST: MOCK_HOST, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, } MOCK_DEVICE_ADDITIONAL = { CONF_HOST: MOCK_HOST_ADDITIONAL, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, } MOCK_CONFIG = { CONF_IP_ADDRESS: MOCK_HOST, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, CONF_CODE: MOCK_CODE, } MOCK_CONFIG_ADDITIONAL = { CONF_IP_ADDRESS: MOCK_HOST_ADDITIONAL, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, CONF_CODE: MOCK_CODE, } MOCK_DATA = {CONF_TOKEN: MOCK_CREDS, "devices": [MOCK_DEVICE]} MOCK_UDP_PORT = int(987) MOCK_TCP_PORT = int(997) MOCK_AUTO = {"Config Mode": "Auto Discover"} MOCK_MANUAL = {"Config Mode": "Manual Entry", CONF_IP_ADDRESS: MOCK_HOST} MOCK_LOCATION = location.LocationInfo( "0.0.0.0", "US", "United States", "CA", "California", "San Diego", "92122", "America/Los_Angeles", 32.8594, -117.2073, True, ) @pytest.fixture(name="location_info", autouse=True) def location_info_fixture(): """Mock location info.""" with patch( "homeassistant.components.ps4.config_flow.location.async_detect_location_info", return_value=MOCK_LOCATION, ): yield @pytest.fixture(name="ps4_setup", autouse=True) def ps4_setup_fixture(): """Patch ps4 setup entry.""" with patch( "homeassistant.components.ps4.async_setup_entry", return_value=True, ): yield async def test_full_flow_implementation(hass): """Test registering an implementation and flow works.""" # User Step Started, results in Step Creds with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # User Input results in created entry. with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert result["data"]["devices"] == [MOCK_DEVICE] assert result["title"] == MOCK_TITLE async def test_multiple_flow_implementation(hass): """Test multiple device flows.""" # User Step Started, results in Step Creds with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # User Input results in created entry. with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert result["data"]["devices"] == [MOCK_DEVICE] assert result["title"] == MOCK_TITLE # Check if entry exists. entries = hass.config_entries.async_entries() assert len(entries) == 1 # Check if there is a device config in entry. entry_1 = entries[0] assert len(entry_1.data["devices"]) == 1 # Test additional flow. # User Step Started, results in Step Mode: with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # Step Link with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ), patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert len(result["data"]["devices"]) == 1 assert result["title"] == MOCK_TITLE # Check if there are 2 entries. entries = hass.config_entries.async_entries() assert len(entries) == 2 # Check if there is device config in the last entry. entry_2 = entries[-1] assert len(entry_2.data["devices"]) == 1 # Check that entry 1 is different from entry 2. assert entry_1 is not entry_2 async def test_port_bind_abort(hass): """Test that flow aborted when cannot bind to ports 987, 997.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_UDP_PORT): reason = "port_987_bind_error" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == reason with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_TCP_PORT): reason = "port_997_bind_error" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == reason async def test_duplicate_abort(hass): """Test that Flow aborts when found devices already configured.""" MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA).add_to_hass(hass) with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_additional_device(hass): """Test that Flow can configure another device.""" # Mock existing entry. entry = MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA) entry.add_to_hass(hass) with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert len(result["data"]["devices"]) == 1 assert result["title"] == MOCK_TITLE async def test_0_pin(hass): """Test Pin with leading '0' is passed correctly.""" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "creds"}, data={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ), patch( "homeassistant.components.ps4.config_flow.location.async_detect_location_info", return_value=MOCK_LOCATION, ): result = await hass.config_entries.flow.async_configure( result["flow_id"], MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" mock_config = MOCK_CONFIG mock_config[CONF_CODE] = MOCK_CODE_LEAD_0 with patch( "pyps4_2ndscreen.Helper.link", return_value=(True, True) ) as mock_call, patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], mock_config ) mock_call.assert_called_once_with( MOCK_HOST, MOCK_CREDS, MOCK_CODE_LEAD_0_STR, DEFAULT_ALIAS ) async def test_no_devices_found_abort(hass): """Test that failure to find devices aborts flow.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch("pyps4_2ndscreen.Helper.has_devices", return_value=[]): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "no_devices_found" async def test_manual_mode(hass): """Test host specified in manual mode is passed to Step Link.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input: manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_MANUAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" async def test_credential_abort(hass): """Test that failure to get credentials aborts flow.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=None): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "credential_error" async def test_credential_timeout(hass): """Test that Credential Timeout shows error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", side_effect=CredentialTimeout): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" assert result["errors"] == {"base": "credential_timeout"} async def test_wrong_pin_error(hass): """Test that incorrect pin throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(True, False)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" assert result["errors"] == {"base": "login_failed"} async def test_device_connection_error(hass): """Test that device not connected or on throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(False, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" assert result["errors"] == {"base": "cannot_connect"} async def test_manual_mode_no_ip_error(hass): """Test no IP specified in manual mode throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={"Config Mode": "Manual Entry"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" assert result["errors"] == {CONF_IP_ADDRESS: "no_ipaddress"}
sdague/home-assistant
tests/components/ps4/test_config_flow.py
homeassistant/components/ipma/config_flow.py
"""Support for the MAX! Cube LAN Gateway.""" import logging from socket import timeout from threading import Lock import time from maxcube.connection import MaxCubeConnection from maxcube.cube import MaxCube import voluptuous as vol from homeassistant.const import CONF_HOST, CONF_PORT, CONF_SCAN_INTERVAL import homeassistant.helpers.config_validation as cv from homeassistant.helpers.discovery import load_platform _LOGGER = logging.getLogger(__name__) DEFAULT_PORT = 62910 DOMAIN = "maxcube" DATA_KEY = "maxcube" NOTIFICATION_ID = "maxcube_notification" NOTIFICATION_TITLE = "Max!Cube gateway setup" CONF_GATEWAYS = "gateways" CONFIG_GATEWAY = vol.Schema( { vol.Required(CONF_HOST): cv.string, vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_SCAN_INTERVAL, default=300): cv.time_period, } ) CONFIG_SCHEMA = vol.Schema( { DOMAIN: vol.Schema( { vol.Required(CONF_GATEWAYS, default={}): vol.All( cv.ensure_list, [CONFIG_GATEWAY] ) } ) }, extra=vol.ALLOW_EXTRA, ) def setup(hass, config): """Establish connection to MAX! Cube.""" if DATA_KEY not in hass.data: hass.data[DATA_KEY] = {} connection_failed = 0 gateways = config[DOMAIN][CONF_GATEWAYS] for gateway in gateways: host = gateway[CONF_HOST] port = gateway[CONF_PORT] scan_interval = gateway[CONF_SCAN_INTERVAL].total_seconds() try: cube = MaxCube(MaxCubeConnection(host, port)) hass.data[DATA_KEY][host] = MaxCubeHandle(cube, scan_interval) except timeout as ex: _LOGGER.error("Unable to connect to Max!Cube gateway: %s", str(ex)) hass.components.persistent_notification.create( f"Error: {ex}<br />You will need to restart Home Assistant after fixing.", title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID, ) connection_failed += 1 if connection_failed >= len(gateways): return False load_platform(hass, "climate", DOMAIN, {}, config) load_platform(hass, "binary_sensor", DOMAIN, {}, config) return True class MaxCubeHandle: """Keep the cube instance in one place and centralize the update.""" def __init__(self, cube, scan_interval): """Initialize the Cube Handle.""" self.cube = cube self.scan_interval = scan_interval self.mutex = Lock() self._updatets = time.monotonic() def update(self): """Pull the latest data from the MAX! Cube.""" # Acquire mutex to prevent simultaneous update from multiple threads with self.mutex: # Only update every update_interval if (time.monotonic() - self._updatets) >= self.scan_interval: _LOGGER.debug("Updating") try: self.cube.update() except timeout: _LOGGER.error("Max!Cube connection failed") return False self._updatets = time.monotonic() else: _LOGGER.debug("Skipping update")
"""Define tests for the PlayStation 4 config flow.""" from pyps4_2ndscreen.errors import CredentialTimeout import pytest from homeassistant import data_entry_flow from homeassistant.components import ps4 from homeassistant.components.ps4.const import ( DEFAULT_ALIAS, DEFAULT_NAME, DEFAULT_REGION, DOMAIN, ) from homeassistant.const import ( CONF_CODE, CONF_HOST, CONF_IP_ADDRESS, CONF_NAME, CONF_REGION, CONF_TOKEN, ) from homeassistant.util import location from tests.async_mock import patch from tests.common import MockConfigEntry MOCK_TITLE = "PlayStation 4" MOCK_CODE = 12345678 MOCK_CODE_LEAD_0 = 1234567 MOCK_CODE_LEAD_0_STR = "01234567" MOCK_CREDS = "000aa000" MOCK_HOST = "192.0.0.0" MOCK_HOST_ADDITIONAL = "192.0.0.1" MOCK_DEVICE = { CONF_HOST: MOCK_HOST, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, } MOCK_DEVICE_ADDITIONAL = { CONF_HOST: MOCK_HOST_ADDITIONAL, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, } MOCK_CONFIG = { CONF_IP_ADDRESS: MOCK_HOST, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, CONF_CODE: MOCK_CODE, } MOCK_CONFIG_ADDITIONAL = { CONF_IP_ADDRESS: MOCK_HOST_ADDITIONAL, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, CONF_CODE: MOCK_CODE, } MOCK_DATA = {CONF_TOKEN: MOCK_CREDS, "devices": [MOCK_DEVICE]} MOCK_UDP_PORT = int(987) MOCK_TCP_PORT = int(997) MOCK_AUTO = {"Config Mode": "Auto Discover"} MOCK_MANUAL = {"Config Mode": "Manual Entry", CONF_IP_ADDRESS: MOCK_HOST} MOCK_LOCATION = location.LocationInfo( "0.0.0.0", "US", "United States", "CA", "California", "San Diego", "92122", "America/Los_Angeles", 32.8594, -117.2073, True, ) @pytest.fixture(name="location_info", autouse=True) def location_info_fixture(): """Mock location info.""" with patch( "homeassistant.components.ps4.config_flow.location.async_detect_location_info", return_value=MOCK_LOCATION, ): yield @pytest.fixture(name="ps4_setup", autouse=True) def ps4_setup_fixture(): """Patch ps4 setup entry.""" with patch( "homeassistant.components.ps4.async_setup_entry", return_value=True, ): yield async def test_full_flow_implementation(hass): """Test registering an implementation and flow works.""" # User Step Started, results in Step Creds with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # User Input results in created entry. with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert result["data"]["devices"] == [MOCK_DEVICE] assert result["title"] == MOCK_TITLE async def test_multiple_flow_implementation(hass): """Test multiple device flows.""" # User Step Started, results in Step Creds with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # User Input results in created entry. with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert result["data"]["devices"] == [MOCK_DEVICE] assert result["title"] == MOCK_TITLE # Check if entry exists. entries = hass.config_entries.async_entries() assert len(entries) == 1 # Check if there is a device config in entry. entry_1 = entries[0] assert len(entry_1.data["devices"]) == 1 # Test additional flow. # User Step Started, results in Step Mode: with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # Step Link with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ), patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert len(result["data"]["devices"]) == 1 assert result["title"] == MOCK_TITLE # Check if there are 2 entries. entries = hass.config_entries.async_entries() assert len(entries) == 2 # Check if there is device config in the last entry. entry_2 = entries[-1] assert len(entry_2.data["devices"]) == 1 # Check that entry 1 is different from entry 2. assert entry_1 is not entry_2 async def test_port_bind_abort(hass): """Test that flow aborted when cannot bind to ports 987, 997.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_UDP_PORT): reason = "port_987_bind_error" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == reason with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_TCP_PORT): reason = "port_997_bind_error" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == reason async def test_duplicate_abort(hass): """Test that Flow aborts when found devices already configured.""" MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA).add_to_hass(hass) with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_additional_device(hass): """Test that Flow can configure another device.""" # Mock existing entry. entry = MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA) entry.add_to_hass(hass) with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert len(result["data"]["devices"]) == 1 assert result["title"] == MOCK_TITLE async def test_0_pin(hass): """Test Pin with leading '0' is passed correctly.""" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "creds"}, data={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ), patch( "homeassistant.components.ps4.config_flow.location.async_detect_location_info", return_value=MOCK_LOCATION, ): result = await hass.config_entries.flow.async_configure( result["flow_id"], MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" mock_config = MOCK_CONFIG mock_config[CONF_CODE] = MOCK_CODE_LEAD_0 with patch( "pyps4_2ndscreen.Helper.link", return_value=(True, True) ) as mock_call, patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], mock_config ) mock_call.assert_called_once_with( MOCK_HOST, MOCK_CREDS, MOCK_CODE_LEAD_0_STR, DEFAULT_ALIAS ) async def test_no_devices_found_abort(hass): """Test that failure to find devices aborts flow.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch("pyps4_2ndscreen.Helper.has_devices", return_value=[]): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "no_devices_found" async def test_manual_mode(hass): """Test host specified in manual mode is passed to Step Link.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input: manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_MANUAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" async def test_credential_abort(hass): """Test that failure to get credentials aborts flow.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=None): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "credential_error" async def test_credential_timeout(hass): """Test that Credential Timeout shows error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", side_effect=CredentialTimeout): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" assert result["errors"] == {"base": "credential_timeout"} async def test_wrong_pin_error(hass): """Test that incorrect pin throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(True, False)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" assert result["errors"] == {"base": "login_failed"} async def test_device_connection_error(hass): """Test that device not connected or on throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(False, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" assert result["errors"] == {"base": "cannot_connect"} async def test_manual_mode_no_ip_error(hass): """Test no IP specified in manual mode throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={"Config Mode": "Manual Entry"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" assert result["errors"] == {CONF_IP_ADDRESS: "no_ipaddress"}
sdague/home-assistant
tests/components/ps4/test_config_flow.py
homeassistant/components/maxcube/__init__.py
"""Define a config flow manager for flunearyou.""" from pyflunearyou import Client from pyflunearyou.errors import FluNearYouError import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE from homeassistant.helpers import aiohttp_client, config_validation as cv from .const import DOMAIN, LOGGER # pylint: disable=unused-import class FluNearYouFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Handle an FluNearYou config flow.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL @property def data_schema(self): """Return the data schema for integration.""" return vol.Schema( { 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_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=self.data_schema) unique_id = f"{user_input[CONF_LATITUDE]}, {user_input[CONF_LONGITUDE]}" await self.async_set_unique_id(unique_id) self._abort_if_unique_id_configured() websession = aiohttp_client.async_get_clientsession(self.hass) client = Client(websession) try: await client.cdc_reports.status_by_coordinates( user_input[CONF_LATITUDE], user_input[CONF_LONGITUDE] ) except FluNearYouError as err: LOGGER.error("Error while configuring integration: %s", err) return self.async_show_form(step_id="user", errors={"base": "unknown"}) return self.async_create_entry(title=unique_id, data=user_input)
"""Define tests for the PlayStation 4 config flow.""" from pyps4_2ndscreen.errors import CredentialTimeout import pytest from homeassistant import data_entry_flow from homeassistant.components import ps4 from homeassistant.components.ps4.const import ( DEFAULT_ALIAS, DEFAULT_NAME, DEFAULT_REGION, DOMAIN, ) from homeassistant.const import ( CONF_CODE, CONF_HOST, CONF_IP_ADDRESS, CONF_NAME, CONF_REGION, CONF_TOKEN, ) from homeassistant.util import location from tests.async_mock import patch from tests.common import MockConfigEntry MOCK_TITLE = "PlayStation 4" MOCK_CODE = 12345678 MOCK_CODE_LEAD_0 = 1234567 MOCK_CODE_LEAD_0_STR = "01234567" MOCK_CREDS = "000aa000" MOCK_HOST = "192.0.0.0" MOCK_HOST_ADDITIONAL = "192.0.0.1" MOCK_DEVICE = { CONF_HOST: MOCK_HOST, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, } MOCK_DEVICE_ADDITIONAL = { CONF_HOST: MOCK_HOST_ADDITIONAL, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, } MOCK_CONFIG = { CONF_IP_ADDRESS: MOCK_HOST, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, CONF_CODE: MOCK_CODE, } MOCK_CONFIG_ADDITIONAL = { CONF_IP_ADDRESS: MOCK_HOST_ADDITIONAL, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, CONF_CODE: MOCK_CODE, } MOCK_DATA = {CONF_TOKEN: MOCK_CREDS, "devices": [MOCK_DEVICE]} MOCK_UDP_PORT = int(987) MOCK_TCP_PORT = int(997) MOCK_AUTO = {"Config Mode": "Auto Discover"} MOCK_MANUAL = {"Config Mode": "Manual Entry", CONF_IP_ADDRESS: MOCK_HOST} MOCK_LOCATION = location.LocationInfo( "0.0.0.0", "US", "United States", "CA", "California", "San Diego", "92122", "America/Los_Angeles", 32.8594, -117.2073, True, ) @pytest.fixture(name="location_info", autouse=True) def location_info_fixture(): """Mock location info.""" with patch( "homeassistant.components.ps4.config_flow.location.async_detect_location_info", return_value=MOCK_LOCATION, ): yield @pytest.fixture(name="ps4_setup", autouse=True) def ps4_setup_fixture(): """Patch ps4 setup entry.""" with patch( "homeassistant.components.ps4.async_setup_entry", return_value=True, ): yield async def test_full_flow_implementation(hass): """Test registering an implementation and flow works.""" # User Step Started, results in Step Creds with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # User Input results in created entry. with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert result["data"]["devices"] == [MOCK_DEVICE] assert result["title"] == MOCK_TITLE async def test_multiple_flow_implementation(hass): """Test multiple device flows.""" # User Step Started, results in Step Creds with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # User Input results in created entry. with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert result["data"]["devices"] == [MOCK_DEVICE] assert result["title"] == MOCK_TITLE # Check if entry exists. entries = hass.config_entries.async_entries() assert len(entries) == 1 # Check if there is a device config in entry. entry_1 = entries[0] assert len(entry_1.data["devices"]) == 1 # Test additional flow. # User Step Started, results in Step Mode: with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # Step Link with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ), patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert len(result["data"]["devices"]) == 1 assert result["title"] == MOCK_TITLE # Check if there are 2 entries. entries = hass.config_entries.async_entries() assert len(entries) == 2 # Check if there is device config in the last entry. entry_2 = entries[-1] assert len(entry_2.data["devices"]) == 1 # Check that entry 1 is different from entry 2. assert entry_1 is not entry_2 async def test_port_bind_abort(hass): """Test that flow aborted when cannot bind to ports 987, 997.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_UDP_PORT): reason = "port_987_bind_error" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == reason with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_TCP_PORT): reason = "port_997_bind_error" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == reason async def test_duplicate_abort(hass): """Test that Flow aborts when found devices already configured.""" MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA).add_to_hass(hass) with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_additional_device(hass): """Test that Flow can configure another device.""" # Mock existing entry. entry = MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA) entry.add_to_hass(hass) with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert len(result["data"]["devices"]) == 1 assert result["title"] == MOCK_TITLE async def test_0_pin(hass): """Test Pin with leading '0' is passed correctly.""" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "creds"}, data={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ), patch( "homeassistant.components.ps4.config_flow.location.async_detect_location_info", return_value=MOCK_LOCATION, ): result = await hass.config_entries.flow.async_configure( result["flow_id"], MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" mock_config = MOCK_CONFIG mock_config[CONF_CODE] = MOCK_CODE_LEAD_0 with patch( "pyps4_2ndscreen.Helper.link", return_value=(True, True) ) as mock_call, patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], mock_config ) mock_call.assert_called_once_with( MOCK_HOST, MOCK_CREDS, MOCK_CODE_LEAD_0_STR, DEFAULT_ALIAS ) async def test_no_devices_found_abort(hass): """Test that failure to find devices aborts flow.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch("pyps4_2ndscreen.Helper.has_devices", return_value=[]): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "no_devices_found" async def test_manual_mode(hass): """Test host specified in manual mode is passed to Step Link.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input: manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_MANUAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" async def test_credential_abort(hass): """Test that failure to get credentials aborts flow.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=None): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "credential_error" async def test_credential_timeout(hass): """Test that Credential Timeout shows error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", side_effect=CredentialTimeout): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" assert result["errors"] == {"base": "credential_timeout"} async def test_wrong_pin_error(hass): """Test that incorrect pin throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(True, False)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" assert result["errors"] == {"base": "login_failed"} async def test_device_connection_error(hass): """Test that device not connected or on throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(False, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" assert result["errors"] == {"base": "cannot_connect"} async def test_manual_mode_no_ip_error(hass): """Test no IP specified in manual mode throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={"Config Mode": "Manual Entry"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" assert result["errors"] == {CONF_IP_ADDRESS: "no_ipaddress"}
sdague/home-assistant
tests/components/ps4/test_config_flow.py
homeassistant/components/flunearyou/config_flow.py
"""Support for Google Maps location sharing.""" from datetime import timedelta import logging from locationsharinglib import Service from locationsharinglib.locationsharinglibexceptions import InvalidCookies import voluptuous as vol from homeassistant.components.device_tracker import PLATFORM_SCHEMA, SOURCE_TYPE_GPS from homeassistant.const import ( ATTR_BATTERY_CHARGING, ATTR_BATTERY_LEVEL, ATTR_ID, CONF_SCAN_INTERVAL, CONF_USERNAME, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.event import track_time_interval from homeassistant.helpers.typing import ConfigType from homeassistant.util import dt as dt_util, slugify _LOGGER = logging.getLogger(__name__) ATTR_ADDRESS = "address" ATTR_FULL_NAME = "full_name" ATTR_LAST_SEEN = "last_seen" ATTR_NICKNAME = "nickname" CONF_MAX_GPS_ACCURACY = "max_gps_accuracy" CREDENTIALS_FILE = ".google_maps_location_sharing.cookies" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_USERNAME): cv.string, vol.Optional(CONF_MAX_GPS_ACCURACY, default=100000): vol.Coerce(float), } ) def setup_scanner(hass, config: ConfigType, see, discovery_info=None): """Set up the Google Maps Location sharing scanner.""" scanner = GoogleMapsScanner(hass, config, see) return scanner.success_init class GoogleMapsScanner: """Representation of an Google Maps location sharing account.""" def __init__(self, hass, config: ConfigType, see) -> None: """Initialize the scanner.""" self.see = see self.username = config[CONF_USERNAME] self.max_gps_accuracy = config[CONF_MAX_GPS_ACCURACY] self.scan_interval = config.get(CONF_SCAN_INTERVAL) or timedelta(seconds=60) self._prev_seen = {} credfile = f"{hass.config.path(CREDENTIALS_FILE)}.{slugify(self.username)}" try: self.service = Service(credfile, self.username) self._update_info() track_time_interval(hass, self._update_info, self.scan_interval) self.success_init = True except InvalidCookies: _LOGGER.error( "The cookie file provided does not provide a valid session. Please create another one and try again" ) self.success_init = False def _update_info(self, now=None): for person in self.service.get_all_people(): try: dev_id = f"google_maps_{slugify(person.id)}" except TypeError: _LOGGER.warning("No location(s) shared with this account") return if ( self.max_gps_accuracy is not None and person.accuracy > self.max_gps_accuracy ): _LOGGER.info( "Ignoring %s update because expected GPS " "accuracy %s is not met: %s", person.nickname, self.max_gps_accuracy, person.accuracy, ) continue last_seen = dt_util.as_utc(person.datetime) if last_seen < self._prev_seen.get(dev_id, last_seen): _LOGGER.warning( "Ignoring %s update because timestamp " "is older than last timestamp", person.nickname, ) _LOGGER.debug("%s < %s", last_seen, self._prev_seen[dev_id]) continue self._prev_seen[dev_id] = last_seen attrs = { ATTR_ADDRESS: person.address, ATTR_FULL_NAME: person.full_name, ATTR_ID: person.id, ATTR_LAST_SEEN: last_seen, ATTR_NICKNAME: person.nickname, ATTR_BATTERY_CHARGING: person.charging, ATTR_BATTERY_LEVEL: person.battery_level, } self.see( dev_id=dev_id, gps=(person.latitude, person.longitude), picture=person.picture_url, source_type=SOURCE_TYPE_GPS, gps_accuracy=person.accuracy, attributes=attrs, )
"""Define tests for the PlayStation 4 config flow.""" from pyps4_2ndscreen.errors import CredentialTimeout import pytest from homeassistant import data_entry_flow from homeassistant.components import ps4 from homeassistant.components.ps4.const import ( DEFAULT_ALIAS, DEFAULT_NAME, DEFAULT_REGION, DOMAIN, ) from homeassistant.const import ( CONF_CODE, CONF_HOST, CONF_IP_ADDRESS, CONF_NAME, CONF_REGION, CONF_TOKEN, ) from homeassistant.util import location from tests.async_mock import patch from tests.common import MockConfigEntry MOCK_TITLE = "PlayStation 4" MOCK_CODE = 12345678 MOCK_CODE_LEAD_0 = 1234567 MOCK_CODE_LEAD_0_STR = "01234567" MOCK_CREDS = "000aa000" MOCK_HOST = "192.0.0.0" MOCK_HOST_ADDITIONAL = "192.0.0.1" MOCK_DEVICE = { CONF_HOST: MOCK_HOST, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, } MOCK_DEVICE_ADDITIONAL = { CONF_HOST: MOCK_HOST_ADDITIONAL, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, } MOCK_CONFIG = { CONF_IP_ADDRESS: MOCK_HOST, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, CONF_CODE: MOCK_CODE, } MOCK_CONFIG_ADDITIONAL = { CONF_IP_ADDRESS: MOCK_HOST_ADDITIONAL, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, CONF_CODE: MOCK_CODE, } MOCK_DATA = {CONF_TOKEN: MOCK_CREDS, "devices": [MOCK_DEVICE]} MOCK_UDP_PORT = int(987) MOCK_TCP_PORT = int(997) MOCK_AUTO = {"Config Mode": "Auto Discover"} MOCK_MANUAL = {"Config Mode": "Manual Entry", CONF_IP_ADDRESS: MOCK_HOST} MOCK_LOCATION = location.LocationInfo( "0.0.0.0", "US", "United States", "CA", "California", "San Diego", "92122", "America/Los_Angeles", 32.8594, -117.2073, True, ) @pytest.fixture(name="location_info", autouse=True) def location_info_fixture(): """Mock location info.""" with patch( "homeassistant.components.ps4.config_flow.location.async_detect_location_info", return_value=MOCK_LOCATION, ): yield @pytest.fixture(name="ps4_setup", autouse=True) def ps4_setup_fixture(): """Patch ps4 setup entry.""" with patch( "homeassistant.components.ps4.async_setup_entry", return_value=True, ): yield async def test_full_flow_implementation(hass): """Test registering an implementation and flow works.""" # User Step Started, results in Step Creds with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # User Input results in created entry. with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert result["data"]["devices"] == [MOCK_DEVICE] assert result["title"] == MOCK_TITLE async def test_multiple_flow_implementation(hass): """Test multiple device flows.""" # User Step Started, results in Step Creds with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # User Input results in created entry. with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert result["data"]["devices"] == [MOCK_DEVICE] assert result["title"] == MOCK_TITLE # Check if entry exists. entries = hass.config_entries.async_entries() assert len(entries) == 1 # Check if there is a device config in entry. entry_1 = entries[0] assert len(entry_1.data["devices"]) == 1 # Test additional flow. # User Step Started, results in Step Mode: with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # Step Link with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ), patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert len(result["data"]["devices"]) == 1 assert result["title"] == MOCK_TITLE # Check if there are 2 entries. entries = hass.config_entries.async_entries() assert len(entries) == 2 # Check if there is device config in the last entry. entry_2 = entries[-1] assert len(entry_2.data["devices"]) == 1 # Check that entry 1 is different from entry 2. assert entry_1 is not entry_2 async def test_port_bind_abort(hass): """Test that flow aborted when cannot bind to ports 987, 997.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_UDP_PORT): reason = "port_987_bind_error" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == reason with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_TCP_PORT): reason = "port_997_bind_error" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == reason async def test_duplicate_abort(hass): """Test that Flow aborts when found devices already configured.""" MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA).add_to_hass(hass) with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_additional_device(hass): """Test that Flow can configure another device.""" # Mock existing entry. entry = MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA) entry.add_to_hass(hass) with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert len(result["data"]["devices"]) == 1 assert result["title"] == MOCK_TITLE async def test_0_pin(hass): """Test Pin with leading '0' is passed correctly.""" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "creds"}, data={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ), patch( "homeassistant.components.ps4.config_flow.location.async_detect_location_info", return_value=MOCK_LOCATION, ): result = await hass.config_entries.flow.async_configure( result["flow_id"], MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" mock_config = MOCK_CONFIG mock_config[CONF_CODE] = MOCK_CODE_LEAD_0 with patch( "pyps4_2ndscreen.Helper.link", return_value=(True, True) ) as mock_call, patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], mock_config ) mock_call.assert_called_once_with( MOCK_HOST, MOCK_CREDS, MOCK_CODE_LEAD_0_STR, DEFAULT_ALIAS ) async def test_no_devices_found_abort(hass): """Test that failure to find devices aborts flow.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch("pyps4_2ndscreen.Helper.has_devices", return_value=[]): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "no_devices_found" async def test_manual_mode(hass): """Test host specified in manual mode is passed to Step Link.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input: manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_MANUAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" async def test_credential_abort(hass): """Test that failure to get credentials aborts flow.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=None): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "credential_error" async def test_credential_timeout(hass): """Test that Credential Timeout shows error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", side_effect=CredentialTimeout): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" assert result["errors"] == {"base": "credential_timeout"} async def test_wrong_pin_error(hass): """Test that incorrect pin throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(True, False)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" assert result["errors"] == {"base": "login_failed"} async def test_device_connection_error(hass): """Test that device not connected or on throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(False, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" assert result["errors"] == {"base": "cannot_connect"} async def test_manual_mode_no_ip_error(hass): """Test no IP specified in manual mode throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={"Config Mode": "Manual Entry"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" assert result["errors"] == {CONF_IP_ADDRESS: "no_ipaddress"}
sdague/home-assistant
tests/components/ps4/test_config_flow.py
homeassistant/components/google_maps/device_tracker.py
"""Support for De Lijn (Flemish public transport) information.""" import logging from pydelijn.api import Passages from pydelijn.common import HttpException import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ATTR_ATTRIBUTION, DEVICE_CLASS_TIMESTAMP from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) ATTRIBUTION = "Data provided by data.delijn.be" CONF_NEXT_DEPARTURE = "next_departure" CONF_STOP_ID = "stop_id" CONF_API_KEY = "api_key" CONF_NUMBER_OF_DEPARTURES = "number_of_departures" DEFAULT_NAME = "De Lijn" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_API_KEY): cv.string, vol.Required(CONF_NEXT_DEPARTURE): [ { vol.Required(CONF_STOP_ID): cv.string, vol.Optional(CONF_NUMBER_OF_DEPARTURES, default=5): cv.positive_int, } ], } ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Create the sensor.""" api_key = config[CONF_API_KEY] session = async_get_clientsession(hass) sensors = [] for nextpassage in config[CONF_NEXT_DEPARTURE]: sensors.append( DeLijnPublicTransportSensor( Passages( hass.loop, nextpassage[CONF_STOP_ID], nextpassage[CONF_NUMBER_OF_DEPARTURES], api_key, session, True, ) ) ) async_add_entities(sensors, True) class DeLijnPublicTransportSensor(Entity): """Representation of a Ruter sensor.""" def __init__(self, line): """Initialize the sensor.""" self.line = line self._attributes = {ATTR_ATTRIBUTION: ATTRIBUTION} self._name = None self._state = None self._available = True async def async_update(self): """Get the latest data from the De Lijn API.""" try: await self.line.get_passages() self._name = await self.line.get_stopname() except HttpException: self._available = False _LOGGER.error("De Lijn http error") return self._attributes["stopname"] = self._name try: first = self.line.passages[0] if first["due_at_realtime"] is not None: first_passage = first["due_at_realtime"] else: first_passage = first["due_at_schedule"] self._state = first_passage self._attributes["line_number_public"] = first["line_number_public"] self._attributes["line_transport_type"] = first["line_transport_type"] self._attributes["final_destination"] = first["final_destination"] self._attributes["due_at_schedule"] = first["due_at_schedule"] self._attributes["due_at_realtime"] = first["due_at_realtime"] self._attributes["is_realtime"] = first["is_realtime"] self._attributes["next_passages"] = self.line.passages self._available = True except (KeyError, IndexError): _LOGGER.error("Invalid data received from De Lijn") self._available = False @property def available(self): """Return True if entity is available.""" return self._available @property def device_class(self): """Return the device class.""" return DEVICE_CLASS_TIMESTAMP @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 of the sensor.""" return "mdi:bus" @property def device_state_attributes(self): """Return attributes for the sensor.""" return self._attributes
"""Define tests for the PlayStation 4 config flow.""" from pyps4_2ndscreen.errors import CredentialTimeout import pytest from homeassistant import data_entry_flow from homeassistant.components import ps4 from homeassistant.components.ps4.const import ( DEFAULT_ALIAS, DEFAULT_NAME, DEFAULT_REGION, DOMAIN, ) from homeassistant.const import ( CONF_CODE, CONF_HOST, CONF_IP_ADDRESS, CONF_NAME, CONF_REGION, CONF_TOKEN, ) from homeassistant.util import location from tests.async_mock import patch from tests.common import MockConfigEntry MOCK_TITLE = "PlayStation 4" MOCK_CODE = 12345678 MOCK_CODE_LEAD_0 = 1234567 MOCK_CODE_LEAD_0_STR = "01234567" MOCK_CREDS = "000aa000" MOCK_HOST = "192.0.0.0" MOCK_HOST_ADDITIONAL = "192.0.0.1" MOCK_DEVICE = { CONF_HOST: MOCK_HOST, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, } MOCK_DEVICE_ADDITIONAL = { CONF_HOST: MOCK_HOST_ADDITIONAL, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, } MOCK_CONFIG = { CONF_IP_ADDRESS: MOCK_HOST, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, CONF_CODE: MOCK_CODE, } MOCK_CONFIG_ADDITIONAL = { CONF_IP_ADDRESS: MOCK_HOST_ADDITIONAL, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, CONF_CODE: MOCK_CODE, } MOCK_DATA = {CONF_TOKEN: MOCK_CREDS, "devices": [MOCK_DEVICE]} MOCK_UDP_PORT = int(987) MOCK_TCP_PORT = int(997) MOCK_AUTO = {"Config Mode": "Auto Discover"} MOCK_MANUAL = {"Config Mode": "Manual Entry", CONF_IP_ADDRESS: MOCK_HOST} MOCK_LOCATION = location.LocationInfo( "0.0.0.0", "US", "United States", "CA", "California", "San Diego", "92122", "America/Los_Angeles", 32.8594, -117.2073, True, ) @pytest.fixture(name="location_info", autouse=True) def location_info_fixture(): """Mock location info.""" with patch( "homeassistant.components.ps4.config_flow.location.async_detect_location_info", return_value=MOCK_LOCATION, ): yield @pytest.fixture(name="ps4_setup", autouse=True) def ps4_setup_fixture(): """Patch ps4 setup entry.""" with patch( "homeassistant.components.ps4.async_setup_entry", return_value=True, ): yield async def test_full_flow_implementation(hass): """Test registering an implementation and flow works.""" # User Step Started, results in Step Creds with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # User Input results in created entry. with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert result["data"]["devices"] == [MOCK_DEVICE] assert result["title"] == MOCK_TITLE async def test_multiple_flow_implementation(hass): """Test multiple device flows.""" # User Step Started, results in Step Creds with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # User Input results in created entry. with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert result["data"]["devices"] == [MOCK_DEVICE] assert result["title"] == MOCK_TITLE # Check if entry exists. entries = hass.config_entries.async_entries() assert len(entries) == 1 # Check if there is a device config in entry. entry_1 = entries[0] assert len(entry_1.data["devices"]) == 1 # Test additional flow. # User Step Started, results in Step Mode: with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # Step Link with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ), patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert len(result["data"]["devices"]) == 1 assert result["title"] == MOCK_TITLE # Check if there are 2 entries. entries = hass.config_entries.async_entries() assert len(entries) == 2 # Check if there is device config in the last entry. entry_2 = entries[-1] assert len(entry_2.data["devices"]) == 1 # Check that entry 1 is different from entry 2. assert entry_1 is not entry_2 async def test_port_bind_abort(hass): """Test that flow aborted when cannot bind to ports 987, 997.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_UDP_PORT): reason = "port_987_bind_error" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == reason with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_TCP_PORT): reason = "port_997_bind_error" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == reason async def test_duplicate_abort(hass): """Test that Flow aborts when found devices already configured.""" MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA).add_to_hass(hass) with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_additional_device(hass): """Test that Flow can configure another device.""" # Mock existing entry. entry = MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA) entry.add_to_hass(hass) with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert len(result["data"]["devices"]) == 1 assert result["title"] == MOCK_TITLE async def test_0_pin(hass): """Test Pin with leading '0' is passed correctly.""" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "creds"}, data={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ), patch( "homeassistant.components.ps4.config_flow.location.async_detect_location_info", return_value=MOCK_LOCATION, ): result = await hass.config_entries.flow.async_configure( result["flow_id"], MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" mock_config = MOCK_CONFIG mock_config[CONF_CODE] = MOCK_CODE_LEAD_0 with patch( "pyps4_2ndscreen.Helper.link", return_value=(True, True) ) as mock_call, patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], mock_config ) mock_call.assert_called_once_with( MOCK_HOST, MOCK_CREDS, MOCK_CODE_LEAD_0_STR, DEFAULT_ALIAS ) async def test_no_devices_found_abort(hass): """Test that failure to find devices aborts flow.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch("pyps4_2ndscreen.Helper.has_devices", return_value=[]): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "no_devices_found" async def test_manual_mode(hass): """Test host specified in manual mode is passed to Step Link.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input: manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_MANUAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" async def test_credential_abort(hass): """Test that failure to get credentials aborts flow.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=None): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "credential_error" async def test_credential_timeout(hass): """Test that Credential Timeout shows error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", side_effect=CredentialTimeout): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" assert result["errors"] == {"base": "credential_timeout"} async def test_wrong_pin_error(hass): """Test that incorrect pin throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(True, False)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" assert result["errors"] == {"base": "login_failed"} async def test_device_connection_error(hass): """Test that device not connected or on throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(False, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" assert result["errors"] == {"base": "cannot_connect"} async def test_manual_mode_no_ip_error(hass): """Test no IP specified in manual mode throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={"Config Mode": "Manual Entry"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" assert result["errors"] == {CONF_IP_ADDRESS: "no_ipaddress"}
sdague/home-assistant
tests/components/ps4/test_config_flow.py
homeassistant/components/delijn/sensor.py
"""Offer MQTT listening automation rules.""" import json import voluptuous as vol from homeassistant.components import mqtt from homeassistant.const import CONF_PAYLOAD, CONF_PLATFORM from homeassistant.core import HassJob, callback import homeassistant.helpers.config_validation as cv # mypy: allow-untyped-defs CONF_ENCODING = "encoding" CONF_QOS = "qos" CONF_TOPIC = "topic" DEFAULT_ENCODING = "utf-8" DEFAULT_QOS = 0 TRIGGER_SCHEMA = vol.Schema( { vol.Required(CONF_PLATFORM): mqtt.DOMAIN, vol.Required(CONF_TOPIC): mqtt.util.valid_subscribe_topic, vol.Optional(CONF_PAYLOAD): cv.string, vol.Optional(CONF_ENCODING, default=DEFAULT_ENCODING): cv.string, vol.Optional(CONF_QOS, default=DEFAULT_QOS): vol.All( vol.Coerce(int), vol.In([0, 1, 2]) ), } ) async def async_attach_trigger(hass, config, action, automation_info): """Listen for state changes based on configuration.""" topic = config[CONF_TOPIC] payload = config.get(CONF_PAYLOAD) encoding = config[CONF_ENCODING] or None qos = config[CONF_QOS] job = HassJob(action) @callback def mqtt_automation_listener(mqttmsg): """Listen for MQTT messages.""" if payload is None or payload == mqttmsg.payload: data = { "platform": "mqtt", "topic": mqttmsg.topic, "payload": mqttmsg.payload, "qos": mqttmsg.qos, "description": f"mqtt topic {mqttmsg.topic}", } try: data["payload_json"] = json.loads(mqttmsg.payload) except ValueError: pass hass.async_run_hass_job(job, {"trigger": data}) remove = await mqtt.async_subscribe( hass, topic, mqtt_automation_listener, encoding=encoding, qos=qos ) return remove
"""Define tests for the PlayStation 4 config flow.""" from pyps4_2ndscreen.errors import CredentialTimeout import pytest from homeassistant import data_entry_flow from homeassistant.components import ps4 from homeassistant.components.ps4.const import ( DEFAULT_ALIAS, DEFAULT_NAME, DEFAULT_REGION, DOMAIN, ) from homeassistant.const import ( CONF_CODE, CONF_HOST, CONF_IP_ADDRESS, CONF_NAME, CONF_REGION, CONF_TOKEN, ) from homeassistant.util import location from tests.async_mock import patch from tests.common import MockConfigEntry MOCK_TITLE = "PlayStation 4" MOCK_CODE = 12345678 MOCK_CODE_LEAD_0 = 1234567 MOCK_CODE_LEAD_0_STR = "01234567" MOCK_CREDS = "000aa000" MOCK_HOST = "192.0.0.0" MOCK_HOST_ADDITIONAL = "192.0.0.1" MOCK_DEVICE = { CONF_HOST: MOCK_HOST, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, } MOCK_DEVICE_ADDITIONAL = { CONF_HOST: MOCK_HOST_ADDITIONAL, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, } MOCK_CONFIG = { CONF_IP_ADDRESS: MOCK_HOST, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, CONF_CODE: MOCK_CODE, } MOCK_CONFIG_ADDITIONAL = { CONF_IP_ADDRESS: MOCK_HOST_ADDITIONAL, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, CONF_CODE: MOCK_CODE, } MOCK_DATA = {CONF_TOKEN: MOCK_CREDS, "devices": [MOCK_DEVICE]} MOCK_UDP_PORT = int(987) MOCK_TCP_PORT = int(997) MOCK_AUTO = {"Config Mode": "Auto Discover"} MOCK_MANUAL = {"Config Mode": "Manual Entry", CONF_IP_ADDRESS: MOCK_HOST} MOCK_LOCATION = location.LocationInfo( "0.0.0.0", "US", "United States", "CA", "California", "San Diego", "92122", "America/Los_Angeles", 32.8594, -117.2073, True, ) @pytest.fixture(name="location_info", autouse=True) def location_info_fixture(): """Mock location info.""" with patch( "homeassistant.components.ps4.config_flow.location.async_detect_location_info", return_value=MOCK_LOCATION, ): yield @pytest.fixture(name="ps4_setup", autouse=True) def ps4_setup_fixture(): """Patch ps4 setup entry.""" with patch( "homeassistant.components.ps4.async_setup_entry", return_value=True, ): yield async def test_full_flow_implementation(hass): """Test registering an implementation and flow works.""" # User Step Started, results in Step Creds with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # User Input results in created entry. with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert result["data"]["devices"] == [MOCK_DEVICE] assert result["title"] == MOCK_TITLE async def test_multiple_flow_implementation(hass): """Test multiple device flows.""" # User Step Started, results in Step Creds with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # User Input results in created entry. with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert result["data"]["devices"] == [MOCK_DEVICE] assert result["title"] == MOCK_TITLE # Check if entry exists. entries = hass.config_entries.async_entries() assert len(entries) == 1 # Check if there is a device config in entry. entry_1 = entries[0] assert len(entry_1.data["devices"]) == 1 # Test additional flow. # User Step Started, results in Step Mode: with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # Step Link with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ), patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert len(result["data"]["devices"]) == 1 assert result["title"] == MOCK_TITLE # Check if there are 2 entries. entries = hass.config_entries.async_entries() assert len(entries) == 2 # Check if there is device config in the last entry. entry_2 = entries[-1] assert len(entry_2.data["devices"]) == 1 # Check that entry 1 is different from entry 2. assert entry_1 is not entry_2 async def test_port_bind_abort(hass): """Test that flow aborted when cannot bind to ports 987, 997.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_UDP_PORT): reason = "port_987_bind_error" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == reason with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_TCP_PORT): reason = "port_997_bind_error" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == reason async def test_duplicate_abort(hass): """Test that Flow aborts when found devices already configured.""" MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA).add_to_hass(hass) with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_additional_device(hass): """Test that Flow can configure another device.""" # Mock existing entry. entry = MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA) entry.add_to_hass(hass) with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert len(result["data"]["devices"]) == 1 assert result["title"] == MOCK_TITLE async def test_0_pin(hass): """Test Pin with leading '0' is passed correctly.""" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "creds"}, data={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ), patch( "homeassistant.components.ps4.config_flow.location.async_detect_location_info", return_value=MOCK_LOCATION, ): result = await hass.config_entries.flow.async_configure( result["flow_id"], MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" mock_config = MOCK_CONFIG mock_config[CONF_CODE] = MOCK_CODE_LEAD_0 with patch( "pyps4_2ndscreen.Helper.link", return_value=(True, True) ) as mock_call, patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], mock_config ) mock_call.assert_called_once_with( MOCK_HOST, MOCK_CREDS, MOCK_CODE_LEAD_0_STR, DEFAULT_ALIAS ) async def test_no_devices_found_abort(hass): """Test that failure to find devices aborts flow.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch("pyps4_2ndscreen.Helper.has_devices", return_value=[]): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "no_devices_found" async def test_manual_mode(hass): """Test host specified in manual mode is passed to Step Link.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input: manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_MANUAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" async def test_credential_abort(hass): """Test that failure to get credentials aborts flow.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=None): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "credential_error" async def test_credential_timeout(hass): """Test that Credential Timeout shows error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", side_effect=CredentialTimeout): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" assert result["errors"] == {"base": "credential_timeout"} async def test_wrong_pin_error(hass): """Test that incorrect pin throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(True, False)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" assert result["errors"] == {"base": "login_failed"} async def test_device_connection_error(hass): """Test that device not connected or on throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(False, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" assert result["errors"] == {"base": "cannot_connect"} async def test_manual_mode_no_ip_error(hass): """Test no IP specified in manual mode throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={"Config Mode": "Manual Entry"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" assert result["errors"] == {CONF_IP_ADDRESS: "no_ipaddress"}
sdague/home-assistant
tests/components/ps4/test_config_flow.py
homeassistant/components/mqtt/trigger.py
"""Email sensor support.""" from collections import deque import datetime import email import imaplib import logging import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( ATTR_DATE, CONF_NAME, CONF_PASSWORD, CONF_PORT, CONF_USERNAME, CONF_VALUE_TEMPLATE, CONTENT_TYPE_TEXT_PLAIN, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) CONF_SERVER = "server" CONF_SENDERS = "senders" CONF_FOLDER = "folder" ATTR_FROM = "from" ATTR_BODY = "body" ATTR_SUBJECT = "subject" DEFAULT_PORT = 993 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Optional(CONF_NAME): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_SERVER): cv.string, vol.Required(CONF_SENDERS): [cv.string], vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_FOLDER, default="INBOX"): cv.string, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Email sensor platform.""" reader = EmailReader( config.get(CONF_USERNAME), config.get(CONF_PASSWORD), config.get(CONF_SERVER), config.get(CONF_PORT), config.get(CONF_FOLDER), ) value_template = config.get(CONF_VALUE_TEMPLATE) if value_template is not None: value_template.hass = hass sensor = EmailContentSensor( hass, reader, config.get(CONF_NAME) or config.get(CONF_USERNAME), config.get(CONF_SENDERS), value_template, ) if sensor.connected: add_entities([sensor], True) else: return False class EmailReader: """A class to read emails from an IMAP server.""" def __init__(self, user, password, server, port, folder): """Initialize the Email Reader.""" self._user = user self._password = password self._server = server self._port = port self._folder = folder self._last_id = None self._unread_ids = deque([]) self.connection = None def connect(self): """Login and setup the connection.""" try: self.connection = imaplib.IMAP4_SSL(self._server, self._port) self.connection.login(self._user, self._password) return True except imaplib.IMAP4.error: _LOGGER.error("Failed to login to %s", self._server) return False def _fetch_message(self, message_uid): """Get an email message from a message id.""" _, message_data = self.connection.uid("fetch", message_uid, "(RFC822)") if message_data is None: return None if message_data[0] is None: return None raw_email = message_data[0][1] email_message = email.message_from_bytes(raw_email) return email_message def read_next(self): """Read the next email from the email server.""" try: self.connection.select(self._folder, readonly=True) if not self._unread_ids: search = f"SINCE {datetime.date.today():%d-%b-%Y}" if self._last_id is not None: search = f"UID {self._last_id}:*" _, data = self.connection.uid("search", None, search) self._unread_ids = deque(data[0].split()) while self._unread_ids: message_uid = self._unread_ids.popleft() if self._last_id is None or int(message_uid) > self._last_id: self._last_id = int(message_uid) return self._fetch_message(message_uid) return self._fetch_message(str(self._last_id)) except imaplib.IMAP4.error: _LOGGER.info("Connection to %s lost, attempting to reconnect", self._server) try: self.connect() _LOGGER.info( "Reconnect to %s succeeded, trying last message", self._server ) if self._last_id is not None: return self._fetch_message(str(self._last_id)) except imaplib.IMAP4.error: _LOGGER.error("Failed to reconnect") return None class EmailContentSensor(Entity): """Representation of an EMail sensor.""" def __init__(self, hass, email_reader, name, allowed_senders, value_template): """Initialize the sensor.""" self.hass = hass self._email_reader = email_reader self._name = name self._allowed_senders = [sender.upper() for sender in allowed_senders] self._value_template = value_template self._last_id = None self._message = None self._state_attributes = None self.connected = self._email_reader.connect() @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the current email state.""" return self._message @property def device_state_attributes(self): """Return other state attributes for the message.""" return self._state_attributes def render_template(self, email_message): """Render the message template.""" variables = { ATTR_FROM: EmailContentSensor.get_msg_sender(email_message), ATTR_SUBJECT: EmailContentSensor.get_msg_subject(email_message), ATTR_DATE: email_message["Date"], ATTR_BODY: EmailContentSensor.get_msg_text(email_message), } return self._value_template.render(variables, parse_result=False) def sender_allowed(self, email_message): """Check if the sender is in the allowed senders list.""" return EmailContentSensor.get_msg_sender(email_message).upper() in ( sender for sender in self._allowed_senders ) @staticmethod def get_msg_sender(email_message): """Get the parsed message sender from the email.""" return str(email.utils.parseaddr(email_message["From"])[1]) @staticmethod def get_msg_subject(email_message): """Decode the message subject.""" decoded_header = email.header.decode_header(email_message["Subject"]) header = email.header.make_header(decoded_header) return str(header) @staticmethod def get_msg_text(email_message): """ Get the message text from the email. Will look for text/plain or use text/html if not found. """ message_text = None message_html = None message_untyped_text = None for part in email_message.walk(): if part.get_content_type() == CONTENT_TYPE_TEXT_PLAIN: if message_text is None: message_text = part.get_payload() elif part.get_content_type() == "text/html": if message_html is None: message_html = part.get_payload() elif part.get_content_type().startswith("text"): if message_untyped_text is None: message_untyped_text = part.get_payload() if message_text is not None: return message_text if message_html is not None: return message_html if message_untyped_text is not None: return message_untyped_text return email_message.get_payload() def update(self): """Read emails and publish state change.""" email_message = self._email_reader.read_next() if email_message is None: self._message = None self._state_attributes = {} return if self.sender_allowed(email_message): message = EmailContentSensor.get_msg_subject(email_message) if self._value_template is not None: message = self.render_template(email_message) self._message = message self._state_attributes = { ATTR_FROM: EmailContentSensor.get_msg_sender(email_message), ATTR_SUBJECT: EmailContentSensor.get_msg_subject(email_message), ATTR_DATE: email_message["Date"], ATTR_BODY: EmailContentSensor.get_msg_text(email_message), }
"""Define tests for the PlayStation 4 config flow.""" from pyps4_2ndscreen.errors import CredentialTimeout import pytest from homeassistant import data_entry_flow from homeassistant.components import ps4 from homeassistant.components.ps4.const import ( DEFAULT_ALIAS, DEFAULT_NAME, DEFAULT_REGION, DOMAIN, ) from homeassistant.const import ( CONF_CODE, CONF_HOST, CONF_IP_ADDRESS, CONF_NAME, CONF_REGION, CONF_TOKEN, ) from homeassistant.util import location from tests.async_mock import patch from tests.common import MockConfigEntry MOCK_TITLE = "PlayStation 4" MOCK_CODE = 12345678 MOCK_CODE_LEAD_0 = 1234567 MOCK_CODE_LEAD_0_STR = "01234567" MOCK_CREDS = "000aa000" MOCK_HOST = "192.0.0.0" MOCK_HOST_ADDITIONAL = "192.0.0.1" MOCK_DEVICE = { CONF_HOST: MOCK_HOST, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, } MOCK_DEVICE_ADDITIONAL = { CONF_HOST: MOCK_HOST_ADDITIONAL, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, } MOCK_CONFIG = { CONF_IP_ADDRESS: MOCK_HOST, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, CONF_CODE: MOCK_CODE, } MOCK_CONFIG_ADDITIONAL = { CONF_IP_ADDRESS: MOCK_HOST_ADDITIONAL, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, CONF_CODE: MOCK_CODE, } MOCK_DATA = {CONF_TOKEN: MOCK_CREDS, "devices": [MOCK_DEVICE]} MOCK_UDP_PORT = int(987) MOCK_TCP_PORT = int(997) MOCK_AUTO = {"Config Mode": "Auto Discover"} MOCK_MANUAL = {"Config Mode": "Manual Entry", CONF_IP_ADDRESS: MOCK_HOST} MOCK_LOCATION = location.LocationInfo( "0.0.0.0", "US", "United States", "CA", "California", "San Diego", "92122", "America/Los_Angeles", 32.8594, -117.2073, True, ) @pytest.fixture(name="location_info", autouse=True) def location_info_fixture(): """Mock location info.""" with patch( "homeassistant.components.ps4.config_flow.location.async_detect_location_info", return_value=MOCK_LOCATION, ): yield @pytest.fixture(name="ps4_setup", autouse=True) def ps4_setup_fixture(): """Patch ps4 setup entry.""" with patch( "homeassistant.components.ps4.async_setup_entry", return_value=True, ): yield async def test_full_flow_implementation(hass): """Test registering an implementation and flow works.""" # User Step Started, results in Step Creds with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # User Input results in created entry. with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert result["data"]["devices"] == [MOCK_DEVICE] assert result["title"] == MOCK_TITLE async def test_multiple_flow_implementation(hass): """Test multiple device flows.""" # User Step Started, results in Step Creds with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # User Input results in created entry. with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert result["data"]["devices"] == [MOCK_DEVICE] assert result["title"] == MOCK_TITLE # Check if entry exists. entries = hass.config_entries.async_entries() assert len(entries) == 1 # Check if there is a device config in entry. entry_1 = entries[0] assert len(entry_1.data["devices"]) == 1 # Test additional flow. # User Step Started, results in Step Mode: with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # Step Link with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ), patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert len(result["data"]["devices"]) == 1 assert result["title"] == MOCK_TITLE # Check if there are 2 entries. entries = hass.config_entries.async_entries() assert len(entries) == 2 # Check if there is device config in the last entry. entry_2 = entries[-1] assert len(entry_2.data["devices"]) == 1 # Check that entry 1 is different from entry 2. assert entry_1 is not entry_2 async def test_port_bind_abort(hass): """Test that flow aborted when cannot bind to ports 987, 997.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_UDP_PORT): reason = "port_987_bind_error" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == reason with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_TCP_PORT): reason = "port_997_bind_error" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == reason async def test_duplicate_abort(hass): """Test that Flow aborts when found devices already configured.""" MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA).add_to_hass(hass) with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_additional_device(hass): """Test that Flow can configure another device.""" # Mock existing entry. entry = MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA) entry.add_to_hass(hass) with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert len(result["data"]["devices"]) == 1 assert result["title"] == MOCK_TITLE async def test_0_pin(hass): """Test Pin with leading '0' is passed correctly.""" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "creds"}, data={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ), patch( "homeassistant.components.ps4.config_flow.location.async_detect_location_info", return_value=MOCK_LOCATION, ): result = await hass.config_entries.flow.async_configure( result["flow_id"], MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" mock_config = MOCK_CONFIG mock_config[CONF_CODE] = MOCK_CODE_LEAD_0 with patch( "pyps4_2ndscreen.Helper.link", return_value=(True, True) ) as mock_call, patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], mock_config ) mock_call.assert_called_once_with( MOCK_HOST, MOCK_CREDS, MOCK_CODE_LEAD_0_STR, DEFAULT_ALIAS ) async def test_no_devices_found_abort(hass): """Test that failure to find devices aborts flow.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch("pyps4_2ndscreen.Helper.has_devices", return_value=[]): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "no_devices_found" async def test_manual_mode(hass): """Test host specified in manual mode is passed to Step Link.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input: manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_MANUAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" async def test_credential_abort(hass): """Test that failure to get credentials aborts flow.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=None): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "credential_error" async def test_credential_timeout(hass): """Test that Credential Timeout shows error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", side_effect=CredentialTimeout): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" assert result["errors"] == {"base": "credential_timeout"} async def test_wrong_pin_error(hass): """Test that incorrect pin throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(True, False)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" assert result["errors"] == {"base": "login_failed"} async def test_device_connection_error(hass): """Test that device not connected or on throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(False, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" assert result["errors"] == {"base": "cannot_connect"} async def test_manual_mode_no_ip_error(hass): """Test no IP specified in manual mode throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={"Config Mode": "Manual Entry"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" assert result["errors"] == {CONF_IP_ADDRESS: "no_ipaddress"}
sdague/home-assistant
tests/components/ps4/test_config_flow.py
homeassistant/components/imap_email_content/sensor.py
"""Config flow for Profiler integration.""" import voluptuous as vol from homeassistant import config_entries from .const import DEFAULT_NAME from .const import DOMAIN # pylint: disable=unused-import class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Handle a config flow for Profiler.""" VERSION = 1 CONNECTION_CLASS = config_entries.CONN_CLASS_UNKNOWN async def async_step_user(self, user_input=None): """Handle the initial step.""" if self._async_current_entries(): return self.async_abort(reason="single_instance_allowed") if user_input is not None: return self.async_create_entry(title=DEFAULT_NAME, data={}) return self.async_show_form(step_id="user", data_schema=vol.Schema({}))
"""Define tests for the PlayStation 4 config flow.""" from pyps4_2ndscreen.errors import CredentialTimeout import pytest from homeassistant import data_entry_flow from homeassistant.components import ps4 from homeassistant.components.ps4.const import ( DEFAULT_ALIAS, DEFAULT_NAME, DEFAULT_REGION, DOMAIN, ) from homeassistant.const import ( CONF_CODE, CONF_HOST, CONF_IP_ADDRESS, CONF_NAME, CONF_REGION, CONF_TOKEN, ) from homeassistant.util import location from tests.async_mock import patch from tests.common import MockConfigEntry MOCK_TITLE = "PlayStation 4" MOCK_CODE = 12345678 MOCK_CODE_LEAD_0 = 1234567 MOCK_CODE_LEAD_0_STR = "01234567" MOCK_CREDS = "000aa000" MOCK_HOST = "192.0.0.0" MOCK_HOST_ADDITIONAL = "192.0.0.1" MOCK_DEVICE = { CONF_HOST: MOCK_HOST, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, } MOCK_DEVICE_ADDITIONAL = { CONF_HOST: MOCK_HOST_ADDITIONAL, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, } MOCK_CONFIG = { CONF_IP_ADDRESS: MOCK_HOST, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, CONF_CODE: MOCK_CODE, } MOCK_CONFIG_ADDITIONAL = { CONF_IP_ADDRESS: MOCK_HOST_ADDITIONAL, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, CONF_CODE: MOCK_CODE, } MOCK_DATA = {CONF_TOKEN: MOCK_CREDS, "devices": [MOCK_DEVICE]} MOCK_UDP_PORT = int(987) MOCK_TCP_PORT = int(997) MOCK_AUTO = {"Config Mode": "Auto Discover"} MOCK_MANUAL = {"Config Mode": "Manual Entry", CONF_IP_ADDRESS: MOCK_HOST} MOCK_LOCATION = location.LocationInfo( "0.0.0.0", "US", "United States", "CA", "California", "San Diego", "92122", "America/Los_Angeles", 32.8594, -117.2073, True, ) @pytest.fixture(name="location_info", autouse=True) def location_info_fixture(): """Mock location info.""" with patch( "homeassistant.components.ps4.config_flow.location.async_detect_location_info", return_value=MOCK_LOCATION, ): yield @pytest.fixture(name="ps4_setup", autouse=True) def ps4_setup_fixture(): """Patch ps4 setup entry.""" with patch( "homeassistant.components.ps4.async_setup_entry", return_value=True, ): yield async def test_full_flow_implementation(hass): """Test registering an implementation and flow works.""" # User Step Started, results in Step Creds with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # User Input results in created entry. with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert result["data"]["devices"] == [MOCK_DEVICE] assert result["title"] == MOCK_TITLE async def test_multiple_flow_implementation(hass): """Test multiple device flows.""" # User Step Started, results in Step Creds with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # User Input results in created entry. with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert result["data"]["devices"] == [MOCK_DEVICE] assert result["title"] == MOCK_TITLE # Check if entry exists. entries = hass.config_entries.async_entries() assert len(entries) == 1 # Check if there is a device config in entry. entry_1 = entries[0] assert len(entry_1.data["devices"]) == 1 # Test additional flow. # User Step Started, results in Step Mode: with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # Step Link with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ), patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert len(result["data"]["devices"]) == 1 assert result["title"] == MOCK_TITLE # Check if there are 2 entries. entries = hass.config_entries.async_entries() assert len(entries) == 2 # Check if there is device config in the last entry. entry_2 = entries[-1] assert len(entry_2.data["devices"]) == 1 # Check that entry 1 is different from entry 2. assert entry_1 is not entry_2 async def test_port_bind_abort(hass): """Test that flow aborted when cannot bind to ports 987, 997.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_UDP_PORT): reason = "port_987_bind_error" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == reason with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_TCP_PORT): reason = "port_997_bind_error" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == reason async def test_duplicate_abort(hass): """Test that Flow aborts when found devices already configured.""" MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA).add_to_hass(hass) with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_additional_device(hass): """Test that Flow can configure another device.""" # Mock existing entry. entry = MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA) entry.add_to_hass(hass) with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert len(result["data"]["devices"]) == 1 assert result["title"] == MOCK_TITLE async def test_0_pin(hass): """Test Pin with leading '0' is passed correctly.""" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "creds"}, data={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ), patch( "homeassistant.components.ps4.config_flow.location.async_detect_location_info", return_value=MOCK_LOCATION, ): result = await hass.config_entries.flow.async_configure( result["flow_id"], MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" mock_config = MOCK_CONFIG mock_config[CONF_CODE] = MOCK_CODE_LEAD_0 with patch( "pyps4_2ndscreen.Helper.link", return_value=(True, True) ) as mock_call, patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], mock_config ) mock_call.assert_called_once_with( MOCK_HOST, MOCK_CREDS, MOCK_CODE_LEAD_0_STR, DEFAULT_ALIAS ) async def test_no_devices_found_abort(hass): """Test that failure to find devices aborts flow.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch("pyps4_2ndscreen.Helper.has_devices", return_value=[]): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "no_devices_found" async def test_manual_mode(hass): """Test host specified in manual mode is passed to Step Link.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input: manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_MANUAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" async def test_credential_abort(hass): """Test that failure to get credentials aborts flow.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=None): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "credential_error" async def test_credential_timeout(hass): """Test that Credential Timeout shows error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", side_effect=CredentialTimeout): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" assert result["errors"] == {"base": "credential_timeout"} async def test_wrong_pin_error(hass): """Test that incorrect pin throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(True, False)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" assert result["errors"] == {"base": "login_failed"} async def test_device_connection_error(hass): """Test that device not connected or on throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(False, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" assert result["errors"] == {"base": "cannot_connect"} async def test_manual_mode_no_ip_error(hass): """Test no IP specified in manual mode throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={"Config Mode": "Manual Entry"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" assert result["errors"] == {CONF_IP_ADDRESS: "no_ipaddress"}
sdague/home-assistant
tests/components/ps4/test_config_flow.py
homeassistant/components/profiler/config_flow.py
"""Support for IntesisHome and airconwithme Smart AC Controllers.""" import logging from random import randrange from pyintesishome import IHAuthenticationError, IHConnectionError, IntesisHome import voluptuous as vol from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateEntity from homeassistant.components.climate.const import ( ATTR_HVAC_MODE, HVAC_MODE_COOL, HVAC_MODE_DRY, HVAC_MODE_FAN_ONLY, HVAC_MODE_HEAT, HVAC_MODE_HEAT_COOL, HVAC_MODE_OFF, PRESET_BOOST, PRESET_COMFORT, PRESET_ECO, SUPPORT_FAN_MODE, SUPPORT_PRESET_MODE, SUPPORT_SWING_MODE, SUPPORT_TARGET_TEMPERATURE, SWING_BOTH, SWING_HORIZONTAL, SWING_OFF, SWING_VERTICAL, ) from homeassistant.const import ( ATTR_TEMPERATURE, CONF_DEVICE, CONF_PASSWORD, CONF_USERNAME, TEMP_CELSIUS, ) from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.event import async_call_later _LOGGER = logging.getLogger(__name__) IH_DEVICE_INTESISHOME = "IntesisHome" IH_DEVICE_AIRCONWITHME = "airconwithme" PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_DEVICE, default=IH_DEVICE_INTESISHOME): vol.In( [IH_DEVICE_AIRCONWITHME, IH_DEVICE_INTESISHOME] ), } ) MAP_IH_TO_HVAC_MODE = { "auto": HVAC_MODE_HEAT_COOL, "cool": HVAC_MODE_COOL, "dry": HVAC_MODE_DRY, "fan": HVAC_MODE_FAN_ONLY, "heat": HVAC_MODE_HEAT, "off": HVAC_MODE_OFF, } MAP_HVAC_MODE_TO_IH = {v: k for k, v in MAP_IH_TO_HVAC_MODE.items()} MAP_IH_TO_PRESET_MODE = { "eco": PRESET_ECO, "comfort": PRESET_COMFORT, "powerful": PRESET_BOOST, } MAP_PRESET_MODE_TO_IH = {v: k for k, v in MAP_IH_TO_PRESET_MODE.items()} IH_SWING_STOP = "auto/stop" IH_SWING_SWING = "swing" MAP_SWING_TO_IH = { SWING_OFF: {"vvane": IH_SWING_STOP, "hvane": IH_SWING_STOP}, SWING_BOTH: {"vvane": IH_SWING_SWING, "hvane": IH_SWING_SWING}, SWING_HORIZONTAL: {"vvane": IH_SWING_STOP, "hvane": IH_SWING_SWING}, SWING_VERTICAL: {"vvane": IH_SWING_SWING, "hvane": IH_SWING_STOP}, } MAP_STATE_ICONS = { HVAC_MODE_COOL: "mdi:snowflake", HVAC_MODE_DRY: "mdi:water-off", HVAC_MODE_FAN_ONLY: "mdi:fan", HVAC_MODE_HEAT: "mdi:white-balance-sunny", HVAC_MODE_HEAT_COOL: "mdi:cached", } async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Create the IntesisHome climate devices.""" ih_user = config[CONF_USERNAME] ih_pass = config[CONF_PASSWORD] device_type = config[CONF_DEVICE] controller = IntesisHome( ih_user, ih_pass, hass.loop, websession=async_get_clientsession(hass), device_type=device_type, ) try: await controller.poll_status() except IHAuthenticationError: _LOGGER.error("Invalid username or password") return except IHConnectionError as ex: _LOGGER.error("Error connecting to the %s server", device_type) raise PlatformNotReady from ex ih_devices = controller.get_devices() if ih_devices: async_add_entities( [ IntesisAC(ih_device_id, device, controller) for ih_device_id, device in ih_devices.items() ], True, ) else: _LOGGER.error( "Error getting device list from %s API: %s", device_type, controller.error_message, ) await controller.stop() class IntesisAC(ClimateEntity): """Represents an Intesishome air conditioning device.""" def __init__(self, ih_device_id, ih_device, controller): """Initialize the thermostat.""" self._controller = controller self._device_id = ih_device_id self._ih_device = ih_device self._device_name = ih_device.get("name") self._device_type = controller.device_type self._connected = None self._setpoint_step = 1 self._current_temp = None self._max_temp = None self._hvac_mode_list = [] self._min_temp = None self._target_temp = None self._outdoor_temp = None self._hvac_mode = None self._preset = None self._preset_list = [PRESET_ECO, PRESET_COMFORT, PRESET_BOOST] self._run_hours = None self._rssi = None self._swing_list = [SWING_OFF] self._vvane = None self._hvane = None self._power = False self._fan_speed = None self._support = 0 self._power_consumption_heat = None self._power_consumption_cool = None # Setpoint support if controller.has_setpoint_control(ih_device_id): self._support |= SUPPORT_TARGET_TEMPERATURE # Setup swing list if controller.has_vertical_swing(ih_device_id): self._swing_list.append(SWING_VERTICAL) if controller.has_horizontal_swing(ih_device_id): self._swing_list.append(SWING_HORIZONTAL) if SWING_HORIZONTAL in self._swing_list and SWING_VERTICAL in self._swing_list: self._swing_list.append(SWING_BOTH) if len(self._swing_list) > 1: self._support |= SUPPORT_SWING_MODE # Setup fan speeds self._fan_modes = controller.get_fan_speed_list(ih_device_id) if self._fan_modes: self._support |= SUPPORT_FAN_MODE # Preset support if ih_device.get("climate_working_mode"): self._support |= SUPPORT_PRESET_MODE # Setup HVAC modes modes = controller.get_mode_list(ih_device_id) if modes: mode_list = [MAP_IH_TO_HVAC_MODE[mode] for mode in modes] self._hvac_mode_list.extend(mode_list) self._hvac_mode_list.append(HVAC_MODE_OFF) async def async_added_to_hass(self): """Subscribe to event updates.""" _LOGGER.debug("Added climate device with state: %s", repr(self._ih_device)) await self._controller.add_update_callback(self.async_update_callback) try: await self._controller.connect() except IHConnectionError as ex: _LOGGER.error("Exception connecting to IntesisHome: %s", ex) raise PlatformNotReady from ex @property def name(self): """Return the name of the AC device.""" return self._device_name @property def temperature_unit(self): """Intesishome API uses celsius on the backend.""" return TEMP_CELSIUS @property def device_state_attributes(self): """Return the device specific state attributes.""" attrs = {} if self._outdoor_temp: attrs["outdoor_temp"] = self._outdoor_temp if self._power_consumption_heat: attrs["power_consumption_heat_kw"] = round( self._power_consumption_heat / 1000, 1 ) if self._power_consumption_cool: attrs["power_consumption_cool_kw"] = round( self._power_consumption_cool / 1000, 1 ) return attrs @property def unique_id(self): """Return unique ID for this device.""" return self._device_id @property def target_temperature_step(self) -> float: """Return whether setpoint should be whole or half degree precision.""" return self._setpoint_step @property def preset_modes(self): """Return a list of HVAC preset modes.""" return self._preset_list @property def preset_mode(self): """Return the current preset mode.""" return self._preset async def async_set_temperature(self, **kwargs): """Set new target temperature.""" temperature = kwargs.get(ATTR_TEMPERATURE) hvac_mode = kwargs.get(ATTR_HVAC_MODE) if hvac_mode: await self.async_set_hvac_mode(hvac_mode) if temperature: _LOGGER.debug("Setting %s to %s degrees", self._device_type, temperature) await self._controller.set_temperature(self._device_id, temperature) self._target_temp = temperature # Write updated temperature to HA state to avoid flapping (API confirmation is slow) self.async_write_ha_state() async def async_set_hvac_mode(self, hvac_mode): """Set operation mode.""" _LOGGER.debug("Setting %s to %s mode", self._device_type, hvac_mode) if hvac_mode == HVAC_MODE_OFF: self._power = False await self._controller.set_power_off(self._device_id) # Write changes to HA, API can be slow to push changes self.async_write_ha_state() return # First check device is turned on if not self._controller.is_on(self._device_id): self._power = True await self._controller.set_power_on(self._device_id) # Set the mode await self._controller.set_mode(self._device_id, MAP_HVAC_MODE_TO_IH[hvac_mode]) # Send the temperature again in case changing modes has changed it if self._target_temp: await self._controller.set_temperature(self._device_id, self._target_temp) # Updates can take longer than 2 seconds, so update locally self._hvac_mode = hvac_mode self.async_write_ha_state() async def async_set_fan_mode(self, fan_mode): """Set fan mode (from quiet, low, medium, high, auto).""" await self._controller.set_fan_speed(self._device_id, fan_mode) # Updates can take longer than 2 seconds, so update locally self._fan_speed = fan_mode self.async_write_ha_state() async def async_set_preset_mode(self, preset_mode): """Set preset mode.""" ih_preset_mode = MAP_PRESET_MODE_TO_IH.get(preset_mode) await self._controller.set_preset_mode(self._device_id, ih_preset_mode) async def async_set_swing_mode(self, swing_mode): """Set the vertical vane.""" swing_settings = MAP_SWING_TO_IH.get(swing_mode) if swing_settings: await self._controller.set_vertical_vane( self._device_id, swing_settings.get("vvane") ) await self._controller.set_horizontal_vane( self._device_id, swing_settings.get("hvane") ) async def async_update(self): """Copy values from controller dictionary to climate device.""" # Update values from controller's device dictionary self._connected = self._controller.is_connected self._current_temp = self._controller.get_temperature(self._device_id) self._fan_speed = self._controller.get_fan_speed(self._device_id) self._power = self._controller.is_on(self._device_id) self._min_temp = self._controller.get_min_setpoint(self._device_id) self._max_temp = self._controller.get_max_setpoint(self._device_id) self._rssi = self._controller.get_rssi(self._device_id) self._run_hours = self._controller.get_run_hours(self._device_id) self._target_temp = self._controller.get_setpoint(self._device_id) self._outdoor_temp = self._controller.get_outdoor_temperature(self._device_id) # Operation mode mode = self._controller.get_mode(self._device_id) self._hvac_mode = MAP_IH_TO_HVAC_MODE.get(mode) # Preset mode preset = self._controller.get_preset_mode(self._device_id) self._preset = MAP_IH_TO_PRESET_MODE.get(preset) # Swing mode # Climate module only supports one swing setting. self._vvane = self._controller.get_vertical_swing(self._device_id) self._hvane = self._controller.get_horizontal_swing(self._device_id) # Power usage self._power_consumption_heat = self._controller.get_heat_power_consumption( self._device_id ) self._power_consumption_cool = self._controller.get_cool_power_consumption( self._device_id ) async def async_will_remove_from_hass(self): """Shutdown the controller when the device is being removed.""" await self._controller.stop() @property def icon(self): """Return the icon for the current state.""" icon = None if self._power: icon = MAP_STATE_ICONS.get(self._hvac_mode) return icon async def async_update_callback(self, device_id=None): """Let HA know there has been an update from the controller.""" # Track changes in connection state if not self._controller.is_connected and self._connected: # Connection has dropped self._connected = False reconnect_minutes = 1 + randrange(10) _LOGGER.error( "Connection to %s API was lost. Reconnecting in %i minutes", self._device_type, reconnect_minutes, ) # Schedule reconnection async_call_later( self.hass, reconnect_minutes * 60, self._controller.connect() ) if self._controller.is_connected and not self._connected: # Connection has been restored self._connected = True _LOGGER.debug("Connection to %s API was restored", self._device_type) if not device_id or self._device_id == device_id: # Update all devices if no device_id was specified _LOGGER.debug( "%s API sent a status update for device %s", self._device_type, device_id, ) self.async_schedule_update_ha_state(True) @property def min_temp(self): """Return the minimum temperature for the current mode of operation.""" return self._min_temp @property def max_temp(self): """Return the maximum temperature for the current mode of operation.""" return self._max_temp @property def should_poll(self): """Poll for updates if pyIntesisHome doesn't have a socket open.""" return False @property def hvac_modes(self): """List of available operation modes.""" return self._hvac_mode_list @property def fan_mode(self): """Return whether the fan is on.""" return self._fan_speed @property def swing_mode(self): """Return current swing mode.""" if self._vvane == IH_SWING_SWING and self._hvane == IH_SWING_SWING: swing = SWING_BOTH elif self._vvane == IH_SWING_SWING: swing = SWING_VERTICAL elif self._hvane == IH_SWING_SWING: swing = SWING_HORIZONTAL else: swing = SWING_OFF return swing @property def fan_modes(self): """List of available fan modes.""" return self._fan_modes @property def swing_modes(self): """List of available swing positions.""" return self._swing_list @property def available(self) -> bool: """If the device hasn't been able to connect, mark as unavailable.""" return self._connected or self._connected is None @property def current_temperature(self): """Return the current temperature.""" return self._current_temp @property def hvac_mode(self): """Return the current mode of operation if unit is on.""" if self._power: return self._hvac_mode return HVAC_MODE_OFF @property def target_temperature(self): """Return the current setpoint temperature if unit is on.""" return self._target_temp @property def supported_features(self): """Return the list of supported features.""" return self._support
"""Define tests for the PlayStation 4 config flow.""" from pyps4_2ndscreen.errors import CredentialTimeout import pytest from homeassistant import data_entry_flow from homeassistant.components import ps4 from homeassistant.components.ps4.const import ( DEFAULT_ALIAS, DEFAULT_NAME, DEFAULT_REGION, DOMAIN, ) from homeassistant.const import ( CONF_CODE, CONF_HOST, CONF_IP_ADDRESS, CONF_NAME, CONF_REGION, CONF_TOKEN, ) from homeassistant.util import location from tests.async_mock import patch from tests.common import MockConfigEntry MOCK_TITLE = "PlayStation 4" MOCK_CODE = 12345678 MOCK_CODE_LEAD_0 = 1234567 MOCK_CODE_LEAD_0_STR = "01234567" MOCK_CREDS = "000aa000" MOCK_HOST = "192.0.0.0" MOCK_HOST_ADDITIONAL = "192.0.0.1" MOCK_DEVICE = { CONF_HOST: MOCK_HOST, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, } MOCK_DEVICE_ADDITIONAL = { CONF_HOST: MOCK_HOST_ADDITIONAL, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, } MOCK_CONFIG = { CONF_IP_ADDRESS: MOCK_HOST, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, CONF_CODE: MOCK_CODE, } MOCK_CONFIG_ADDITIONAL = { CONF_IP_ADDRESS: MOCK_HOST_ADDITIONAL, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, CONF_CODE: MOCK_CODE, } MOCK_DATA = {CONF_TOKEN: MOCK_CREDS, "devices": [MOCK_DEVICE]} MOCK_UDP_PORT = int(987) MOCK_TCP_PORT = int(997) MOCK_AUTO = {"Config Mode": "Auto Discover"} MOCK_MANUAL = {"Config Mode": "Manual Entry", CONF_IP_ADDRESS: MOCK_HOST} MOCK_LOCATION = location.LocationInfo( "0.0.0.0", "US", "United States", "CA", "California", "San Diego", "92122", "America/Los_Angeles", 32.8594, -117.2073, True, ) @pytest.fixture(name="location_info", autouse=True) def location_info_fixture(): """Mock location info.""" with patch( "homeassistant.components.ps4.config_flow.location.async_detect_location_info", return_value=MOCK_LOCATION, ): yield @pytest.fixture(name="ps4_setup", autouse=True) def ps4_setup_fixture(): """Patch ps4 setup entry.""" with patch( "homeassistant.components.ps4.async_setup_entry", return_value=True, ): yield async def test_full_flow_implementation(hass): """Test registering an implementation and flow works.""" # User Step Started, results in Step Creds with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # User Input results in created entry. with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert result["data"]["devices"] == [MOCK_DEVICE] assert result["title"] == MOCK_TITLE async def test_multiple_flow_implementation(hass): """Test multiple device flows.""" # User Step Started, results in Step Creds with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # User Input results in created entry. with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert result["data"]["devices"] == [MOCK_DEVICE] assert result["title"] == MOCK_TITLE # Check if entry exists. entries = hass.config_entries.async_entries() assert len(entries) == 1 # Check if there is a device config in entry. entry_1 = entries[0] assert len(entry_1.data["devices"]) == 1 # Test additional flow. # User Step Started, results in Step Mode: with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # Step Link with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ), patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert len(result["data"]["devices"]) == 1 assert result["title"] == MOCK_TITLE # Check if there are 2 entries. entries = hass.config_entries.async_entries() assert len(entries) == 2 # Check if there is device config in the last entry. entry_2 = entries[-1] assert len(entry_2.data["devices"]) == 1 # Check that entry 1 is different from entry 2. assert entry_1 is not entry_2 async def test_port_bind_abort(hass): """Test that flow aborted when cannot bind to ports 987, 997.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_UDP_PORT): reason = "port_987_bind_error" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == reason with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_TCP_PORT): reason = "port_997_bind_error" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == reason async def test_duplicate_abort(hass): """Test that Flow aborts when found devices already configured.""" MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA).add_to_hass(hass) with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_additional_device(hass): """Test that Flow can configure another device.""" # Mock existing entry. entry = MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA) entry.add_to_hass(hass) with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert len(result["data"]["devices"]) == 1 assert result["title"] == MOCK_TITLE async def test_0_pin(hass): """Test Pin with leading '0' is passed correctly.""" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "creds"}, data={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ), patch( "homeassistant.components.ps4.config_flow.location.async_detect_location_info", return_value=MOCK_LOCATION, ): result = await hass.config_entries.flow.async_configure( result["flow_id"], MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" mock_config = MOCK_CONFIG mock_config[CONF_CODE] = MOCK_CODE_LEAD_0 with patch( "pyps4_2ndscreen.Helper.link", return_value=(True, True) ) as mock_call, patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], mock_config ) mock_call.assert_called_once_with( MOCK_HOST, MOCK_CREDS, MOCK_CODE_LEAD_0_STR, DEFAULT_ALIAS ) async def test_no_devices_found_abort(hass): """Test that failure to find devices aborts flow.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch("pyps4_2ndscreen.Helper.has_devices", return_value=[]): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "no_devices_found" async def test_manual_mode(hass): """Test host specified in manual mode is passed to Step Link.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input: manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_MANUAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" async def test_credential_abort(hass): """Test that failure to get credentials aborts flow.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=None): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "credential_error" async def test_credential_timeout(hass): """Test that Credential Timeout shows error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", side_effect=CredentialTimeout): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" assert result["errors"] == {"base": "credential_timeout"} async def test_wrong_pin_error(hass): """Test that incorrect pin throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(True, False)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" assert result["errors"] == {"base": "login_failed"} async def test_device_connection_error(hass): """Test that device not connected or on throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(False, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" assert result["errors"] == {"base": "cannot_connect"} async def test_manual_mode_no_ip_error(hass): """Test no IP specified in manual mode throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={"Config Mode": "Manual Entry"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" assert result["errors"] == {CONF_IP_ADDRESS: "no_ipaddress"}
sdague/home-assistant
tests/components/ps4/test_config_flow.py
homeassistant/components/intesishome/climate.py
"""Support for Osram Lightify.""" import logging import random from lightify import Lightify import voluptuous as vol from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_EFFECT, ATTR_HS_COLOR, ATTR_TRANSITION, EFFECT_RANDOM, PLATFORM_SCHEMA, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP, SUPPORT_EFFECT, SUPPORT_TRANSITION, LightEntity, ) from homeassistant.const import CONF_HOST import homeassistant.helpers.config_validation as cv import homeassistant.util.color as color_util _LOGGER = logging.getLogger(__name__) CONF_ALLOW_LIGHTIFY_NODES = "allow_lightify_nodes" CONF_ALLOW_LIGHTIFY_GROUPS = "allow_lightify_groups" CONF_ALLOW_LIGHTIFY_SENSORS = "allow_lightify_sensors" CONF_ALLOW_LIGHTIFY_SWITCHES = "allow_lightify_switches" CONF_INTERVAL_LIGHTIFY_STATUS = "interval_lightify_status" CONF_INTERVAL_LIGHTIFY_CONF = "interval_lightify_conf" DEFAULT_ALLOW_LIGHTIFY_NODES = True DEFAULT_ALLOW_LIGHTIFY_GROUPS = True DEFAULT_ALLOW_LIGHTIFY_SENSORS = True DEFAULT_ALLOW_LIGHTIFY_SWITCHES = True DEFAULT_INTERVAL_LIGHTIFY_STATUS = 5 DEFAULT_INTERVAL_LIGHTIFY_CONF = 3600 PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_HOST): cv.string, vol.Optional( CONF_ALLOW_LIGHTIFY_NODES, default=DEFAULT_ALLOW_LIGHTIFY_NODES ): cv.boolean, vol.Optional( CONF_ALLOW_LIGHTIFY_GROUPS, default=DEFAULT_ALLOW_LIGHTIFY_GROUPS ): cv.boolean, vol.Optional( CONF_ALLOW_LIGHTIFY_SENSORS, default=DEFAULT_ALLOW_LIGHTIFY_SENSORS ): cv.boolean, vol.Optional( CONF_ALLOW_LIGHTIFY_SWITCHES, default=DEFAULT_ALLOW_LIGHTIFY_SWITCHES ): cv.boolean, vol.Optional( CONF_INTERVAL_LIGHTIFY_STATUS, default=DEFAULT_INTERVAL_LIGHTIFY_STATUS ): cv.positive_int, vol.Optional( CONF_INTERVAL_LIGHTIFY_CONF, default=DEFAULT_INTERVAL_LIGHTIFY_CONF ): cv.positive_int, } ) DEFAULT_BRIGHTNESS = 2 DEFAULT_KELVIN = 2700 def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Osram Lightify lights.""" host = config[CONF_HOST] try: bridge = Lightify(host, log_level=logging.NOTSET) except OSError as err: _LOGGER.exception("Error connecting to bridge: %s due to: %s", host, err) return setup_bridge(bridge, add_entities, config) def setup_bridge(bridge, add_entities, config): """Set up the Lightify bridge.""" lights = {} groups = {} groups_last_updated = [0] def update_lights(): """Update the lights objects with the latest info from the bridge.""" try: new_lights = bridge.update_all_light_status( config[CONF_INTERVAL_LIGHTIFY_STATUS] ) lights_changed = bridge.lights_changed() except TimeoutError: _LOGGER.error("Timeout during updating of lights") return 0 except OSError: _LOGGER.error("OSError during updating of lights") return 0 if new_lights and config[CONF_ALLOW_LIGHTIFY_NODES]: new_entities = [] for addr, light in new_lights.items(): if ( light.devicetype().name == "SENSOR" and not config[CONF_ALLOW_LIGHTIFY_SENSORS] ) or ( light.devicetype().name == "SWITCH" and not config[CONF_ALLOW_LIGHTIFY_SWITCHES] ): continue if addr not in lights: osram_light = OsramLightifyLight( light, update_lights, lights_changed ) lights[addr] = osram_light new_entities.append(osram_light) else: lights[addr].update_luminary(light) add_entities(new_entities) return lights_changed def update_groups(): """Update the groups objects with the latest info from the bridge.""" lights_changed = update_lights() try: bridge.update_scene_list(config[CONF_INTERVAL_LIGHTIFY_CONF]) new_groups = bridge.update_group_list(config[CONF_INTERVAL_LIGHTIFY_CONF]) groups_updated = bridge.groups_updated() except TimeoutError: _LOGGER.error("Timeout during updating of scenes/groups") return 0 except OSError: _LOGGER.error("OSError during updating of scenes/groups") return 0 if new_groups: new_groups = {group.idx(): group for group in new_groups.values()} new_entities = [] for idx, group in new_groups.items(): if idx not in groups: osram_group = OsramLightifyGroup( group, update_groups, groups_updated ) groups[idx] = osram_group new_entities.append(osram_group) else: groups[idx].update_luminary(group) add_entities(new_entities) if groups_updated > groups_last_updated[0]: groups_last_updated[0] = groups_updated for idx, osram_group in groups.items(): if idx not in new_groups: osram_group.update_static_attributes() return max(lights_changed, groups_updated) update_lights() if config[CONF_ALLOW_LIGHTIFY_GROUPS]: update_groups() class Luminary(LightEntity): """Representation of Luminary Lights and Groups.""" def __init__(self, luminary, update_func, changed): """Initialize a Luminary Light.""" self.update_func = update_func self._luminary = luminary self._changed = changed self._unique_id = None self._supported_features = [] self._effect_list = [] self._is_on = False self._available = True self._min_mireds = None self._max_mireds = None self._brightness = None self._color_temp = None self._rgb_color = None self._device_attributes = None self.update_static_attributes() self.update_dynamic_attributes() def _get_unique_id(self): """Get a unique ID (not implemented).""" raise NotImplementedError def _get_supported_features(self): """Get list of supported features.""" features = 0 if "lum" in self._luminary.supported_features(): features = features | SUPPORT_BRIGHTNESS | SUPPORT_TRANSITION if "temp" in self._luminary.supported_features(): features = features | SUPPORT_COLOR_TEMP | SUPPORT_TRANSITION if "rgb" in self._luminary.supported_features(): features = features | SUPPORT_COLOR | SUPPORT_TRANSITION | SUPPORT_EFFECT return features def _get_effect_list(self): """Get list of supported effects.""" effects = [] if "rgb" in self._luminary.supported_features(): effects.append(EFFECT_RANDOM) return effects @property def name(self): """Return the name of the luminary.""" return self._luminary.name() @property def hs_color(self): """Return last hs color value set.""" return color_util.color_RGB_to_hs(*self._rgb_color) @property def color_temp(self): """Return the color temperature.""" return self._color_temp @property def brightness(self): """Return brightness of the luminary (0..255).""" return self._brightness @property def is_on(self): """Return True if the device is on.""" return self._is_on @property def supported_features(self): """List of supported features.""" return self._supported_features @property def effect_list(self): """List of supported effects.""" return self._effect_list @property def min_mireds(self): """Return the coldest color_temp that this light supports.""" return self._min_mireds @property def max_mireds(self): """Return the warmest color_temp that this light supports.""" return self._max_mireds @property def unique_id(self): """Return a unique ID.""" return self._unique_id @property def device_state_attributes(self): """Return device specific state attributes.""" return self._device_attributes @property def available(self): """Return True if entity is available.""" return self._available def play_effect(self, effect, transition): """Play selected effect.""" if effect == EFFECT_RANDOM: self._rgb_color = ( random.randrange(0, 256), random.randrange(0, 256), random.randrange(0, 256), ) self._luminary.set_rgb(*self._rgb_color, transition) self._luminary.set_onoff(True) return True return False def turn_on(self, **kwargs): """Turn the device on.""" transition = int(kwargs.get(ATTR_TRANSITION, 0) * 10) if ATTR_EFFECT in kwargs: self.play_effect(kwargs[ATTR_EFFECT], transition) return if ATTR_HS_COLOR in kwargs: self._rgb_color = color_util.color_hs_to_RGB(*kwargs[ATTR_HS_COLOR]) self._luminary.set_rgb(*self._rgb_color, transition) if ATTR_COLOR_TEMP in kwargs: self._color_temp = kwargs[ATTR_COLOR_TEMP] self._luminary.set_temperature( int(color_util.color_temperature_mired_to_kelvin(self._color_temp)), transition, ) self._is_on = True if ATTR_BRIGHTNESS in kwargs: self._brightness = kwargs[ATTR_BRIGHTNESS] self._luminary.set_luminance(int(self._brightness / 2.55), transition) else: self._luminary.set_onoff(True) def turn_off(self, **kwargs): """Turn the device off.""" self._is_on = False if ATTR_TRANSITION in kwargs: transition = int(kwargs[ATTR_TRANSITION] * 10) self._brightness = DEFAULT_BRIGHTNESS self._luminary.set_luminance(0, transition) else: self._luminary.set_onoff(False) def update_luminary(self, luminary): """Update internal luminary object.""" self._luminary = luminary self.update_static_attributes() def update_static_attributes(self): """Update static attributes of the luminary.""" self._unique_id = self._get_unique_id() self._supported_features = self._get_supported_features() self._effect_list = self._get_effect_list() if self._supported_features & SUPPORT_COLOR_TEMP: self._min_mireds = color_util.color_temperature_kelvin_to_mired( self._luminary.max_temp() or DEFAULT_KELVIN ) self._max_mireds = color_util.color_temperature_kelvin_to_mired( self._luminary.min_temp() or DEFAULT_KELVIN ) def update_dynamic_attributes(self): """Update dynamic attributes of the luminary.""" self._is_on = self._luminary.on() self._available = self._luminary.reachable() and not self._luminary.deleted() if self._supported_features & SUPPORT_BRIGHTNESS: self._brightness = int(self._luminary.lum() * 2.55) if self._supported_features & SUPPORT_COLOR_TEMP: self._color_temp = color_util.color_temperature_kelvin_to_mired( self._luminary.temp() or DEFAULT_KELVIN ) if self._supported_features & SUPPORT_COLOR: self._rgb_color = self._luminary.rgb() def update(self): """Synchronize state with bridge.""" changed = self.update_func() if changed > self._changed: self._changed = changed self.update_dynamic_attributes() class OsramLightifyLight(Luminary): """Representation of an Osram Lightify Light.""" def _get_unique_id(self): """Get a unique ID.""" return self._luminary.addr() def update_static_attributes(self): """Update static attributes of the luminary.""" super().update_static_attributes() attrs = { "device_type": f"{self._luminary.type_id()} ({self._luminary.devicename()})", "firmware_version": self._luminary.version(), } if self._luminary.devicetype().name == "SENSOR": attrs["sensor_values"] = self._luminary.raw_values() self._device_attributes = attrs class OsramLightifyGroup(Luminary): """Representation of an Osram Lightify Group.""" def _get_unique_id(self): """Get a unique ID for the group.""" # Actually, it's a wrong choice for a unique ID, because a combination of # lights is NOT unique (Osram Lightify allows to create different groups # with the same lights). Also a combination of lights may easily change, # but the group remains the same from the user's perspective. # It should be something like "<gateway host>-<group.idx()>" # For now keeping it as is for backward compatibility with existing # users. return f"{self._luminary.lights()}" def _get_supported_features(self): """Get list of supported features.""" features = super()._get_supported_features() if self._luminary.scenes(): features = features | SUPPORT_EFFECT return features def _get_effect_list(self): """Get list of supported effects.""" effects = super()._get_effect_list() effects.extend(self._luminary.scenes()) return sorted(effects) def play_effect(self, effect, transition): """Play selected effect.""" if super().play_effect(effect, transition): return True if effect in self._luminary.scenes(): self._luminary.activate_scene(effect) return True return False def update_static_attributes(self): """Update static attributes of the luminary.""" super().update_static_attributes() self._device_attributes = {"lights": self._luminary.light_names()}
"""Define tests for the PlayStation 4 config flow.""" from pyps4_2ndscreen.errors import CredentialTimeout import pytest from homeassistant import data_entry_flow from homeassistant.components import ps4 from homeassistant.components.ps4.const import ( DEFAULT_ALIAS, DEFAULT_NAME, DEFAULT_REGION, DOMAIN, ) from homeassistant.const import ( CONF_CODE, CONF_HOST, CONF_IP_ADDRESS, CONF_NAME, CONF_REGION, CONF_TOKEN, ) from homeassistant.util import location from tests.async_mock import patch from tests.common import MockConfigEntry MOCK_TITLE = "PlayStation 4" MOCK_CODE = 12345678 MOCK_CODE_LEAD_0 = 1234567 MOCK_CODE_LEAD_0_STR = "01234567" MOCK_CREDS = "000aa000" MOCK_HOST = "192.0.0.0" MOCK_HOST_ADDITIONAL = "192.0.0.1" MOCK_DEVICE = { CONF_HOST: MOCK_HOST, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, } MOCK_DEVICE_ADDITIONAL = { CONF_HOST: MOCK_HOST_ADDITIONAL, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, } MOCK_CONFIG = { CONF_IP_ADDRESS: MOCK_HOST, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, CONF_CODE: MOCK_CODE, } MOCK_CONFIG_ADDITIONAL = { CONF_IP_ADDRESS: MOCK_HOST_ADDITIONAL, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, CONF_CODE: MOCK_CODE, } MOCK_DATA = {CONF_TOKEN: MOCK_CREDS, "devices": [MOCK_DEVICE]} MOCK_UDP_PORT = int(987) MOCK_TCP_PORT = int(997) MOCK_AUTO = {"Config Mode": "Auto Discover"} MOCK_MANUAL = {"Config Mode": "Manual Entry", CONF_IP_ADDRESS: MOCK_HOST} MOCK_LOCATION = location.LocationInfo( "0.0.0.0", "US", "United States", "CA", "California", "San Diego", "92122", "America/Los_Angeles", 32.8594, -117.2073, True, ) @pytest.fixture(name="location_info", autouse=True) def location_info_fixture(): """Mock location info.""" with patch( "homeassistant.components.ps4.config_flow.location.async_detect_location_info", return_value=MOCK_LOCATION, ): yield @pytest.fixture(name="ps4_setup", autouse=True) def ps4_setup_fixture(): """Patch ps4 setup entry.""" with patch( "homeassistant.components.ps4.async_setup_entry", return_value=True, ): yield async def test_full_flow_implementation(hass): """Test registering an implementation and flow works.""" # User Step Started, results in Step Creds with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # User Input results in created entry. with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert result["data"]["devices"] == [MOCK_DEVICE] assert result["title"] == MOCK_TITLE async def test_multiple_flow_implementation(hass): """Test multiple device flows.""" # User Step Started, results in Step Creds with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # User Input results in created entry. with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert result["data"]["devices"] == [MOCK_DEVICE] assert result["title"] == MOCK_TITLE # Check if entry exists. entries = hass.config_entries.async_entries() assert len(entries) == 1 # Check if there is a device config in entry. entry_1 = entries[0] assert len(entry_1.data["devices"]) == 1 # Test additional flow. # User Step Started, results in Step Mode: with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # Step Link with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ), patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert len(result["data"]["devices"]) == 1 assert result["title"] == MOCK_TITLE # Check if there are 2 entries. entries = hass.config_entries.async_entries() assert len(entries) == 2 # Check if there is device config in the last entry. entry_2 = entries[-1] assert len(entry_2.data["devices"]) == 1 # Check that entry 1 is different from entry 2. assert entry_1 is not entry_2 async def test_port_bind_abort(hass): """Test that flow aborted when cannot bind to ports 987, 997.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_UDP_PORT): reason = "port_987_bind_error" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == reason with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_TCP_PORT): reason = "port_997_bind_error" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == reason async def test_duplicate_abort(hass): """Test that Flow aborts when found devices already configured.""" MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA).add_to_hass(hass) with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_additional_device(hass): """Test that Flow can configure another device.""" # Mock existing entry. entry = MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA) entry.add_to_hass(hass) with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert len(result["data"]["devices"]) == 1 assert result["title"] == MOCK_TITLE async def test_0_pin(hass): """Test Pin with leading '0' is passed correctly.""" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "creds"}, data={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ), patch( "homeassistant.components.ps4.config_flow.location.async_detect_location_info", return_value=MOCK_LOCATION, ): result = await hass.config_entries.flow.async_configure( result["flow_id"], MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" mock_config = MOCK_CONFIG mock_config[CONF_CODE] = MOCK_CODE_LEAD_0 with patch( "pyps4_2ndscreen.Helper.link", return_value=(True, True) ) as mock_call, patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], mock_config ) mock_call.assert_called_once_with( MOCK_HOST, MOCK_CREDS, MOCK_CODE_LEAD_0_STR, DEFAULT_ALIAS ) async def test_no_devices_found_abort(hass): """Test that failure to find devices aborts flow.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch("pyps4_2ndscreen.Helper.has_devices", return_value=[]): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "no_devices_found" async def test_manual_mode(hass): """Test host specified in manual mode is passed to Step Link.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input: manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_MANUAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" async def test_credential_abort(hass): """Test that failure to get credentials aborts flow.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=None): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "credential_error" async def test_credential_timeout(hass): """Test that Credential Timeout shows error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", side_effect=CredentialTimeout): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" assert result["errors"] == {"base": "credential_timeout"} async def test_wrong_pin_error(hass): """Test that incorrect pin throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(True, False)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" assert result["errors"] == {"base": "login_failed"} async def test_device_connection_error(hass): """Test that device not connected or on throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(False, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" assert result["errors"] == {"base": "cannot_connect"} async def test_manual_mode_no_ip_error(hass): """Test no IP specified in manual mode throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={"Config Mode": "Manual Entry"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" assert result["errors"] == {CONF_IP_ADDRESS: "no_ipaddress"}
sdague/home-assistant
tests/components/ps4/test_config_flow.py
homeassistant/components/osramlightify/light.py
""" Support for the LIFX platform that implements lights. This is a legacy platform, included because the current lifx platform does not yet support Windows. """ import logging import liffylights import voluptuous as vol from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, ATTR_TRANSITION, PLATFORM_SCHEMA, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP, SUPPORT_TRANSITION, LightEntity, ) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.event import track_time_change from homeassistant.util.color import ( color_temperature_kelvin_to_mired, color_temperature_mired_to_kelvin, ) _LOGGER = logging.getLogger(__name__) BYTE_MAX = 255 CONF_BROADCAST = "broadcast" CONF_SERVER = "server" SHORT_MAX = 65535 TEMP_MAX = 9000 TEMP_MAX_HASS = 500 TEMP_MIN = 2500 TEMP_MIN_HASS = 154 SUPPORT_LIFX = ( SUPPORT_BRIGHTNESS | SUPPORT_COLOR_TEMP | SUPPORT_COLOR | SUPPORT_TRANSITION ) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( {vol.Optional(CONF_SERVER): cv.string, vol.Optional(CONF_BROADCAST): cv.string} ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the LIFX platform.""" server_addr = config.get(CONF_SERVER) broadcast_addr = config.get(CONF_BROADCAST) lifx_library = LIFX(add_entities, server_addr, broadcast_addr) # Register our poll service track_time_change(hass, lifx_library.poll, second=[10, 40]) lifx_library.probe() class LIFX: """Representation of a LIFX light.""" def __init__(self, add_entities_callback, server_addr=None, broadcast_addr=None): """Initialize the light.""" self._devices = [] self._add_entities_callback = add_entities_callback self._liffylights = liffylights.LiffyLights( self.on_device, self.on_power, self.on_color, server_addr, broadcast_addr ) def find_bulb(self, ipaddr): """Search for bulbs.""" bulb = None for device in self._devices: if device.ipaddr == ipaddr: bulb = device break return bulb def on_device(self, ipaddr, name, power, hue, sat, bri, kel): """Initialize the light.""" bulb = self.find_bulb(ipaddr) if bulb is None: _LOGGER.debug( "new bulb %s %s %d %d %d %d %d", ipaddr, name, power, hue, sat, bri, kel ) bulb = LIFXLight(self._liffylights, ipaddr, name, power, hue, sat, bri, kel) self._devices.append(bulb) self._add_entities_callback([bulb]) else: _LOGGER.debug( "update bulb %s %s %d %d %d %d %d", ipaddr, name, power, hue, sat, bri, kel, ) bulb.set_power(power) bulb.set_color(hue, sat, bri, kel) bulb.schedule_update_ha_state() def on_color(self, ipaddr, hue, sat, bri, kel): """Initialize the light.""" bulb = self.find_bulb(ipaddr) if bulb is not None: bulb.set_color(hue, sat, bri, kel) bulb.schedule_update_ha_state() def on_power(self, ipaddr, power): """Initialize the light.""" bulb = self.find_bulb(ipaddr) if bulb is not None: bulb.set_power(power) bulb.schedule_update_ha_state() def poll(self, now): """Set up polling for the light.""" self.probe() def probe(self, address=None): """Probe the light.""" self._liffylights.probe(address) class LIFXLight(LightEntity): """Representation of a LIFX light.""" def __init__(self, liffy, ipaddr, name, power, hue, saturation, brightness, kelvin): """Initialize the light.""" _LOGGER.debug("LIFXLight: %s %s", ipaddr, name) self._liffylights = liffy self._ip = ipaddr self.set_name(name) self.set_power(power) self.set_color(hue, saturation, brightness, kelvin) @property def should_poll(self): """No polling needed for LIFX light.""" return False @property def name(self): """Return the name of the device.""" return self._name @property def ipaddr(self): """Return the IP address of the device.""" return self._ip @property def hs_color(self): """Return the hs value.""" return (self._hue / 65535 * 360, self._sat / 65535 * 100) @property def brightness(self): """Return the brightness of this light between 0..255.""" brightness = int(self._bri / (BYTE_MAX + 1)) _LOGGER.debug("brightness: %d", brightness) return brightness @property def color_temp(self): """Return the color temperature.""" temperature = color_temperature_kelvin_to_mired(self._kel) _LOGGER.debug("color_temp: %d", temperature) return temperature @property def is_on(self): """Return true if device is on.""" _LOGGER.debug("is_on: %d", self._power) return self._power != 0 @property def supported_features(self): """Flag supported features.""" return SUPPORT_LIFX def turn_on(self, **kwargs): """Turn the device on.""" if ATTR_TRANSITION in kwargs: fade = int(kwargs[ATTR_TRANSITION] * 1000) else: fade = 0 if ATTR_HS_COLOR in kwargs: hue, saturation = kwargs[ATTR_HS_COLOR] hue = hue / 360 * 65535 saturation = saturation / 100 * 65535 else: hue = self._hue saturation = self._sat if ATTR_BRIGHTNESS in kwargs: brightness = kwargs[ATTR_BRIGHTNESS] * (BYTE_MAX + 1) else: brightness = self._bri if ATTR_COLOR_TEMP in kwargs: kelvin = int(color_temperature_mired_to_kelvin(kwargs[ATTR_COLOR_TEMP])) else: kelvin = self._kel _LOGGER.debug( "turn_on: %s (%d) %d %d %d %d %d", self._ip, self._power, hue, saturation, brightness, kelvin, fade, ) if self._power == 0: self._liffylights.set_color( self._ip, hue, saturation, brightness, kelvin, 0 ) self._liffylights.set_power(self._ip, 65535, fade) else: self._liffylights.set_color( self._ip, hue, saturation, brightness, kelvin, fade ) def turn_off(self, **kwargs): """Turn the device off.""" if ATTR_TRANSITION in kwargs: fade = int(kwargs[ATTR_TRANSITION] * 1000) else: fade = 0 _LOGGER.debug("turn_off: %s %d", self._ip, fade) self._liffylights.set_power(self._ip, 0, fade) def set_name(self, name): """Set name of the light.""" self._name = name def set_power(self, power): """Set power state value.""" _LOGGER.debug("set_power: %d", power) self._power = power != 0 def set_color(self, hue, sat, bri, kel): """Set color state values.""" self._hue = hue self._sat = sat self._bri = bri self._kel = kel
"""Define tests for the PlayStation 4 config flow.""" from pyps4_2ndscreen.errors import CredentialTimeout import pytest from homeassistant import data_entry_flow from homeassistant.components import ps4 from homeassistant.components.ps4.const import ( DEFAULT_ALIAS, DEFAULT_NAME, DEFAULT_REGION, DOMAIN, ) from homeassistant.const import ( CONF_CODE, CONF_HOST, CONF_IP_ADDRESS, CONF_NAME, CONF_REGION, CONF_TOKEN, ) from homeassistant.util import location from tests.async_mock import patch from tests.common import MockConfigEntry MOCK_TITLE = "PlayStation 4" MOCK_CODE = 12345678 MOCK_CODE_LEAD_0 = 1234567 MOCK_CODE_LEAD_0_STR = "01234567" MOCK_CREDS = "000aa000" MOCK_HOST = "192.0.0.0" MOCK_HOST_ADDITIONAL = "192.0.0.1" MOCK_DEVICE = { CONF_HOST: MOCK_HOST, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, } MOCK_DEVICE_ADDITIONAL = { CONF_HOST: MOCK_HOST_ADDITIONAL, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, } MOCK_CONFIG = { CONF_IP_ADDRESS: MOCK_HOST, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, CONF_CODE: MOCK_CODE, } MOCK_CONFIG_ADDITIONAL = { CONF_IP_ADDRESS: MOCK_HOST_ADDITIONAL, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, CONF_CODE: MOCK_CODE, } MOCK_DATA = {CONF_TOKEN: MOCK_CREDS, "devices": [MOCK_DEVICE]} MOCK_UDP_PORT = int(987) MOCK_TCP_PORT = int(997) MOCK_AUTO = {"Config Mode": "Auto Discover"} MOCK_MANUAL = {"Config Mode": "Manual Entry", CONF_IP_ADDRESS: MOCK_HOST} MOCK_LOCATION = location.LocationInfo( "0.0.0.0", "US", "United States", "CA", "California", "San Diego", "92122", "America/Los_Angeles", 32.8594, -117.2073, True, ) @pytest.fixture(name="location_info", autouse=True) def location_info_fixture(): """Mock location info.""" with patch( "homeassistant.components.ps4.config_flow.location.async_detect_location_info", return_value=MOCK_LOCATION, ): yield @pytest.fixture(name="ps4_setup", autouse=True) def ps4_setup_fixture(): """Patch ps4 setup entry.""" with patch( "homeassistant.components.ps4.async_setup_entry", return_value=True, ): yield async def test_full_flow_implementation(hass): """Test registering an implementation and flow works.""" # User Step Started, results in Step Creds with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # User Input results in created entry. with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert result["data"]["devices"] == [MOCK_DEVICE] assert result["title"] == MOCK_TITLE async def test_multiple_flow_implementation(hass): """Test multiple device flows.""" # User Step Started, results in Step Creds with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # User Input results in created entry. with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert result["data"]["devices"] == [MOCK_DEVICE] assert result["title"] == MOCK_TITLE # Check if entry exists. entries = hass.config_entries.async_entries() assert len(entries) == 1 # Check if there is a device config in entry. entry_1 = entries[0] assert len(entry_1.data["devices"]) == 1 # Test additional flow. # User Step Started, results in Step Mode: with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # Step Link with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ), patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert len(result["data"]["devices"]) == 1 assert result["title"] == MOCK_TITLE # Check if there are 2 entries. entries = hass.config_entries.async_entries() assert len(entries) == 2 # Check if there is device config in the last entry. entry_2 = entries[-1] assert len(entry_2.data["devices"]) == 1 # Check that entry 1 is different from entry 2. assert entry_1 is not entry_2 async def test_port_bind_abort(hass): """Test that flow aborted when cannot bind to ports 987, 997.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_UDP_PORT): reason = "port_987_bind_error" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == reason with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_TCP_PORT): reason = "port_997_bind_error" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == reason async def test_duplicate_abort(hass): """Test that Flow aborts when found devices already configured.""" MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA).add_to_hass(hass) with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_additional_device(hass): """Test that Flow can configure another device.""" # Mock existing entry. entry = MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA) entry.add_to_hass(hass) with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert len(result["data"]["devices"]) == 1 assert result["title"] == MOCK_TITLE async def test_0_pin(hass): """Test Pin with leading '0' is passed correctly.""" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "creds"}, data={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ), patch( "homeassistant.components.ps4.config_flow.location.async_detect_location_info", return_value=MOCK_LOCATION, ): result = await hass.config_entries.flow.async_configure( result["flow_id"], MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" mock_config = MOCK_CONFIG mock_config[CONF_CODE] = MOCK_CODE_LEAD_0 with patch( "pyps4_2ndscreen.Helper.link", return_value=(True, True) ) as mock_call, patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], mock_config ) mock_call.assert_called_once_with( MOCK_HOST, MOCK_CREDS, MOCK_CODE_LEAD_0_STR, DEFAULT_ALIAS ) async def test_no_devices_found_abort(hass): """Test that failure to find devices aborts flow.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch("pyps4_2ndscreen.Helper.has_devices", return_value=[]): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "no_devices_found" async def test_manual_mode(hass): """Test host specified in manual mode is passed to Step Link.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input: manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_MANUAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" async def test_credential_abort(hass): """Test that failure to get credentials aborts flow.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=None): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "credential_error" async def test_credential_timeout(hass): """Test that Credential Timeout shows error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", side_effect=CredentialTimeout): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" assert result["errors"] == {"base": "credential_timeout"} async def test_wrong_pin_error(hass): """Test that incorrect pin throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(True, False)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" assert result["errors"] == {"base": "login_failed"} async def test_device_connection_error(hass): """Test that device not connected or on throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(False, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" assert result["errors"] == {"base": "cannot_connect"} async def test_manual_mode_no_ip_error(hass): """Test no IP specified in manual mode throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={"Config Mode": "Manual Entry"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" assert result["errors"] == {CONF_IP_ADDRESS: "no_ipaddress"}
sdague/home-assistant
tests/components/ps4/test_config_flow.py
homeassistant/components/lifx_legacy/light.py
"""Plugwise Binary Sensor component for Home Assistant.""" import logging from homeassistant.components.binary_sensor import BinarySensorEntity from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.core import callback from .const import ( COORDINATOR, DOMAIN, FLAME_ICON, FLOW_OFF_ICON, FLOW_ON_ICON, IDLE_ICON, ) from .sensor import SmileSensor BINARY_SENSOR_MAP = { "dhw_state": ["Domestic Hot Water State", None], "slave_boiler_state": ["Secondary Heater Device State", None], } _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Smile binary_sensors from a config entry.""" api = hass.data[DOMAIN][config_entry.entry_id]["api"] coordinator = hass.data[DOMAIN][config_entry.entry_id][COORDINATOR] entities = [] all_devices = api.get_all_devices() for dev_id, device_properties in all_devices.items(): if device_properties["class"] != "heater_central": continue data = api.get_device_data(dev_id) for binary_sensor, dummy in BINARY_SENSOR_MAP.items(): if binary_sensor not in data: continue entities.append( PwBinarySensor( api, coordinator, device_properties["name"], binary_sensor, dev_id, device_properties["class"], ) ) async_add_entities(entities, True) class PwBinarySensor(SmileSensor, BinarySensorEntity): """Representation of a Plugwise binary_sensor.""" def __init__(self, api, coordinator, name, binary_sensor, dev_id, model): """Set up the Plugwise API.""" super().__init__(api, coordinator, name, dev_id, binary_sensor) self._binary_sensor = binary_sensor self._is_on = False self._icon = None self._unique_id = f"{dev_id}-{binary_sensor}" @property def is_on(self): """Return true if the binary sensor is on.""" return self._is_on @property def icon(self): """Return the icon to use in the frontend.""" return self._icon @callback def _async_process_data(self): """Update the entity.""" data = self._api.get_device_data(self._dev_id) if not data: _LOGGER.error("Received no data for device %s", self._binary_sensor) self.async_write_ha_state() return if self._binary_sensor not in data: self.async_write_ha_state() return self._is_on = data[self._binary_sensor] self._state = STATE_OFF if self._binary_sensor == "dhw_state": self._icon = FLOW_OFF_ICON if self._binary_sensor == "slave_boiler_state": self._icon = IDLE_ICON if self._is_on: self._state = STATE_ON if self._binary_sensor == "dhw_state": self._icon = FLOW_ON_ICON if self._binary_sensor == "slave_boiler_state": self._icon = FLAME_ICON self.async_write_ha_state()
"""Define tests for the PlayStation 4 config flow.""" from pyps4_2ndscreen.errors import CredentialTimeout import pytest from homeassistant import data_entry_flow from homeassistant.components import ps4 from homeassistant.components.ps4.const import ( DEFAULT_ALIAS, DEFAULT_NAME, DEFAULT_REGION, DOMAIN, ) from homeassistant.const import ( CONF_CODE, CONF_HOST, CONF_IP_ADDRESS, CONF_NAME, CONF_REGION, CONF_TOKEN, ) from homeassistant.util import location from tests.async_mock import patch from tests.common import MockConfigEntry MOCK_TITLE = "PlayStation 4" MOCK_CODE = 12345678 MOCK_CODE_LEAD_0 = 1234567 MOCK_CODE_LEAD_0_STR = "01234567" MOCK_CREDS = "000aa000" MOCK_HOST = "192.0.0.0" MOCK_HOST_ADDITIONAL = "192.0.0.1" MOCK_DEVICE = { CONF_HOST: MOCK_HOST, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, } MOCK_DEVICE_ADDITIONAL = { CONF_HOST: MOCK_HOST_ADDITIONAL, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, } MOCK_CONFIG = { CONF_IP_ADDRESS: MOCK_HOST, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, CONF_CODE: MOCK_CODE, } MOCK_CONFIG_ADDITIONAL = { CONF_IP_ADDRESS: MOCK_HOST_ADDITIONAL, CONF_NAME: DEFAULT_NAME, CONF_REGION: DEFAULT_REGION, CONF_CODE: MOCK_CODE, } MOCK_DATA = {CONF_TOKEN: MOCK_CREDS, "devices": [MOCK_DEVICE]} MOCK_UDP_PORT = int(987) MOCK_TCP_PORT = int(997) MOCK_AUTO = {"Config Mode": "Auto Discover"} MOCK_MANUAL = {"Config Mode": "Manual Entry", CONF_IP_ADDRESS: MOCK_HOST} MOCK_LOCATION = location.LocationInfo( "0.0.0.0", "US", "United States", "CA", "California", "San Diego", "92122", "America/Los_Angeles", 32.8594, -117.2073, True, ) @pytest.fixture(name="location_info", autouse=True) def location_info_fixture(): """Mock location info.""" with patch( "homeassistant.components.ps4.config_flow.location.async_detect_location_info", return_value=MOCK_LOCATION, ): yield @pytest.fixture(name="ps4_setup", autouse=True) def ps4_setup_fixture(): """Patch ps4 setup entry.""" with patch( "homeassistant.components.ps4.async_setup_entry", return_value=True, ): yield async def test_full_flow_implementation(hass): """Test registering an implementation and flow works.""" # User Step Started, results in Step Creds with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # User Input results in created entry. with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert result["data"]["devices"] == [MOCK_DEVICE] assert result["title"] == MOCK_TITLE async def test_multiple_flow_implementation(hass): """Test multiple device flows.""" # User Step Started, results in Step Creds with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # User Input results in created entry. with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert result["data"]["devices"] == [MOCK_DEVICE] assert result["title"] == MOCK_TITLE # Check if entry exists. entries = hass.config_entries.async_entries() assert len(entries) == 1 # Check if there is a device config in entry. entry_1 = entries[0] assert len(entry_1.data["devices"]) == 1 # Test additional flow. # User Step Started, results in Step Mode: with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None), patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" # Step Creds results with form in Step Mode. with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input which is not manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" # Step Link with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ), patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert len(result["data"]["devices"]) == 1 assert result["title"] == MOCK_TITLE # Check if there are 2 entries. entries = hass.config_entries.async_entries() assert len(entries) == 2 # Check if there is device config in the last entry. entry_2 = entries[-1] assert len(entry_2.data["devices"]) == 1 # Check that entry 1 is different from entry 2. assert entry_1 is not entry_2 async def test_port_bind_abort(hass): """Test that flow aborted when cannot bind to ports 987, 997.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_UDP_PORT): reason = "port_987_bind_error" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == reason with patch("pyps4_2ndscreen.Helper.port_bind", return_value=MOCK_TCP_PORT): reason = "port_997_bind_error" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == reason async def test_duplicate_abort(hass): """Test that Flow aborts when found devices already configured.""" MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA).add_to_hass(hass) with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured" async def test_additional_device(hass): """Test that Flow can configure another device.""" # Mock existing entry. entry = MockConfigEntry(domain=ps4.DOMAIN, data=MOCK_DATA) entry.add_to_hass(hass) with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}, {"host-ip": MOCK_HOST_ADDITIONAL}], ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(True, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG_ADDITIONAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_TOKEN] == MOCK_CREDS assert len(result["data"]["devices"]) == 1 assert result["title"] == MOCK_TITLE async def test_0_pin(hass): """Test Pin with leading '0' is passed correctly.""" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "creds"}, data={}, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ), patch( "homeassistant.components.ps4.config_flow.location.async_detect_location_info", return_value=MOCK_LOCATION, ): result = await hass.config_entries.flow.async_configure( result["flow_id"], MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" mock_config = MOCK_CONFIG mock_config[CONF_CODE] = MOCK_CODE_LEAD_0 with patch( "pyps4_2ndscreen.Helper.link", return_value=(True, True) ) as mock_call, patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], mock_config ) mock_call.assert_called_once_with( MOCK_HOST, MOCK_CREDS, MOCK_CODE_LEAD_0_STR, DEFAULT_ALIAS ) async def test_no_devices_found_abort(hass): """Test that failure to find devices aborts flow.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch("pyps4_2ndscreen.Helper.has_devices", return_value=[]): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "no_devices_found" async def test_manual_mode(hass): """Test host specified in manual mode is passed to Step Link.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" # Step Mode with User Input: manual, results in Step Link. with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_MANUAL ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" async def test_credential_abort(hass): """Test that failure to get credentials aborts flow.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=None): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "credential_error" async def test_credential_timeout(hass): """Test that Credential Timeout shows error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", side_effect=CredentialTimeout): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" assert result["errors"] == {"base": "credential_timeout"} async def test_wrong_pin_error(hass): """Test that incorrect pin throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(True, False)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" assert result["errors"] == {"base": "login_failed"} async def test_device_connection_error(hass): """Test that device not connected or on throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" with patch( "pyps4_2ndscreen.Helper.has_devices", return_value=[{"host-ip": MOCK_HOST}] ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_AUTO ) with patch("pyps4_2ndscreen.Helper.link", return_value=(False, True)): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_CONFIG ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "link" assert result["errors"] == {"base": "cannot_connect"} async def test_manual_mode_no_ip_error(hass): """Test no IP specified in manual mode throws an error.""" with patch("pyps4_2ndscreen.Helper.port_bind", return_value=None): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "creds" with patch("pyps4_2ndscreen.Helper.get_creds", return_value=MOCK_CREDS): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={"Config Mode": "Manual Entry"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "mode" assert result["errors"] == {CONF_IP_ADDRESS: "no_ipaddress"}
sdague/home-assistant
tests/components/ps4/test_config_flow.py
homeassistant/components/plugwise/binary_sensor.py