async def test_dock_vacuum(hass): """Test dock trait support for vacuum domain.""" assert helpers.get_google_type(vacuum.DOMAIN, None) is not None assert trait.DockTrait.supported(vacuum.DOMAIN, 0, None) trt = trait.DockTrait(hass, State('vacuum.bla', vacuum.STATE_IDLE), BASIC_CONFIG) assert trt.sync_attributes() == {} assert trt.query_attributes() == {'isDocked': False} calls = async_mock_service(hass, vacuum.DOMAIN, vacuum.SERVICE_RETURN_TO_BASE) await trt.execute(trait.COMMAND_DOCK, BASIC_DATA, {}, {}) assert len(calls) == 1 assert calls[0].data == { ATTR_ENTITY_ID: 'vacuum.bla', }
def to_native(self): """Convert to an HA state object.""" context = Context(id=self.context_id, user_id=self.context_user_id) try: return State( self.entity_id, self.state, json.loads(self.attributes), _process_timestamp(self.last_changed), _process_timestamp(self.last_updated), context=context, # Temp, because database can still store invalid entity IDs # Remove with 1.0 or in 2020. temp_invalid_id_bypass=True, ) except ValueError: # When json.loads fails _LOGGER.exception("Error converting row to state: %s", self) return None
async def test_google_config_expose_entity_prefs(mock_conf, cloud_prefs): """Test Google config should expose using prefs.""" entity_conf = {"should_expose": False} await cloud_prefs.async_update( google_entity_configs={"light.kitchen": entity_conf}, google_default_expose=["light"], ) state = State("light.kitchen", "on") assert not mock_conf.should_expose(state) entity_conf["should_expose"] = True assert mock_conf.should_expose(state) entity_conf["should_expose"] = None assert mock_conf.should_expose(state) await cloud_prefs.async_update(google_default_expose=["sensor"], ) assert not mock_conf.should_expose(state)
async def test_temperature_setting_climate_onoff(hass): """Test TemperatureSetting trait support for climate domain - range.""" assert helpers.get_google_type(climate.DOMAIN, None) is not None assert not trait.TemperatureSettingTrait.supported(climate.DOMAIN, 0, None) assert trait.TemperatureSettingTrait.supported( climate.DOMAIN, climate.SUPPORT_OPERATION_MODE, None) hass.config.units.temperature_unit = TEMP_FAHRENHEIT trt = trait.TemperatureSettingTrait(hass, State( 'climate.bla', climate.STATE_AUTO, { ATTR_SUPPORTED_FEATURES: ( climate.SUPPORT_OPERATION_MODE | climate.SUPPORT_ON_OFF | climate.SUPPORT_TARGET_TEMPERATURE_HIGH | climate.SUPPORT_TARGET_TEMPERATURE_LOW), climate.ATTR_OPERATION_MODE: climate.STATE_COOL, climate.ATTR_OPERATION_LIST: [ climate.STATE_COOL, climate.STATE_HEAT, climate.STATE_AUTO, ], climate.ATTR_MIN_TEMP: None, climate.ATTR_MAX_TEMP: None, }), BASIC_CONFIG) assert trt.sync_attributes() == { 'availableThermostatModes': 'off,on,cool,heat,heatcool', 'thermostatTemperatureUnit': 'F', } assert trt.can_execute(trait.COMMAND_THERMOSTAT_SET_MODE, {}) calls = async_mock_service( hass, climate.DOMAIN, SERVICE_TURN_ON) await trt.execute(trait.COMMAND_THERMOSTAT_SET_MODE, BASIC_DATA, { 'thermostatMode': 'on', }, {}) assert len(calls) == 1 calls = async_mock_service( hass, climate.DOMAIN, SERVICE_TURN_OFF) await trt.execute(trait.COMMAND_THERMOSTAT_SET_MODE, BASIC_DATA, { 'thermostatMode': 'off', }, {}) assert len(calls) == 1
async def test_scene_script(hass): """Test Scene trait support for script domain.""" assert trait.SceneTrait.supported(script.DOMAIN, 0) trt = trait.SceneTrait(hass, State('script.bla', STATE_OFF)) assert trt.sync_attributes() == {} assert trt.query_attributes() == {} assert trt.can_execute(trait.COMMAND_ACTIVATE_SCENE, {}) calls = async_mock_service(hass, script.DOMAIN, SERVICE_TURN_ON) await trt.execute(trait.COMMAND_ACTIVATE_SCENE, {}) # We don't wait till script execution is done. await hass.async_block_till_done() assert len(calls) == 1 assert calls[0].data == { ATTR_ENTITY_ID: 'script.bla', }
async def async_reproduce_states(hass: HomeAssistantType, states: Iterable[State], context: Optional[Context] = None) -> None: """Reproduce component states.""" from . import get_entity_ids from homeassistant.helpers.state import async_reproduce_state states_copy = [] for state in states: members = get_entity_ids(hass, state.entity_id) for member in members: states_copy.append( State(member, state.state, state.attributes, last_changed=state.last_changed, last_updated=state.last_updated, context=state.context)) await async_reproduce_state(hass, states_copy, blocking=True, context=context)
async def test_attribute(hass, service, attribute): """Test that service call is made for each attribute.""" hass.states.async_set(ENTITY_1, STATE_ON, {}) turn_on_calls = async_mock_service(hass, DOMAIN, SERVICE_TURN_ON) turn_off_calls = async_mock_service(hass, DOMAIN, SERVICE_TURN_OFF) calls_1 = async_mock_service(hass, DOMAIN, service) value = "dummy" await async_reproduce_states( hass, [State(ENTITY_1, STATE_ON, {attribute: value})]) await hass.async_block_till_done() assert len(turn_on_calls) == 0 assert len(turn_off_calls) == 0 assert len(calls_1) == 1 assert calls_1[0].data == {"entity_id": ENTITY_1, attribute: value}
async def test_attribute(hass, service, attribute, supported_feature): """Test that service call is made for each attribute.""" hass.states.async_set( ENTITY_1, "something", {ATTR_SUPPORTED_FEATURES: supported_feature}, ) calls_1 = async_mock_service(hass, DOMAIN, service) value = "dummy" await async_reproduce_states(hass, [State(ENTITY_1, None, {attribute: value})]) await hass.async_block_till_done() assert len(calls_1) == 1 assert calls_1[0].data == {"entity_id": ENTITY_1, attribute: value}
async def test_openclose_cover_no_position(hass): """Test OpenClose trait support for cover domain.""" assert helpers.get_google_type(cover.DOMAIN, None) is not None assert trait.OpenCloseTrait.supported(cover.DOMAIN, cover.SUPPORT_SET_POSITION, None) trt = trait.OpenCloseTrait(hass, State('cover.bla', cover.STATE_OPEN, {}), BASIC_CONFIG) assert trt.sync_attributes() == {} assert trt.query_attributes() == {'openPercent': 100} calls = async_mock_service(hass, cover.DOMAIN, cover.SERVICE_CLOSE_COVER) await trt.execute(trait.COMMAND_OPENCLOSE, BASIC_DATA, {'openPercent': 0}, {}) assert len(calls) == 1 assert calls[0].data == { ATTR_ENTITY_ID: 'cover.bla', }
async def test_reproducing_states(hass: HomeAssistant, caplog: pytest.LogCaptureFixture) -> None: """Test reproducing NEW_NAME states.""" hass.states.async_set("NEW_DOMAIN.entity_off", "off", {}) hass.states.async_set("NEW_DOMAIN.entity_on", "on", {"color": "red"}) turn_on_calls = async_mock_service(hass, "NEW_DOMAIN", "turn_on") turn_off_calls = async_mock_service(hass, "NEW_DOMAIN", "turn_off") # These calls should do nothing as entities already in desired state await hass.helpers.state.async_reproduce_state( [ State("NEW_DOMAIN.entity_off", "off"), State("NEW_DOMAIN.entity_on", "on", {"color": "red"}), ], blocking=True, ) assert len(turn_on_calls) == 0 assert len(turn_off_calls) == 0 # Test invalid state is handled await hass.helpers.state.async_reproduce_state( [State("NEW_DOMAIN.entity_off", "not_supported")], blocking=True) assert "not_supported" in caplog.text assert len(turn_on_calls) == 0 assert len(turn_off_calls) == 0 # Make sure correct services are called await hass.helpers.state.async_reproduce_state( [ State("NEW_DOMAIN.entity_on", "off"), State("NEW_DOMAIN.entity_off", "on", {"color": "red"}), # Should not raise State("NEW_DOMAIN.non_existing", "on"), ], blocking=True, ) assert len(turn_on_calls) == 1 assert turn_on_calls[0].domain == "NEW_DOMAIN" assert turn_on_calls[0].data == { "entity_id": "NEW_DOMAIN.entity_off", "color": "red", } assert len(turn_off_calls) == 1 assert turn_off_calls[0].domain == "NEW_DOMAIN" assert turn_off_calls[0].data == {"entity_id": "NEW_DOMAIN.entity_on"}
async def test_number_restore_and_respond(hass: HomeAssistant, knx: KNXTestKit): """Test KNX number with passive_address and respond_to_read restoring state.""" test_address = "1/1/1" test_passive_address = "3/3/3" RESTORE_DATA = { "native_max_value": None, # Ignored by KNX number "native_min_value": None, # Ignored by KNX number "native_step": None, # Ignored by KNX number "native_unit_of_measurement": None, # Ignored by KNX number "native_value": 160.0, } mock_restore_cache_with_extra_data( hass, ((State("number.test", "abc"), RESTORE_DATA), )) await knx.setup_integration({ NumberSchema.PLATFORM: { CONF_NAME: "test", KNX_ADDRESS: [test_address, test_passive_address], CONF_RESPOND_TO_READ: True, CONF_TYPE: "illuminance", } }) # restored state - doesn't send telegram state = hass.states.get("number.test") assert state.state == "160.0" assert state.attributes.get("unit_of_measurement") == "lx" await knx.assert_telegram_count(0) # respond with restored state await knx.receive_read(test_address) await knx.assert_response(test_address, (0x1F, 0xD0)) # don't respond to passive address await knx.receive_read(test_passive_address) await knx.assert_no_telegram() # update from KNX passive address await knx.receive_write(test_passive_address, (0x4E, 0xDE)) state = hass.states.get("number.test") assert state.state == "9000.96"
async def test_startstop_vacuum(hass): """Test startStop trait support for vacuum domain.""" assert helpers.get_google_type(vacuum.DOMAIN, None) is not None assert trait.StartStopTrait.supported(vacuum.DOMAIN, 0, None) trt = trait.StartStopTrait( hass, State( "vacuum.bla", vacuum.STATE_PAUSED, {ATTR_SUPPORTED_FEATURES: vacuum.SUPPORT_PAUSE}, ), BASIC_CONFIG, ) assert trt.sync_attributes() == {"pausable": True} assert trt.query_attributes() == {"isRunning": False, "isPaused": True} start_calls = async_mock_service(hass, vacuum.DOMAIN, vacuum.SERVICE_START) await trt.execute(trait.COMMAND_STARTSTOP, BASIC_DATA, {"start": True}, {}) assert len(start_calls) == 1 assert start_calls[0].data == {ATTR_ENTITY_ID: "vacuum.bla"} stop_calls = async_mock_service(hass, vacuum.DOMAIN, vacuum.SERVICE_STOP) await trt.execute(trait.COMMAND_STARTSTOP, BASIC_DATA, {"start": False}, {}) assert len(stop_calls) == 1 assert stop_calls[0].data == {ATTR_ENTITY_ID: "vacuum.bla"} pause_calls = async_mock_service(hass, vacuum.DOMAIN, vacuum.SERVICE_PAUSE) await trt.execute(trait.COMMAND_PAUSEUNPAUSE, BASIC_DATA, {"pause": True}, {}) assert len(pause_calls) == 1 assert pause_calls[0].data == {ATTR_ENTITY_ID: "vacuum.bla"} unpause_calls = async_mock_service(hass, vacuum.DOMAIN, vacuum.SERVICE_START) await trt.execute(trait.COMMAND_PAUSEUNPAUSE, BASIC_DATA, {"pause": False}, {}) assert len(unpause_calls) == 1 assert unpause_calls[0].data == {ATTR_ENTITY_ID: "vacuum.bla"}
async def test_reproduce_group(hass): """Test reproduce_state with group.""" context = Context() def clone_state(state, entity_id): """Return a cloned state with different entity_id.""" return State( entity_id, state.state, state.attributes, last_changed=state.last_changed, last_updated=state.last_updated, context=state.context, ) with patch("homeassistant.helpers.state.async_reproduce_state") as fun: fun.return_value = Future() fun.return_value.set_result(None) hass.states.async_set( "group.test", "off", {"entity_id": ["light.test1", "light.test2", "switch.test1"]}, ) hass.states.async_set("light.test1", "off") hass.states.async_set("light.test2", "off") hass.states.async_set("switch.test1", "off") state = State("group.test", "on") await async_reproduce_states(hass, [state], context) fun.assert_called_once_with( hass, [ clone_state(state, "light.test1"), clone_state(state, "light.test2"), clone_state(state, "switch.test1"), ], blocking=True, context=context, )
async def test_select_dpt_2_restore(hass: HomeAssistant, knx: KNXTestKit): """Test KNX select with passive_address and respond_to_read restoring state.""" _options = [ { CONF_PAYLOAD: 0b00, SelectSchema.CONF_OPTION: "No control" }, { CONF_PAYLOAD: 0b10, SelectSchema.CONF_OPTION: "Control - Off" }, { CONF_PAYLOAD: 0b11, SelectSchema.CONF_OPTION: "Control - On" }, ] test_address = "1/1/1" test_passive_address = "3/3/3" fake_state = State("select.test", "Control - On") mock_restore_cache(hass, (fake_state, )) await knx.setup_integration({ SelectSchema.PLATFORM: { CONF_NAME: "test", KNX_ADDRESS: [test_address, test_passive_address], CONF_RESPOND_TO_READ: True, CONF_PAYLOAD_LENGTH: 0, SelectSchema.CONF_OPTIONS: _options, } }) # restored state - doesn't send telegram state = hass.states.get("select.test") assert state.state == "Control - On" await knx.assert_telegram_count(0) # respond with restored state await knx.receive_read(test_address) await knx.assert_response(test_address, 3) # don't respond to passive address await knx.receive_read(test_passive_address) await knx.assert_no_telegram()
async def test_color_spectrum_light(hass): """Test ColorSpectrum trait support for light domain.""" assert not trait.ColorSpectrumTrait.supported(light.DOMAIN, 0) assert trait.ColorSpectrumTrait.supported(light.DOMAIN, light.SUPPORT_COLOR) trt = trait.ColorSpectrumTrait(hass, State('light.bla', STATE_ON, { light.ATTR_HS_COLOR: (0, 94), }), BASIC_CONFIG) assert trt.sync_attributes() == { 'colorModel': 'rgb' } assert trt.query_attributes() == { 'color': { 'spectrumRGB': 16715535 } } assert not trt.can_execute(trait.COMMAND_COLOR_ABSOLUTE, { 'color': { 'temperature': 400 } }) assert trt.can_execute(trait.COMMAND_COLOR_ABSOLUTE, { 'color': { 'spectrumRGB': 16715792 } }) calls = async_mock_service(hass, light.DOMAIN, SERVICE_TURN_ON) await trt.execute(trait.COMMAND_COLOR_ABSOLUTE, BASIC_DATA, { 'color': { 'spectrumRGB': 1052927 } }) assert len(calls) == 1 assert calls[0].data == { ATTR_ENTITY_ID: 'light.bla', light.ATTR_HS_COLOR: (240, 93.725), }
async def test_startstop_vacuum(hass): """Test startStop trait support for vacuum domain.""" assert trait.StartStopTrait.supported(vacuum.DOMAIN, 0) trt = trait.StartStopTrait( hass, State('vacuum.bla', vacuum.STATE_PAUSED, { ATTR_SUPPORTED_FEATURES: vacuum.SUPPORT_PAUSE, }), BASIC_CONFIG) assert trt.sync_attributes() == {'pausable': True} assert trt.query_attributes() == {'isRunning': False, 'isPaused': True} start_calls = async_mock_service(hass, vacuum.DOMAIN, vacuum.SERVICE_START) await trt.execute(trait.COMMAND_STARTSTOP, {'start': True}) assert len(start_calls) == 1 assert start_calls[0].data == { ATTR_ENTITY_ID: 'vacuum.bla', } stop_calls = async_mock_service(hass, vacuum.DOMAIN, vacuum.SERVICE_STOP) await trt.execute(trait.COMMAND_STARTSTOP, {'start': False}) assert len(stop_calls) == 1 assert stop_calls[0].data == { ATTR_ENTITY_ID: 'vacuum.bla', } pause_calls = async_mock_service(hass, vacuum.DOMAIN, vacuum.SERVICE_PAUSE) await trt.execute(trait.COMMAND_PAUSEUNPAUSE, {'pause': True}) assert len(pause_calls) == 1 assert pause_calls[0].data == { ATTR_ENTITY_ID: 'vacuum.bla', } unpause_calls = async_mock_service(hass, vacuum.DOMAIN, vacuum.SERVICE_START) await trt.execute(trait.COMMAND_PAUSEUNPAUSE, {'pause': False}) assert len(unpause_calls) == 1 assert unpause_calls[0].data == { ATTR_ENTITY_ID: 'vacuum.bla', }
def test_state_changed_event_sends_message(self, mock_utcnow, mock_pub): """Test the sending of a new message if event changed.""" now = dt_util.as_utc(dt_util.now()) e_id = 'fake.entity' pub_topic = 'bar' mock_utcnow.return_value = now # Add the eventstream component for publishing events assert self.add_eventstream(pub_topic=pub_topic) self.hass.block_till_done() # Reset the mock because it will have already gotten calls for the # mqtt_eventstream state change on initialization, etc. mock_pub.reset_mock() # Set a state of an entity mock_state_change_event(self.hass, State(e_id, 'on')) self.hass.block_till_done() # The order of the JSON is indeterminate, # so first just check that publish was called mock_pub.assert_called_with(self.hass, pub_topic, ANY) assert mock_pub.called # Get the actual call to publish and make sure it was the one # we were looking for msg = mock_pub.call_args[0][2] event = {} event['event_type'] = EVENT_STATE_CHANGED new_state = { "last_updated": now.isoformat(), "state": "on", "entity_id": e_id, "attributes": {}, "last_changed": now.isoformat(), } event['event_data'] = {"new_state": new_state, "entity_id": e_id} # Verify that the message received was that expected result = json.loads(msg) result['event_data']['new_state'].pop('context') assert result == event
async def test_state_with_context(hass): """Test that context is forwarded.""" hass.states.async_set( ENTITY_1, "something", {ATTR_SUPPORTED_FEATURES: MediaPlayerEntityFeature.TURN_ON}, ) calls = async_mock_service(hass, DOMAIN, SERVICE_TURN_ON) context = Context() await async_reproduce_states(hass, [State(ENTITY_1, "on")], context=context) await hass.async_block_till_done() assert len(calls) == 1 assert calls[0].data == {"entity_id": ENTITY_1} assert calls[0].context == context
def test_restore_state(hass): """Ensure states are restored on startup.""" mock_restore_cache( hass, (State('climate.test_thermostat', '0', {ATTR_TEMPERATURE: "20"}), )) hass.state = CoreState.starting yield from async_setup_component( hass, climate.DOMAIN, { 'climate': { 'platform': 'generic_thermostat', 'name': 'test_thermostat', 'heater': ENT_SWITCH, 'target_sensor': ENT_SENSOR, } }) state = hass.states.get('climate.test_thermostat') assert (state.attributes[ATTR_TEMPERATURE] == 20)
async def test_attribute_no_state(hass): """Test that no state service call is made with none state.""" calls_1 = async_mock_service(hass, DOMAIN, SERVICE_TURN_ON) calls_2 = async_mock_service(hass, DOMAIN, SERVICE_TURN_OFF) calls_3 = async_mock_service(hass, DOMAIN, SERVICE_SET_OPERATION_MODE) value = "dummy" await async_reproduce_states( hass, [State(ENTITY_1, None, {ATTR_OPERATION_MODE: value})]) await hass.async_block_till_done() assert len(calls_1) == 0 assert len(calls_2) == 0 assert len(calls_3) == 1 assert calls_3[0].data == { 'entity_id': ENTITY_1, ATTR_OPERATION_MODE: value }
async def test_restore_state_last_off(hass): """Test restoring state when the last state is off.""" mock_restore_cache(hass, [State("switch.flux", "off")]) assert await async_setup_component( hass, "switch", { "switch": { "platform": "flux", "name": "flux", "lights": ["light.desk", "light.lamp"], } }, ) await hass.async_block_till_done() state = hass.states.get("switch.flux") assert state assert state.state == "off"
def test_state_changed_event_sends_message(self, mock_utcnow, mock_pub): """Test the sending of a new message if event changed.""" e_id = "fake.entity" base_topic = "pub" # Add the statestream component for publishing state updates assert self.add_statestream(base_topic=base_topic) self.hass.block_till_done() # Reset the mock because it will have already gotten calls for the # mqtt_statestream state change on initialization, etc. mock_pub.reset_mock() # Set a state of an entity mock_state_change_event(self.hass, State(e_id, "on")) self.hass.block_till_done() # Make sure 'on' was published to pub/fake/entity/state mock_pub.assert_called_with(self.hass, "pub/fake/entity/state", "on", 1, True) assert mock_pub.called
async def test_list_alexa_entities(hass, hass_ws_client, setup_api, mock_cloud_login): """Test that we can list Alexa entities.""" client = await hass_ws_client(hass) entity = LightCapabilities( hass, MagicMock(entity_config={}), State("light.kitchen", "on") ) with patch( "homeassistant.components.alexa.entities" ".async_get_entities", return_value=[entity], ): await client.send_json({"id": 5, "type": "cloud/alexa/entities"}) response = await client.receive_json() assert response["success"] assert len(response["result"]) == 1 assert response["result"][0] == { "entity_id": "light.kitchen", "display_categories": ["LIGHT"], "interfaces": ["Alexa.PowerController", "Alexa.EndpointHealth"], }
async def test_list_google_entities(hass, hass_ws_client, setup_api, mock_cloud_login): """Test that we can list Google entities.""" client = await hass_ws_client(hass) entity = GoogleEntity( hass, MockConfig(should_expose=lambda *_: False), State("light.kitchen", "on") ) with patch( "homeassistant.components.google_assistant.helpers" ".async_get_entities", return_value=[entity], ): await client.send_json({"id": 5, "type": "cloud/google_assistant/entities"}) response = await client.receive_json() assert response["success"] assert len(response["result"]) == 1 assert response["result"][0] == { "entity_id": "light.kitchen", "might_2fa": False, "traits": ["action.devices.traits.OnOff"], }
async def test_brightness_light(hass): """Test brightness trait support for light domain.""" assert trait.BrightnessTrait.supported(light.DOMAIN, light.SUPPORT_BRIGHTNESS) trt = trait.BrightnessTrait( hass, State('light.bla', light.STATE_ON, {light.ATTR_BRIGHTNESS: 243}), BASIC_CONFIG) assert trt.sync_attributes() == {} assert trt.query_attributes() == {'brightness': 95} calls = async_mock_service(hass, light.DOMAIN, light.SERVICE_TURN_ON) await trt.execute(trait.COMMAND_BRIGHTNESS_ABSOLUTE, {'brightness': 50}) assert len(calls) == 1 assert calls[0].data == { ATTR_ENTITY_ID: 'light.bla', light.ATTR_BRIGHTNESS_PCT: 50 }
async def test_lock_unlock_lock(hass): """Test LockUnlock trait locking support for lock domain.""" assert trait.LockUnlockTrait.supported(lock.DOMAIN, lock.SUPPORT_OPEN, None) trt = trait.LockUnlockTrait(hass, State('lock.front_door', lock.STATE_UNLOCKED), BASIC_CONFIG) assert trt.sync_attributes() == {} assert trt.query_attributes() == {'isLocked': False} assert trt.can_execute(trait.COMMAND_LOCKUNLOCK, {'lock': True}) calls = async_mock_service(hass, lock.DOMAIN, lock.SERVICE_LOCK) await trt.execute(trait.COMMAND_LOCKUNLOCK, BASIC_DATA, {'lock': True}) assert len(calls) == 1 assert calls[0].data == {ATTR_ENTITY_ID: 'lock.front_door'}
async def test_trigger_entity_restore_state_auto_off(hass, count, domain, config, restored_state, freezer): """Test restoring trigger template binary sensor.""" freezer.move_to("2022-02-02 12:02:00+00:00") fake_state = State( "binary_sensor.test", restored_state, {}, ) fake_extra_data = { "auto_off_time": { "__type": "<class 'datetime.datetime'>", "isoformat": datetime(2022, 2, 2, 12, 2, 2, tzinfo=timezone.utc).isoformat(), }, } mock_restore_cache_with_extra_data(hass, ((fake_state, fake_extra_data), )) with assert_setup_component(count, domain): assert await async_setup_component( hass, domain, config, ) await hass.async_block_till_done() await hass.async_start() await hass.async_block_till_done() state = hass.states.get("binary_sensor.test") assert state.state == restored_state # Now wait for the auto-off freezer.move_to("2022-02-02 12:02:03+00:00") await hass.async_block_till_done() await hass.async_block_till_done() state = hass.states.get("binary_sensor.test") assert state.state == OFF
async def test_capability_custom_range_random_access(hass): state = State('switch.test', '30', {}) hass.states.async_set(state.entity_id, state.state) cap = CustomRangeCapability( hass, BASIC_CONFIG, state, 'test_range', { const.CONF_ENTITY_CUSTOM_CAPABILITY_STATE_ENTITY_ID: state.entity_id, const.CONF_ENTITY_RANGE: { const.CONF_ENTITY_RANGE_MIN: 10, const.CONF_ENTITY_RANGE_MAX: 50, const.CONF_ENTITY_RANGE_PRECISION: 3, }, const.CONF_ENTITY_CUSTOM_RANGE_SET_VALUE: { CONF_SERVICE: 'test.set_value', ATTR_ENTITY_ID: 'input_number.test', CONF_SERVICE_DATA: { 'value': dynamic_template('value: {{ value|int }}') } }, }) assert cap.supported() assert cap.retrievable assert cap.support_random_access assert cap.get_value() == 30 calls = async_mock_service(hass, 'test', 'set_value') await cap.set_state(BASIC_DATA, {'value': 40}) await cap.set_state(BASIC_DATA, {'value': 100}) await cap.set_state(BASIC_DATA, {'value': 10, 'relative': True}) await cap.set_state(BASIC_DATA, {'value': -3, 'relative': True}) await cap.set_state(BASIC_DATA, {'value': -50, 'relative': True}) assert len(calls) == 5 for i in range(0, len(calls)): assert calls[i].data[ATTR_ENTITY_ID] == 'input_number.test' assert calls[0].data['value'] == 'value: 40' assert calls[1].data['value'] == 'value: 100' assert calls[2].data['value'] == 'value: 40' assert calls[3].data['value'] == 'value: 27' assert calls[4].data['value'] == 'value: 10'
async def test_restore_state(hass, zha_device_restored, zigpy_shade_device): """Ensure states are restored on startup.""" mock_restore_cache( hass, (State( "cover.fakemanufacturer_fakemodel_e769900a_level_on_off_shade", STATE_OPEN, {ATTR_CURRENT_POSITION: 50}, ), ), ) hass.state = CoreState.starting zha_device = await zha_device_restored(zigpy_shade_device) entity_id = await find_entity_id(DOMAIN, zha_device, hass) assert entity_id is not None # test that the cover was created and that it is unavailable assert hass.states.get(entity_id).state == STATE_OPEN assert hass.states.get(entity_id).attributes[ATTR_CURRENT_POSITION] == 50
async def test_state_restore(hass, rfxtrx, state, brightness): """State restoration.""" entity_id = "light.ac_213c7f2_16" mock_restore_cache( hass, [State(entity_id, state, attributes={ATTR_BRIGHTNESS: brightness})] ) entry_data = create_rfx_test_cfg( devices={"0b1100cd0213c7f210020f51": {"signal_repetitions": 1}} ) mock_entry = MockConfigEntry(domain="rfxtrx", unique_id=DOMAIN, data=entry_data) mock_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_entry.entry_id) await hass.async_block_till_done() assert hass.states.get(entity_id).state == state assert hass.states.get(entity_id).attributes.get(ATTR_BRIGHTNESS) == brightness