async def test_if_fires_using_at_input_datetime(hass, calls, has_date, has_time): """Test for firing at input_datetime.""" await async_setup_component( hass, "input_datetime", {"input_datetime": {"trigger": {"has_date": has_date, "has_time": has_time}}}, ) now = dt_util.now() trigger_dt = now.replace( hour=5 if has_time else 0, minute=0, second=0, microsecond=0 ) + timedelta(2) await hass.services.async_call( "input_datetime", "set_datetime", { ATTR_ENTITY_ID: "input_datetime.trigger", "datetime": str(trigger_dt.replace(tzinfo=None)), }, blocking=True, ) time_that_will_not_match_right_away = trigger_dt - timedelta(minutes=1) some_data = "{{ trigger.platform }}-{{ trigger.now.day }}-{{ trigger.now.hour }}-{{trigger.entity_id}}" with patch( "homeassistant.util.dt.utcnow", return_value=dt_util.as_utc(time_that_will_not_match_right_away), ): assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: { "trigger": {"platform": "time", "at": "input_datetime.trigger"}, "action": { "service": "test.automation", "data_template": {"some": some_data}, }, } }, ) await hass.async_block_till_done() async_fire_time_changed(hass, trigger_dt + timedelta(seconds=1)) await hass.async_block_till_done() assert len(calls) == 1 assert ( calls[0].data["some"] == f"time-{trigger_dt.day}-{trigger_dt.hour}-input_datetime.trigger" ) if has_date: trigger_dt += timedelta(days=1) if has_time: trigger_dt += timedelta(hours=1) await hass.services.async_call( "input_datetime", "set_datetime", { ATTR_ENTITY_ID: "input_datetime.trigger", "datetime": str(trigger_dt.replace(tzinfo=None)), }, blocking=True, ) async_fire_time_changed(hass, trigger_dt + timedelta(seconds=1)) await hass.async_block_till_done() assert len(calls) == 2 assert ( calls[1].data["some"] == f"time-{trigger_dt.day}-{trigger_dt.hour}-input_datetime.trigger" )
def test_offset(self): """Test offset.""" after = self.hass.config.time_zone.localize( datetime(2019, 1, 10, 18, 0, 0)).astimezone(pytz.UTC) + timedelta( hours=1, minutes=34) before = self.hass.config.time_zone.localize( datetime(2019, 1, 10, 22, 0, 0)).astimezone(pytz.UTC) + timedelta( hours=1, minutes=45) entity_id = "binary_sensor.evening" config = { "binary_sensor": [{ "platform": "tod", "name": "Evening", "after": "18:00", "after_offset": "1:34", "before": "22:00", "before_offset": "1:45", }] } testtime = after + timedelta(seconds=-1) with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=testtime, ): setup_component(self.hass, "binary_sensor", config) self.hass.block_till_done() state = self.hass.states.get(entity_id) assert state.state == STATE_OFF testtime = after with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=testtime, ): self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: testtime}) self.hass.block_till_done() state = self.hass.states.get(entity_id) assert state.state == STATE_ON testtime = before + timedelta(seconds=-1) with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=testtime, ): self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: testtime}) self.hass.block_till_done() state = self.hass.states.get(entity_id) assert state.state == STATE_ON testtime = before with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=testtime, ): self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: testtime}) self.hass.block_till_done() state = self.hass.states.get(entity_id) assert state.state == STATE_OFF testtime = before + timedelta(seconds=1) with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=testtime, ): self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: testtime}) self.hass.block_till_done() state = self.hass.states.get(entity_id) assert state.state == STATE_OFF
def test_sun_offset(self): """Test sun event with offset.""" test_time = self.hass.config.time_zone.localize(datetime( 2019, 1, 12)).astimezone(pytz.UTC) sunrise = dt_util.as_local( get_astral_event_date(self.hass, "sunrise", dt_util.as_utc(test_time)) + timedelta(hours=-1, minutes=-30)) sunset = dt_util.as_local( get_astral_event_date(self.hass, "sunset", dt_util.as_utc( test_time)) + timedelta(hours=1, minutes=30)) config = { "binary_sensor": [{ "platform": "tod", "name": "Day", "after": "sunrise", "after_offset": "-1:30", "before": "sunset", "before_offset": "1:30", }] } entity_id = "binary_sensor.day" testtime = sunrise + timedelta(seconds=-1) with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=testtime, ): setup_component(self.hass, "binary_sensor", config) self.hass.block_till_done() self.hass.block_till_done() state = self.hass.states.get(entity_id) assert state.state == STATE_OFF testtime = sunrise with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=testtime, ): self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: testtime}) self.hass.block_till_done() state = self.hass.states.get(entity_id) assert state.state == STATE_ON testtime = sunrise + timedelta(seconds=1) with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=testtime, ): self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: testtime}) self.hass.block_till_done() state = self.hass.states.get(entity_id) assert state.state == STATE_ON self.hass.block_till_done() testtime = sunset + timedelta(seconds=-1) with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=testtime, ): self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: testtime}) self.hass.block_till_done() state = self.hass.states.get(entity_id) assert state.state == STATE_ON self.hass.block_till_done() testtime = sunset with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=testtime, ): self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: testtime}) self.hass.block_till_done() state = self.hass.states.get(entity_id) assert state.state == STATE_OFF self.hass.block_till_done() testtime = sunset + timedelta(seconds=1) with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=testtime, ): self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: testtime}) self.hass.block_till_done() state = self.hass.states.get(entity_id) assert state.state == STATE_OFF test_time = test_time + timedelta(days=1) sunrise = dt_util.as_local( get_astral_event_date(self.hass, "sunrise", dt_util.as_utc(test_time)) + timedelta(hours=-1, minutes=-30)) testtime = sunrise with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=testtime, ): self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: testtime}) self.hass.block_till_done() state = self.hass.states.get(entity_id) assert state.state == STATE_ON
def hue_setup_fixture(): """Mock hue entry setup.""" with patch("homeassistant.components.hue.async_setup_entry", return_value=True): yield
def broadlink_setup_fixture(): """Mock broadlink entry setup.""" with patch( "homeassistant.components.broadlink.async_setup", return_value=True ), patch("homeassistant.components.broadlink.async_setup_entry", return_value=True): yield
def mock_secret(): """Mock secret.""" with patch("secrets.token_hex", return_value=SECRET): yield
def mock_setup(): """Mock entry setup.""" with patch( "homeassistant.components.speedtestdotnet.async_setup_entry", return_value=True, ): yield
async def test_delete_automation(hass, hass_client): """Test deleting an automation.""" ent_reg = await hass.helpers.entity_registry.async_get_registry() assert await async_setup_component( hass, "automation", { "automation": [ { "id": "sun", "trigger": { "platform": "event", "event_type": "test_event" }, "action": { "service": "test.automation" }, }, { "id": "moon", "trigger": { "platform": "event", "event_type": "test_event" }, "action": { "service": "test.automation" }, }, ] }, ) assert len(ent_reg.entities) == 2 with patch.object(config, "SECTIONS", ["automation"]): assert await async_setup_component(hass, "config", {}) client = await hass_client() orig_data = [{"id": "sun"}, {"id": "moon"}] def mock_read(path): """Mock reading data.""" return orig_data written = [] def mock_write(path, data): """Mock writing data.""" written.append(data) with patch("homeassistant.components.config._read", mock_read), patch( "homeassistant.components.config._write", mock_write), patch("homeassistant.config.async_hass_config_yaml", return_value={}): resp = await client.delete("/api/config/automation/config/sun") await hass.async_block_till_done() assert resp.status == 200 result = await resp.json() assert result == {"result": "ok"} assert len(written) == 1 assert written[0][0]["id"] == "moon" assert len(ent_reg.entities) == 1
def mock_supervisor_fixture(): """Mock Supervisor.""" with patch("homeassistant.components.hassio.is_hassio", return_value=True): yield
def product_class_mock_fixture(): """Return a mocked feature.""" path = "homeassistant.components.blebox.config_flow.Products" patcher = patch(path, DEFAULT, blebox_uniapi.products.Products, True, True) yield patcher
def test_initialize_from_database_with_maxage(self): """Test initializing the statistics from the database.""" mock_data = { "return_time": datetime(2017, 8, 2, 12, 23, 42, tzinfo=dt_util.UTC) } def mock_now(): return mock_data["return_time"] # Testing correct retrieval from recorder, thus we do not # want purging to occur within the class itself. def mock_purge(self): return # Set maximum age to 3 hours. max_age = 3 # Determine what our minimum age should be based on test values. expected_min_age = mock_data["return_time"] + timedelta( hours=len(self.values) - max_age) # enable the recorder init_recorder_component(self.hass) self.hass.block_till_done() self.hass.data[recorder.DATA_INSTANCE].block_till_done() with patch("homeassistant.components.statistics.sensor.dt_util.utcnow", new=mock_now), patch.object(StatisticsSensor, "_purge_old", mock_purge): # store some values for value in self.values: self.hass.states.set( "sensor.test_monitored", value, {ATTR_UNIT_OF_MEASUREMENT: TEMP_CELSIUS}, ) self.hass.block_till_done() # insert the next value 1 hour later mock_data["return_time"] += timedelta(hours=1) # wait for the recorder to really store the data wait_recording_done(self.hass) # only now create the statistics component, so that it must read # the data from the database assert setup_component( self.hass, "sensor", { "sensor": { "platform": "statistics", "name": "test", "entity_id": "sensor.test_monitored", "sampling_size": 100, "max_age": { "hours": max_age }, } }, ) self.hass.block_till_done() self.hass.block_till_done() self.hass.start() self.hass.block_till_done() # check if the result is as in test_sensor_source() state = self.hass.states.get("sensor.test") assert expected_min_age == state.attributes.get("min_age") # The max_age timestamp should be 1 hour before what we have right # now in mock_data['return_time']. assert mock_data["return_time"] == state.attributes.get( "max_age") + timedelta(hours=1)
async def test_services(hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker) -> None: """Test the different media player services.""" await setup_integration(hass, aioclient_mock) with patch("homeassistant.components.roku.Roku.remote") as remote_mock: await hass.services.async_call(MP_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: MAIN_ENTITY_ID}, blocking=True) remote_mock.assert_called_once_with("poweroff") with patch("homeassistant.components.roku.Roku.remote") as remote_mock: await hass.services.async_call(MP_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: MAIN_ENTITY_ID}, blocking=True) remote_mock.assert_called_once_with("poweron") with patch("homeassistant.components.roku.Roku.remote") as remote_mock: await hass.services.async_call( MP_DOMAIN, SERVICE_MEDIA_PLAY_PAUSE, {ATTR_ENTITY_ID: MAIN_ENTITY_ID}, blocking=True, ) remote_mock.assert_called_once_with("play") with patch("homeassistant.components.roku.Roku.remote") as remote_mock: await hass.services.async_call( MP_DOMAIN, SERVICE_MEDIA_NEXT_TRACK, {ATTR_ENTITY_ID: MAIN_ENTITY_ID}, blocking=True, ) remote_mock.assert_called_once_with("forward") with patch("homeassistant.components.roku.Roku.remote") as remote_mock: await hass.services.async_call( MP_DOMAIN, SERVICE_MEDIA_PREVIOUS_TRACK, {ATTR_ENTITY_ID: MAIN_ENTITY_ID}, blocking=True, ) remote_mock.assert_called_once_with("reverse") with patch("homeassistant.components.roku.Roku.remote") as remote_mock: await hass.services.async_call( MP_DOMAIN, SERVICE_SELECT_SOURCE, { ATTR_ENTITY_ID: MAIN_ENTITY_ID, ATTR_INPUT_SOURCE: "Home" }, blocking=True, ) remote_mock.assert_called_once_with("home") with patch("homeassistant.components.roku.Roku.launch") as remote_mock: await hass.services.async_call( MP_DOMAIN, SERVICE_SELECT_SOURCE, { ATTR_ENTITY_ID: MAIN_ENTITY_ID, ATTR_INPUT_SOURCE: "Netflix" }, blocking=True, ) remote_mock.assert_called_once_with("12")
def delay_fixture(): """Patch the delay script function.""" with patch( "homeassistant.components.samsungtv.media_player.Script.async_run" ) as delay: yield delay
async def mock_async_start(): """Start the mocking.""" # We only mock time during tests and we want to track tasks with patch("homeassistant.core._async_create_timer"), patch.object( hass, "async_stop_track_tasks"): await orig_start()
async def test_shade(hass, zha_device_joined_restored, zigpy_shade_device): """Test zha cover platform for shade device type.""" # load up cover domain zha_device = await zha_device_joined_restored(zigpy_shade_device) cluster_on_off = zigpy_shade_device.endpoints.get(1).on_off cluster_level = zigpy_shade_device.endpoints.get(1).level entity_id = await find_entity_id(DOMAIN, zha_device, hass) assert entity_id is not None await async_enable_traffic(hass, [zha_device], enabled=False) # test that the cover was created and that it is unavailable assert hass.states.get(entity_id).state == STATE_UNAVAILABLE # allow traffic to flow through the gateway and device await async_enable_traffic(hass, [zha_device]) await hass.async_block_till_done() # test that the state has changed from unavailable to off await send_attributes_report(hass, cluster_on_off, {8: 0, 0: False, 1: 1}) assert hass.states.get(entity_id).state == STATE_CLOSED # test to see if it opens await send_attributes_report(hass, cluster_on_off, {8: 0, 0: True, 1: 1}) assert hass.states.get(entity_id).state == STATE_OPEN # close from UI command fails with patch("zigpy.zcl.Cluster.request", side_effect=asyncio.TimeoutError): await hass.services.async_call(DOMAIN, SERVICE_CLOSE_COVER, {"entity_id": entity_id}, blocking=True) assert cluster_on_off.request.call_count == 1 assert cluster_on_off.request.call_args[0][0] is False assert cluster_on_off.request.call_args[0][1] == 0x0000 assert hass.states.get(entity_id).state == STATE_OPEN with patch("zigpy.zcl.Cluster.request", AsyncMock(return_value=[0x1, zcl_f.Status.SUCCESS])): await hass.services.async_call(DOMAIN, SERVICE_CLOSE_COVER, {"entity_id": entity_id}, blocking=True) assert cluster_on_off.request.call_count == 1 assert cluster_on_off.request.call_args[0][0] is False assert cluster_on_off.request.call_args[0][1] == 0x0000 assert hass.states.get(entity_id).state == STATE_CLOSED # open from UI command fails assert ATTR_CURRENT_POSITION not in hass.states.get(entity_id).attributes await send_attributes_report(hass, cluster_level, {0: 0}) with patch("zigpy.zcl.Cluster.request", side_effect=asyncio.TimeoutError): await hass.services.async_call(DOMAIN, SERVICE_OPEN_COVER, {"entity_id": entity_id}, blocking=True) assert cluster_on_off.request.call_count == 1 assert cluster_on_off.request.call_args[0][0] is False assert cluster_on_off.request.call_args[0][1] == 0x0001 assert hass.states.get(entity_id).state == STATE_CLOSED # open from UI succeeds with patch("zigpy.zcl.Cluster.request", AsyncMock(return_value=[0x0, zcl_f.Status.SUCCESS])): await hass.services.async_call(DOMAIN, SERVICE_OPEN_COVER, {"entity_id": entity_id}, blocking=True) assert cluster_on_off.request.call_count == 1 assert cluster_on_off.request.call_args[0][0] is False assert cluster_on_off.request.call_args[0][1] == 0x0001 assert hass.states.get(entity_id).state == STATE_OPEN # set position UI command fails with patch("zigpy.zcl.Cluster.request", side_effect=asyncio.TimeoutError): await hass.services.async_call( DOMAIN, SERVICE_SET_COVER_POSITION, { "entity_id": entity_id, "position": 47 }, blocking=True, ) assert cluster_level.request.call_count == 1 assert cluster_level.request.call_args[0][0] is False assert cluster_level.request.call_args[0][1] == 0x0004 assert int(cluster_level.request.call_args[0][3] * 100 / 255) == 47 assert hass.states.get( entity_id).attributes[ATTR_CURRENT_POSITION] == 0 # set position UI success with patch("zigpy.zcl.Cluster.request", AsyncMock(return_value=[0x5, zcl_f.Status.SUCCESS])): await hass.services.async_call( DOMAIN, SERVICE_SET_COVER_POSITION, { "entity_id": entity_id, "position": 47 }, blocking=True, ) assert cluster_level.request.call_count == 1 assert cluster_level.request.call_args[0][0] is False assert cluster_level.request.call_args[0][1] == 0x0004 assert int(cluster_level.request.call_args[0][3] * 100 / 255) == 47 assert hass.states.get( entity_id).attributes[ATTR_CURRENT_POSITION] == 47 # report position change await send_attributes_report(hass, cluster_level, {8: 0, 0: 100, 1: 1}) assert hass.states.get(entity_id).attributes[ATTR_CURRENT_POSITION] == int( 100 * 100 / 255) # test rejoin await async_test_rejoin(hass, zigpy_shade_device, [cluster_level, cluster_on_off], (1, )) assert hass.states.get(entity_id).state == STATE_OPEN # test cover stop with patch("zigpy.zcl.Cluster.request", side_effect=asyncio.TimeoutError): await hass.services.async_call( DOMAIN, SERVICE_STOP_COVER, {"entity_id": entity_id}, blocking=True, ) assert cluster_level.request.call_count == 1 assert cluster_level.request.call_args[0][0] is False assert cluster_level.request.call_args[0][1] in (0x0003, 0x0007)
def mock_addon_info(): """Mock Supervisor add-on info.""" with patch("homeassistant.components.hassio.async_get_addon_info" ) as addon_info: addon_info.return_value = {} yield addon_info
def mock_webhook_id(): """Mock webhook_id.""" with patch("homeassistant.components.webhook.async_generate_id", return_value=WEBHOOK_ID): yield
def mock_set_addon_options(): """Mock set add-on options.""" with patch("homeassistant.components.hassio.async_set_addon_options" ) as set_options: yield set_options
async def test_expiration_on_discovery_and_discovery_update_of_binary_sensor( hass, mqtt_mock, caplog): """Test that binary_sensor with expire_after set behaves correctly on discovery and discovery update.""" entry = hass.config_entries.async_entries(mqtt.DOMAIN)[0] await async_start(hass, "homeassistant", entry) config = { "name": "Test", "state_topic": "test-topic", "expire_after": 4, "force_update": True, } config_msg = json.dumps(config) # Set time and publish config message to create binary_sensor via discovery with 4 s expiry now = datetime(2017, 1, 1, 1, tzinfo=dt_util.UTC) with patch(("homeassistant.helpers.event.dt_util.utcnow"), return_value=now): async_fire_time_changed(hass, now) async_fire_mqtt_message(hass, "homeassistant/binary_sensor/bla/config", config_msg) await hass.async_block_till_done() # Test that binary_sensor is not available state = hass.states.get("binary_sensor.test") assert state.state == STATE_UNAVAILABLE # Publish state message with patch(("homeassistant.helpers.event.dt_util.utcnow"), return_value=now): async_fire_mqtt_message(hass, "test-topic", "ON") await hass.async_block_till_done() # Test that binary_sensor has correct state state = hass.states.get("binary_sensor.test") assert state.state == STATE_ON # Advance +3 seconds now = now + timedelta(seconds=3) with patch(("homeassistant.helpers.event.dt_util.utcnow"), return_value=now): async_fire_time_changed(hass, now) await hass.async_block_till_done() # binary_sensor is not yet expired state = hass.states.get("binary_sensor.test") assert state.state == STATE_ON # Resend config message to update discovery with patch(("homeassistant.helpers.event.dt_util.utcnow"), return_value=now): async_fire_time_changed(hass, now) async_fire_mqtt_message(hass, "homeassistant/binary_sensor/bla/config", config_msg) await hass.async_block_till_done() # Test that binary_sensor has not expired state = hass.states.get("binary_sensor.test") assert state.state == STATE_ON # Add +2 seconds now = now + timedelta(seconds=2) with patch(("homeassistant.helpers.event.dt_util.utcnow"), return_value=now): async_fire_time_changed(hass, now) await hass.async_block_till_done() # Test that binary_sensor has expired state = hass.states.get("binary_sensor.test") assert state.state == STATE_UNAVAILABLE # Resend config message to update discovery with patch(("homeassistant.helpers.event.dt_util.utcnow"), return_value=now): async_fire_mqtt_message(hass, "homeassistant/binary_sensor/bla/config", config_msg) await hass.async_block_till_done() # Test that binary_sensor is still expired state = hass.states.get("binary_sensor.test") assert state.state == STATE_UNAVAILABLE
def mock_install_addon(): """Mock install add-on.""" with patch("homeassistant.components.hassio.async_install_addon" ) as install_addon: yield install_addon
async def test_form_user_multiple_ups(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) config_entry = MockConfigEntry( domain=DOMAIN, data={"host": "2.2.2.2", "port": 123, "resources": ["battery.charge"]}, options={CONF_RESOURCES: ["battery.charge"]}, ) config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} mock_pynut = _get_mock_pynutclient( list_vars={"battery.voltage": "voltage"}, list_ups={"ups1": "UPS 1", "ups2": "UPS2"}, ) with patch( "homeassistant.components.nut.PyNUTClient", return_value=mock_pynut, ): result2 = await hass.config_entries.flow.async_configure( result["flow_id"], { "host": "1.1.1.1", "username": "******", "password": "******", "port": 2222, }, ) assert result2["step_id"] == "ups" assert result2["type"] == "form" with patch( "homeassistant.components.nut.PyNUTClient", return_value=mock_pynut, ): result3 = await hass.config_entries.flow.async_configure( result2["flow_id"], {"alias": "ups2"}, ) assert result3["step_id"] == "resources" assert result3["type"] == "form" with patch( "homeassistant.components.nut.PyNUTClient", return_value=mock_pynut, ), patch( "homeassistant.components.nut.async_setup", return_value=True ) as mock_setup, patch( "homeassistant.components.nut.async_setup_entry", return_value=True, ) as mock_setup_entry: result4 = await hass.config_entries.flow.async_configure( result3["flow_id"], {"resources": ["battery.voltage"]}, ) assert result4["type"] == "create_entry" assert result4["title"] == "[email protected]:2222" assert result4["data"] == { "host": "1.1.1.1", "password": "******", "alias": "ups2", "port": 2222, "resources": ["battery.voltage"], "username": "******", } await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 2
def mock_start_addon(): """Mock start add-on.""" with patch("homeassistant.components.hassio.async_start_addon" ) as start_addon: yield start_addon
async def test_reload(hass, hass_admin_user): """Test reloading the YAML config.""" assert await async_setup_component( hass, DOMAIN, { DOMAIN: [ { "name": "Person 1", "id": "id-1" }, { "name": "Person 2", "id": "id-2" }, ] }, ) assert len(hass.states.async_entity_ids()) == 2 state_1 = hass.states.get("person.person_1") state_2 = hass.states.get("person.person_2") state_3 = hass.states.get("person.person_3") assert state_1 is not None assert state_1.name == "Person 1" assert state_2 is not None assert state_2.name == "Person 2" assert state_3 is None with patch( "homeassistant.config.load_yaml_config_file", autospec=True, return_value={ DOMAIN: [ { "name": "Person 1-updated", "id": "id-1" }, { "name": "Person 3", "id": "id-3" }, ] }, ): await hass.services.async_call( DOMAIN, SERVICE_RELOAD, blocking=True, context=Context(user_id=hass_admin_user.id), ) await hass.async_block_till_done() assert len(hass.states.async_entity_ids()) == 2 state_1 = hass.states.get("person.person_1") state_2 = hass.states.get("person.person_2") state_3 = hass.states.get("person.person_3") assert state_1 is not None assert state_1.name == "Person 1-updated" assert state_2 is None assert state_3 is not None assert state_3.name == "Person 3"
def mock_client_fixture(): """Mock the apache kafka client.""" with patch(f"{PRODUCER_PATH}.start") as start, patch( f"{PRODUCER_PATH}.send_and_wait") as send_and_wait, patch( f"{PRODUCER_PATH}.__init__", return_value=None) as init: yield MockKafkaClient(init, start, send_and_wait)
def test_from_sunset_to_sunrise(self): """Test period from sunset to sunrise.""" test_time = self.hass.config.time_zone.localize(datetime( 2019, 1, 12)).astimezone(pytz.UTC) sunset = dt_util.as_local( get_astral_event_date(self.hass, "sunset", test_time)) sunrise = dt_util.as_local( get_astral_event_next(self.hass, "sunrise", sunset)) # assert sunset == sunrise config = { "binary_sensor": [{ "platform": "tod", "name": "Night", "after": "sunset", "before": "sunrise", }] } entity_id = "binary_sensor.night" testtime = sunset + timedelta(minutes=-1) with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=testtime, ): setup_component(self.hass, "binary_sensor", config) self.hass.block_till_done() self.hass.block_till_done() state = self.hass.states.get(entity_id) assert state.state == STATE_OFF testtime = sunset with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=testtime, ): self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: testtime}) self.hass.block_till_done() state = self.hass.states.get(entity_id) assert state.state == STATE_ON testtime = sunset + timedelta(minutes=1) with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=testtime, ): self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: testtime}) self.hass.block_till_done() state = self.hass.states.get(entity_id) assert state.state == STATE_ON testtime = sunrise + timedelta(minutes=-1) with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=testtime, ): self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: testtime}) self.hass.block_till_done() state = self.hass.states.get(entity_id) assert state.state == STATE_ON testtime = sunrise with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=testtime, ): self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: testtime}) self.hass.block_till_done() state = self.hass.states.get(entity_id) self.hass.block_till_done() # assert state == "dupa" assert state.state == STATE_OFF testtime = sunrise + timedelta(minutes=1) with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=testtime, ): self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: testtime}) self.hass.block_till_done() state = self.hass.states.get(entity_id) assert state.state == STATE_OFF
def mock_client_stop(): """Mock client stop at module scope for teardown.""" with patch(f"{PRODUCER_PATH}.stop") as stop: yield stop
def test_norwegian_case_summer(self): """Test location in Norway where the sun doesn't set in summer.""" self.hass.config.latitude = 69.6 self.hass.config.longitude = 18.8 test_time = self.hass.config.time_zone.localize(datetime( 2010, 6, 1)).astimezone(pytz.UTC) sunrise = dt_util.as_local( get_astral_event_next(self.hass, "sunrise", dt_util.as_utc(test_time))) sunset = dt_util.as_local( get_astral_event_next(self.hass, "sunset", dt_util.as_utc(test_time))) config = { "binary_sensor": [{ "platform": "tod", "name": "Day", "after": "sunrise", "before": "sunset", }] } entity_id = "binary_sensor.day" testtime = test_time with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=testtime, ): setup_component(self.hass, "binary_sensor", config) self.hass.block_till_done() self.hass.block_till_done() state = self.hass.states.get(entity_id) assert state.state == STATE_OFF testtime = sunrise + timedelta(seconds=-1) with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=testtime, ): self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: testtime}) self.hass.block_till_done() state = self.hass.states.get(entity_id) assert state.state == STATE_OFF testtime = sunrise with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=testtime, ): self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: testtime}) self.hass.block_till_done() state = self.hass.states.get(entity_id) assert state.state == STATE_ON testtime = sunrise + timedelta(seconds=1) with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=testtime, ): self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: testtime}) self.hass.block_till_done() state = self.hass.states.get(entity_id) assert state.state == STATE_ON self.hass.block_till_done() testtime = sunset + timedelta(seconds=-1) with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=testtime, ): self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: testtime}) self.hass.block_till_done() state = self.hass.states.get(entity_id) assert state.state == STATE_ON self.hass.block_till_done() testtime = sunset with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=testtime, ): self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: testtime}) self.hass.block_till_done() state = self.hass.states.get(entity_id) assert state.state == STATE_OFF self.hass.block_till_done() testtime = sunset + timedelta(seconds=1) with patch( "homeassistant.components.tod.binary_sensor.dt_util.utcnow", return_value=testtime, ): self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: testtime}) self.hass.block_till_done() state = self.hass.states.get(entity_id) assert state.state == STATE_OFF
async def test_cover(m1, hass, zha_device_joined_restored, zigpy_cover_device): """Test zha cover platform.""" # load up cover domain cluster = zigpy_cover_device.endpoints.get(1).window_covering cluster.PLUGGED_ATTR_READS = {"current_position_lift_percentage": 100} zha_device = await zha_device_joined_restored(zigpy_cover_device) assert cluster.read_attributes.call_count == 2 assert "current_position_lift_percentage" in cluster.read_attributes.call_args[ 0][0] entity_id = await find_entity_id(DOMAIN, zha_device, hass) assert entity_id is not None await async_enable_traffic(hass, [zha_device], enabled=False) # test that the cover was created and that it is unavailable assert hass.states.get(entity_id).state == STATE_UNAVAILABLE # allow traffic to flow through the gateway and device await async_enable_traffic(hass, [zha_device]) await hass.async_block_till_done() # test that the state has changed from unavailable to off await send_attributes_report(hass, cluster, {0: 0, 8: 100, 1: 1}) assert hass.states.get(entity_id).state == STATE_CLOSED # test to see if it opens await send_attributes_report(hass, cluster, {0: 1, 8: 0, 1: 100}) assert hass.states.get(entity_id).state == STATE_OPEN # close from UI with patch("zigpy.zcl.Cluster.request", return_value=mock_coro([0x1, zcl_f.Status.SUCCESS])): await hass.services.async_call(DOMAIN, SERVICE_CLOSE_COVER, {"entity_id": entity_id}, blocking=True) assert cluster.request.call_count == 1 assert cluster.request.call_args[0][0] is False assert cluster.request.call_args[0][1] == 0x01 assert cluster.request.call_args[0][2] == () assert cluster.request.call_args[1]["expect_reply"] is True # open from UI with patch("zigpy.zcl.Cluster.request", return_value=mock_coro([0x0, zcl_f.Status.SUCCESS])): await hass.services.async_call(DOMAIN, SERVICE_OPEN_COVER, {"entity_id": entity_id}, blocking=True) assert cluster.request.call_count == 1 assert cluster.request.call_args[0][0] is False assert cluster.request.call_args[0][1] == 0x00 assert cluster.request.call_args[0][2] == () assert cluster.request.call_args[1]["expect_reply"] is True # set position UI with patch("zigpy.zcl.Cluster.request", return_value=mock_coro([0x5, zcl_f.Status.SUCCESS])): await hass.services.async_call( DOMAIN, SERVICE_SET_COVER_POSITION, { "entity_id": entity_id, "position": 47 }, blocking=True, ) assert cluster.request.call_count == 1 assert cluster.request.call_args[0][0] is False assert cluster.request.call_args[0][1] == 0x05 assert cluster.request.call_args[0][2] == (zigpy.types.uint8_t, ) assert cluster.request.call_args[0][3] == 53 assert cluster.request.call_args[1]["expect_reply"] is True # stop from UI with patch("zigpy.zcl.Cluster.request", return_value=mock_coro([0x2, zcl_f.Status.SUCCESS])): await hass.services.async_call(DOMAIN, SERVICE_STOP_COVER, {"entity_id": entity_id}, blocking=True) assert cluster.request.call_count == 1 assert cluster.request.call_args[0][0] is False assert cluster.request.call_args[0][1] == 0x02 assert cluster.request.call_args[0][2] == () assert cluster.request.call_args[1]["expect_reply"] is True # test rejoin await async_test_rejoin(hass, zigpy_cover_device, [cluster], (1, )) assert hass.states.get(entity_id).state == STATE_OPEN
def mock_finish_setup(): """Mock out the finish setup method.""" with patch("homeassistant.components.mqtt.MQTT.async_connect", return_value=True) as mock_finish: yield mock_finish
async def test_camera_disabled(hass): """Test that Axis camera platform is loaded properly but does not create camera entity.""" with patch("axis.vapix.Params.image_format", new=None): await setup_axis_integration(hass) assert len(hass.states.async_entity_ids(CAMERA_DOMAIN)) == 0