def test_service_say_german_config(self, aioclient_mock): """Test service call say with german code in the config.""" calls = mock_service(self.hass, DOMAIN_MP, SERVICE_PLAY_MEDIA) self.form_data['hl'] = 'de-de' aioclient_mock.post( self.url, data=self.form_data, status=200, content=b'test') config = { tts.DOMAIN: { 'platform': 'voicerss', 'api_key': '1234567xx', 'language': 'de-de', } } with assert_setup_component(1, tts.DOMAIN): setup_component(self.hass, tts.DOMAIN, config) self.hass.services.call(tts.DOMAIN, 'voicerss_say', { tts.ATTR_MESSAGE: "I person is on front of your door.", }) self.hass.block_till_done() assert len(calls) == 1 assert len(aioclient_mock.mock_calls) == 1 assert aioclient_mock.mock_calls[0][2] == self.form_data
def test_dst(self): """Test sun event with offset.""" self.hass.config.time_zone = pytz.timezone('CET') test_time = self.hass.config.time_zone.localize( datetime(2019, 3, 30, 3, 0, 0)).astimezone(pytz.UTC) config = { 'binary_sensor': [ { 'platform': 'tod', 'name': 'Day', 'after': '2:30', 'before': '2:40' } ] } # after 2019-03-30 03:00 CET the next update should ge scheduled # at 3:30 not 2:30 local time # Internally the 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() state = self.hass.states.get(entity_id) state.attributes['after'] == '2019-03-31T03:30:00+02:00' state.attributes['before'] == '2019-03-31T03:40:00+02:00' state.attributes['next_update'] == '2019-03-31T03:30:00+02:00' assert state.state == STATE_OFF
def setup_method(self): """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() config = { ip.DOMAIN: { 'platform': 'demo' }, 'camera': { 'platform': 'demo' }, } with patch('homeassistant.components.image_processing.demo.' 'DemoImageProcessingFace.should_poll', new_callable=PropertyMock(return_value=False)): setup_component(self.hass, ip.DOMAIN, config) state = self.hass.states.get('camera.demo_camera') self.url = "{0}{1}".format( self.hass.config.api.base_url, state.attributes.get(ATTR_ENTITY_PICTURE)) self.face_events = [] @callback def mock_face_event(event): """Mock event.""" self.face_events.append(event) self.hass.bus.listen('image_processing.detect_face', mock_face_event)
def test_filling_the_cache(): """Test filling the cache from the DB.""" test_entity_id1 = 'input_boolean.b1' test_entity_id2 = 'input_boolean.b2' hass = get_test_home_assistant() hass.state = CoreState.starting init_recorder_component(hass) _add_data_in_last_run(hass, { test_entity_id1: 'on', test_entity_id2: 'off', }) hass.block_till_done() setup_component(hass, input_boolean.DOMAIN, { input_boolean.DOMAIN: { 'b1': None, 'b2': None, }}) hass.start() state = hass.states.get('input_boolean.b1') assert state assert state.state == 'on' state = hass.states.get('input_boolean.b2') assert state assert state.state == 'off' hass.stop()
def test_midnight_turnover_after_midnight_inside_period(self): """Test midnight turnover setting before midnight inside period .""" test_time = self.hass.config.time_zone.localize( datetime(2019, 1, 10, 21, 0, 0)).astimezone(pytz.UTC) config = { 'binary_sensor': [ { 'platform': 'tod', 'name': 'Night', 'after': '22:00', 'before': '5:00' }, ] } with patch('homeassistant.components.tod.binary_sensor.dt_util.utcnow', return_value=test_time): setup_component(self.hass, 'binary_sensor', config) state = self.hass.states.get('binary_sensor.night') assert state.state == STATE_OFF self.hass.block_till_done() with patch('homeassistant.components.tod.binary_sensor.dt_util.utcnow', return_value=test_time + timedelta(hours=1)): self.hass.bus.fire(ha.EVENT_TIME_CHANGED, { ha.ATTR_NOW: test_time + timedelta(hours=1)}) self.hass.block_till_done() state = self.hass.states.get('binary_sensor.night') assert state.state == STATE_ON
def test_setup_component(self): """Setup ffmpeg component.""" with assert_setup_component(1, 'binary_sensor'): setup_component(self.hass, 'binary_sensor', self.config) assert self.hass.data['ffmpeg'].binary == 'ffmpeg' assert self.hass.states.get('binary_sensor.ffmpeg_motion') is not None
def test_setup_component_invalidprovince(self): """Setup workday component.""" with assert_setup_component(1, 'binary_sensor'): setup_component(self.hass, 'binary_sensor', self.config_invalidprovince) assert self.hass.states.get('binary_sensor.workday_sensor') is None
def test_service_say_german_config(self, mock_calculate, aioclient_mock): """Test service call say with german code in the config.""" calls = mock_service(self.hass, DOMAIN_MP, SERVICE_PLAY_MEDIA) self.url_param['tl'] = 'de' aioclient_mock.get( self.url, params=self.url_param, status=200, content=b'test') config = { tts.DOMAIN: { 'platform': 'google', 'language': 'de', } } with assert_setup_component(1, tts.DOMAIN): setup_component(self.hass, tts.DOMAIN, config) self.hass.services.call(tts.DOMAIN, 'google_say', { tts.ATTR_MESSAGE: "90% of I person is on front of your door.", }) self.hass.block_till_done() assert len(calls) == 1 assert len(aioclient_mock.mock_calls) == 1
def test_setting_up_group(self): """Setup the setting of a group.""" setup_component(self.hass, 'group', {'group': {}}) component = EntityComponent(_LOGGER, DOMAIN, self.hass, group_name='everyone') # No group after setup assert len(self.hass.states.entity_ids()) == 0 component.add_entities([MockEntity()]) self.hass.block_till_done() # group exists assert len(self.hass.states.entity_ids()) == 2 assert self.hass.states.entity_ids('group') == ['group.everyone'] group = self.hass.states.get('group.everyone') assert group.attributes.get('entity_id') == \ ('test_domain.unnamed_device',) # group extended component.add_entities([MockEntity(name='goodbye')]) self.hass.block_till_done() assert len(self.hass.states.entity_ids()) == 3 group = self.hass.states.get('group.everyone') # Ordered in order of added to the group assert group.attributes.get('entity_id') == \ ('test_domain.goodbye', 'test_domain.unnamed_device')
def test_setup_component_and_test_service(self): """Set up the demo platform and call service.""" calls = mock_service(self.hass, DOMAIN_MP, SERVICE_PLAY_MEDIA) config = { tts.DOMAIN: { 'platform': 'demo', } } with assert_setup_component(1, tts.DOMAIN): setup_component(self.hass, tts.DOMAIN, config) self.hass.services.call(tts.DOMAIN, 'demo_say', { tts.ATTR_MESSAGE: "I person is on front of your door.", }) self.hass.block_till_done() assert len(calls) == 1 assert calls[0].data[ATTR_MEDIA_CONTENT_TYPE] == MEDIA_TYPE_MUSIC assert calls[0].data[ATTR_MEDIA_CONTENT_ID] == \ "{}/api/tts_proxy/265944c108cbb00b2a621be5930513e03a0bb2cd" \ "_en_-_demo.mp3".format(self.hass.config.api.base_url) assert os.path.isfile(os.path.join( self.default_tts_cache, "265944c108cbb00b2a621be5930513e03a0bb2cd_en_-_demo.mp3"))
def test_heater_switch(self): """Test heater switching test switch.""" platform = loader.get_component(self.hass, 'switch.test') platform.init() self.switch_1 = platform.DEVICES[1] assert setup_component(self.hass, switch.DOMAIN, {'switch': { 'platform': 'test'}}) heater_switch = self.switch_1.entity_id assert setup_component(self.hass, climate.DOMAIN, {'climate': { 'platform': 'generic_thermostat', 'name': 'test', 'heater': heater_switch, 'target_sensor': ENT_SENSOR }}) self.assertEqual(STATE_OFF, self.hass.states.get(heater_switch).state) self._setup_sensor(18) self.hass.block_till_done() climate.set_temperature(self.hass, 23) self.hass.block_till_done() self.assertEqual(STATE_ON, self.hass.states.get(heater_switch).state)
def test_setup_component_test_with_cache_dir(self): """Set up demo platform with cache and call service without cache.""" calls = mock_service(self.hass, DOMAIN_MP, SERVICE_PLAY_MEDIA) _, demo_data = self.demo_provider.get_tts_audio("bla", 'en') cache_file = os.path.join( self.default_tts_cache, "265944c108cbb00b2a621be5930513e03a0bb2cd_en_-_demo.mp3") os.mkdir(self.default_tts_cache) with open(cache_file, "wb") as voice_file: voice_file.write(demo_data) config = { tts.DOMAIN: { 'platform': 'demo', 'cache': True, } } with assert_setup_component(1, tts.DOMAIN): setup_component(self.hass, tts.DOMAIN, config) with patch('homeassistant.components.tts.demo.DemoProvider.' 'get_tts_audio', return_value=(None, None)): self.hass.services.call(tts.DOMAIN, 'demo_say', { tts.ATTR_MESSAGE: "I person is on front of your door.", }) self.hass.block_till_done() assert len(calls) == 1 assert calls[0].data[ATTR_MEDIA_CONTENT_ID] == \ "{}/api/tts_proxy/265944c108cbb00b2a621be5930513e03a0bb2cd" \ "_en_-_demo.mp3".format(self.hass.config.api.base_url)
def test_service_groups(self, mock_update, aioclient_mock): """Set up component, test groups services.""" aioclient_mock.put( self.endpoint_url.format("persongroups/service_group"), status=200, text="{}" ) aioclient_mock.delete( self.endpoint_url.format("persongroups/service_group"), status=200, text="{}" ) with assert_setup_component(3, mf.DOMAIN): setup_component(self.hass, mf.DOMAIN, self.config) create_group(self.hass, 'Service Group') self.hass.block_till_done() entity = self.hass.states.get('microsoft_face.service_group') assert entity is not None assert len(aioclient_mock.mock_calls) == 1 delete_group(self.hass, 'Service Group') self.hass.block_till_done() entity = self.hass.states.get('microsoft_face.service_group') assert entity is None assert len(aioclient_mock.mock_calls) == 2
def test_service_face(self, camera_mock, aioclient_mock): """Set up component, test person face services.""" aioclient_mock.get( self.endpoint_url.format("persongroups"), text=load_fixture('microsoft_face_persongroups.json') ) aioclient_mock.get( self.endpoint_url.format("persongroups/test_group1/persons"), text=load_fixture('microsoft_face_persons.json') ) aioclient_mock.get( self.endpoint_url.format("persongroups/test_group2/persons"), text=load_fixture('microsoft_face_persons.json') ) self.config['camera'] = {'platform': 'demo'} with assert_setup_component(3, mf.DOMAIN): setup_component(self.hass, mf.DOMAIN, self.config) assert len(aioclient_mock.mock_calls) == 3 aioclient_mock.post( self.endpoint_url.format( "persongroups/test_group2/persons/" "2ae4935b-9659-44c3-977f-61fac20d0538/persistedFaces"), status=200, text="{}" ) face_person( self.hass, 'test_group2', 'David', 'camera.demo_camera') self.hass.block_till_done() assert len(aioclient_mock.mock_calls) == 4 assert aioclient_mock.mock_calls[3][2] == b'Test'
def test_service_say_russian_config(self, aioclient_mock): """Test service call say.""" calls = mock_service(self.hass, DOMAIN_MP, SERVICE_PLAY_MEDIA) url_param = { 'text': 'HomeAssistant', 'lang': 'ru-RU', 'key': '1234567xx', 'speaker': 'zahar', 'format': 'mp3', 'emotion': 'neutral', 'speed': 1 } aioclient_mock.get( self._base_url, status=200, content=b'test', params=url_param) config = { tts.DOMAIN: { 'platform': 'yandextts', 'api_key': '1234567xx', 'language': 'ru-RU', } } with assert_setup_component(1, tts.DOMAIN): setup_component(self.hass, tts.DOMAIN, config) self.hass.services.call(tts.DOMAIN, 'yandextts_say', { tts.ATTR_MESSAGE: "HomeAssistant", }) self.hass.block_till_done() assert len(aioclient_mock.mock_calls) == 1 assert len(calls) == 1
def test_setup_component_test_entities(self, aioclient_mock): """Set up component.""" aioclient_mock.get( self.endpoint_url.format("persongroups"), text=load_fixture('microsoft_face_persongroups.json') ) aioclient_mock.get( self.endpoint_url.format("persongroups/test_group1/persons"), text=load_fixture('microsoft_face_persons.json') ) aioclient_mock.get( self.endpoint_url.format("persongroups/test_group2/persons"), text=load_fixture('microsoft_face_persons.json') ) with assert_setup_component(3, mf.DOMAIN): setup_component(self.hass, mf.DOMAIN, self.config) assert len(aioclient_mock.mock_calls) == 3 entity_group1 = self.hass.states.get('microsoft_face.test_group1') entity_group2 = self.hass.states.get('microsoft_face.test_group2') assert entity_group1 is not None assert entity_group2 is not None assert entity_group1.attributes['Ryan'] == \ '25985303-c537-4467-b41d-bdb45cd95ca1' assert entity_group1.attributes['David'] == \ '2ae4935b-9659-44c3-977f-61fac20d0538' assert entity_group2.attributes['Ryan'] == \ '25985303-c537-4467-b41d-bdb45cd95ca1' assert entity_group2.attributes['David'] == \ '2ae4935b-9659-44c3-977f-61fac20d0538'
def test_setup_component_and_test_service_with_receive_voice_german(self): """Set up the demo platform and call service and receive voice.""" calls = mock_service(self.hass, DOMAIN_MP, SERVICE_PLAY_MEDIA) config = { tts.DOMAIN: { 'platform': 'demo', 'language': 'de', } } with assert_setup_component(1, tts.DOMAIN): setup_component(self.hass, tts.DOMAIN, config) self.hass.start() self.hass.services.call(tts.DOMAIN, 'demo_say', { tts.ATTR_MESSAGE: "I person is on front of your door.", }) self.hass.block_till_done() assert len(calls) == 1 req = requests.get(calls[0].data[ATTR_MEDIA_CONTENT_ID]) _, demo_data = self.demo_provider.get_tts_audio("bla", "de") demo_data = tts.SpeechManager.write_tags( "265944c108cbb00b2a621be5930513e03a0bb2cd_de_-_demo.mp3", demo_data, self.demo_provider, "I person is on front of your door.", 'de', None) assert req.status_code == 200 assert req.content == demo_data
def test_if_action_after(self): """Test if action was after.""" self.hass.states.set(sun.ENTITY_ID, sun.STATE_ABOVE_HORIZON, { sun.STATE_ATTR_NEXT_RISING: '2015-09-16T14:00:00Z', }) setup_component(self.hass, automation.DOMAIN, { automation.DOMAIN: { 'trigger': { 'platform': 'event', 'event_type': 'test_event', }, 'condition': { 'condition': 'sun', 'after': 'sunrise', }, 'action': { 'service': 'test.automation' } } }) now = datetime(2015, 9, 16, 13, tzinfo=dt_util.UTC) with patch('homeassistant.util.dt.now', return_value=now): self.hass.bus.fire('test_event') self.hass.block_till_done() self.assertEqual(0, len(self.calls)) now = datetime(2015, 9, 16, 15, tzinfo=dt_util.UTC) with patch('homeassistant.util.dt.now', return_value=now): self.hass.bus.fire('test_event') self.hass.block_till_done() self.assertEqual(1, len(self.calls))
def test_service_say_error_msg(self, aioclient_mock): """Test service call say with http error api message.""" calls = mock_service(self.hass, DOMAIN_MP, SERVICE_PLAY_MEDIA) aioclient_mock.post( self.url, data=self.form_data, status=200, content=b'The subscription does not support SSML!' ) config = { tts.DOMAIN: { 'platform': 'voicerss', 'api_key': '1234567xx', } } with assert_setup_component(1, tts.DOMAIN): setup_component(self.hass, tts.DOMAIN, config) self.hass.services.call(tts.DOMAIN, 'voicerss_say', { tts.ATTR_MESSAGE: "I person is on front of your door.", }) self.hass.block_till_done() assert len(calls) == 0 assert len(aioclient_mock.mock_calls) == 1 assert aioclient_mock.mock_calls[0][2] == self.form_data
def test_setup_component_and_test_service_with_base_url_set(self): """Set up the demo platform with ``base_url`` set and call service.""" calls = mock_service(self.hass, DOMAIN_MP, SERVICE_PLAY_MEDIA) config = { tts.DOMAIN: { 'platform': 'demo', 'base_url': 'http://fnord', } } with assert_setup_component(1, tts.DOMAIN): setup_component(self.hass, tts.DOMAIN, config) self.hass.services.call(tts.DOMAIN, 'demo_say', { tts.ATTR_MESSAGE: "I person is on front of your door.", }) self.hass.block_till_done() assert len(calls) == 1 assert calls[0].data[ATTR_MEDIA_CONTENT_TYPE] == MEDIA_TYPE_MUSIC assert calls[0].data[ATTR_MEDIA_CONTENT_ID] == \ "http://fnord" \ "/api/tts_proxy/265944c108cbb00b2a621be5930513e03a0bb2cd" \ "_en_-_demo.mp3"
def test_disable_component_if_invalid_return(self): """Test disabling component if invalid return.""" loader.set_component( 'disabled_component', MockModule('disabled_component', setup=lambda hass, config: None)) assert not setup.setup_component(self.hass, 'disabled_component') assert loader.get_component('disabled_component') is None assert 'disabled_component' not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) loader.set_component( 'disabled_component', MockModule('disabled_component', setup=lambda hass, config: False)) assert not setup.setup_component(self.hass, 'disabled_component') assert loader.get_component('disabled_component') is not None assert 'disabled_component' not in self.hass.config.components self.hass.data.pop(setup.DATA_SETUP) loader.set_component( 'disabled_component', MockModule('disabled_component', setup=lambda hass, config: True)) assert setup.setup_component(self.hass, 'disabled_component') assert loader.get_component('disabled_component') is not None assert 'disabled_component' in self.hass.config.components
def test_service_say_timeout(self, aioclient_mock): """Test service call say with http timeout.""" calls = mock_service(self.hass, DOMAIN_MP, SERVICE_PLAY_MEDIA) aioclient_mock.post( self.url, data=self.form_data, exc=asyncio.TimeoutError()) config = { tts.DOMAIN: { 'platform': 'voicerss', 'api_key': '1234567xx', } } with assert_setup_component(1, tts.DOMAIN): setup_component(self.hass, tts.DOMAIN, config) self.hass.services.call(tts.DOMAIN, 'voicerss_say', { tts.ATTR_MESSAGE: "I person is on front of your door.", }) self.hass.block_till_done() assert len(calls) == 0 assert len(aioclient_mock.mock_calls) == 1 assert aioclient_mock.mock_calls[0][2] == self.form_data
def test_fire_event_sensor(self): """Test fire event.""" self.assertTrue(setup_component(self.hass, 'rfxtrx', { 'rfxtrx': { 'device': '/dev/serial/by-id/usb' + '-RFXCOM_RFXtrx433_A1Y0NJGR-if00-port0', 'dummy': True} })) self.assertTrue(setup_component(self.hass, 'sensor', { 'sensor': {'platform': 'rfxtrx', 'automatic_add': True, 'devices': {'0a520802060100ff0e0269': { 'name': 'Test', rfxtrx.ATTR_FIREEVENT: True} }}})) calls = [] @callback def record_event(event): """Add recorded event to set.""" calls.append(event) self.hass.bus.listen("signal_received", record_event) self.hass.block_till_done() event = rfxtrx.get_rfx_object('0a520802060101ff0f0269') event.data = bytearray(b'\nR\x08\x01\x07\x01\x00\xb8\x1b\x02y') rfxtrx.RECEIVED_EVT_SUBSCRIBERS[0](event) self.hass.block_till_done() self.assertEqual(1, len(calls)) self.assertEqual(calls[0].data, {'entity_id': 'sensor.test'})
def test_sensor_value_from_code(): """Test the setting of value via pilight.""" with assert_setup_component(1): setup_component(HASS, sensor.DOMAIN, { sensor.DOMAIN: { 'platform': 'pilight', 'name': 'test', 'variable': 'test', 'payload': {'protocol': 'test-protocol'}, 'unit_of_measurement': 'fav unit' } }) state = HASS.states.get('sensor.test') assert state.state == 'unknown' unit_of_measurement = state.attributes.get('unit_of_measurement') assert unit_of_measurement == 'fav unit' # Set value from data with correct payload fire_pilight_message(protocol='test-protocol', data={'test': 42}) HASS.block_till_done() state = HASS.states.get('sensor.test') assert state.state == '42'
def test_sunrise_trigger(self): """Test the sunrise trigger.""" self.hass.states.set(sun.ENTITY_ID, sun.STATE_ABOVE_HORIZON, { sun.STATE_ATTR_NEXT_RISING: '2015-09-16T14:00:00Z', }) now = datetime(2015, 9, 13, 23, tzinfo=dt_util.UTC) trigger_time = datetime(2015, 9, 16, 14, tzinfo=dt_util.UTC) with patch('homeassistant.util.dt.utcnow', return_value=now): setup_component(self.hass, automation.DOMAIN, { automation.DOMAIN: { 'trigger': { 'platform': 'sun', 'event': 'sunrise', }, 'action': { 'service': 'test.automation', } } }) fire_time_changed(self.hass, trigger_time) self.hass.block_till_done() self.assertEqual(1, len(self.calls))
def test_setup_component_and_test_with_service_options_def(self, def_mock): """Set up the demo platform and call service with default options.""" calls = mock_service(self.hass, DOMAIN_MP, SERVICE_PLAY_MEDIA) config = { tts.DOMAIN: { 'platform': 'demo', } } with assert_setup_component(1, tts.DOMAIN): setup_component(self.hass, tts.DOMAIN, config) self.hass.services.call(tts.DOMAIN, 'demo_say', { tts.ATTR_MESSAGE: "I person is on front of your door.", tts.ATTR_LANGUAGE: "de", }) self.hass.block_till_done() opt_hash = ctypes.c_size_t(hash(frozenset({'voice': 'alex'}))).value assert len(calls) == 1 assert calls[0].data[ATTR_MEDIA_CONTENT_TYPE] == MEDIA_TYPE_MUSIC assert calls[0].data[ATTR_MEDIA_CONTENT_ID] == \ "{}/api/tts_proxy/265944c108cbb00b2a621be5930513e03a0bb2cd" \ "_de_{}_demo.mp3".format(self.hass.config.api.base_url, opt_hash) assert os.path.isfile(os.path.join( self.default_tts_cache, "265944c108cbb00b2a621be5930513e03a0bb2cd_de_{0}_demo.mp3".format( opt_hash)))
def test_service_say(self, aioclient_mock): """Test service call say.""" calls = mock_service(self.hass, DOMAIN_MP, SERVICE_PLAY_MEDIA) aioclient_mock.post( self.url, data=self.form_data, status=200, content=b'test') config = { tts.DOMAIN: { 'platform': 'voicerss', 'api_key': '1234567xx', } } with assert_setup_component(1, tts.DOMAIN): setup_component(self.hass, tts.DOMAIN, config) self.hass.services.call(tts.DOMAIN, 'voicerss_say', { tts.ATTR_MESSAGE: "I person is on front of your door.", }) self.hass.block_till_done() assert len(calls) == 1 assert len(aioclient_mock.mock_calls) == 1 assert aioclient_mock.mock_calls[0][2] == self.form_data assert calls[0].data[ATTR_MEDIA_CONTENT_ID].find(".mp3") != -1
def test_setup_component_and_test_service_with_service_options_wrong(self): """Set up the demo platform and call service with wrong options.""" calls = mock_service(self.hass, DOMAIN_MP, SERVICE_PLAY_MEDIA) config = { tts.DOMAIN: { 'platform': 'demo', } } with assert_setup_component(1, tts.DOMAIN): setup_component(self.hass, tts.DOMAIN, config) self.hass.services.call(tts.DOMAIN, 'demo_say', { tts.ATTR_MESSAGE: "I person is on front of your door.", tts.ATTR_LANGUAGE: "de", tts.ATTR_OPTIONS: { 'speed': 1 } }) self.hass.block_till_done() opt_hash = ctypes.c_size_t(hash(frozenset({'speed': 1}))).value assert len(calls) == 0 assert not os.path.isfile(os.path.join( self.default_tts_cache, "265944c108cbb00b2a621be5930513e03a0bb2cd_de_{0}_demo.mp3".format( opt_hash)))
def test_setup_component_load_cache_retrieve_without_mem_cache(self): """Set up component and load cache and get without mem cache.""" _, demo_data = self.demo_provider.get_tts_audio("bla", 'en') cache_file = os.path.join( self.default_tts_cache, "265944c108cbb00b2a621be5930513e03a0bb2cd_en_-_demo.mp3") os.mkdir(self.default_tts_cache) with open(cache_file, "wb") as voice_file: voice_file.write(demo_data) config = { tts.DOMAIN: { 'platform': 'demo', 'cache': True, } } with assert_setup_component(1, tts.DOMAIN): setup_component(self.hass, tts.DOMAIN, config) self.hass.start() url = ("{}/api/tts_proxy/265944c108cbb00b2a621be5930513e03a0bb2cd" "_en_-_demo.mp3").format(self.hass.config.api.base_url) req = requests.get(url) assert req.status_code == 200 assert req.content == demo_data
def test_setup_component_and_test_service_clear_cache(self): """Set up the demo platform and call service clear cache.""" calls = mock_service(self.hass, DOMAIN_MP, SERVICE_PLAY_MEDIA) config = { tts.DOMAIN: { 'platform': 'demo', } } with assert_setup_component(1, tts.DOMAIN): setup_component(self.hass, tts.DOMAIN, config) self.hass.services.call(tts.DOMAIN, 'demo_say', { tts.ATTR_MESSAGE: "I person is on front of your door.", }) self.hass.block_till_done() assert len(calls) == 1 assert os.path.isfile(os.path.join( self.default_tts_cache, "265944c108cbb00b2a621be5930513e03a0bb2cd_en_-_demo.mp3")) self.hass.services.call(tts.DOMAIN, tts.SERVICE_CLEAR_CACHE, {}) self.hass.block_till_done() assert not os.path.isfile(os.path.join( self.default_tts_cache, "265944c108cbb00b2a621be5930513e03a0bb2cd_en_-_demo.mp3"))
def test_setup_minimal_config(self, mock_client): """Test the setup with minimal configuration.""" config = {'influxdb': {}} assert setup_component(self.hass, influxdb.DOMAIN, config)
def test_flux_with_multiple_lights(self): """Test the flux switch with multiple light entities.""" platform = loader.get_component(self.hass, 'light.test') platform.init() assert setup_component(self.hass, light.DOMAIN, {light.DOMAIN: {CONF_PLATFORM: 'test'}}) dev1, dev2, dev3 = platform.DEVICES common_light.turn_on(self.hass, entity_id=dev2.entity_id) self.hass.block_till_done() common_light.turn_on(self.hass, entity_id=dev3.entity_id) self.hass.block_till_done() state = self.hass.states.get(dev1.entity_id) assert STATE_ON == state.state assert state.attributes.get('xy_color') is None assert state.attributes.get('brightness') is None state = self.hass.states.get(dev2.entity_id) assert STATE_ON == state.state assert state.attributes.get('xy_color') is None assert state.attributes.get('brightness') is None state = self.hass.states.get(dev3.entity_id) assert STATE_ON == state.state assert state.attributes.get('xy_color') is None assert state.attributes.get('brightness') is None test_time = dt_util.utcnow().replace(hour=12, minute=0, second=0) sunset_time = test_time.replace(hour=17, minute=0, second=0) sunrise_time = test_time.replace(hour=5, minute=0, second=0) def event_date(hass, event, now=None): if event == SUN_EVENT_SUNRISE: print('sunrise {}'.format(sunrise_time)) return sunrise_time print('sunset {}'.format(sunset_time)) return sunset_time with patch('homeassistant.components.switch.flux.dt_utcnow', return_value=test_time), \ patch('homeassistant.helpers.sun.get_astral_event_date', side_effect=event_date): assert setup_component(self.hass, switch.DOMAIN, { switch.DOMAIN: { 'platform': 'flux', 'name': 'flux', 'lights': [dev1.entity_id, dev2.entity_id, dev3.entity_id] } }) turn_on_calls = mock_service( self.hass, light.DOMAIN, SERVICE_TURN_ON) common.turn_on(self.hass, 'switch.flux') self.hass.block_till_done() fire_time_changed(self.hass, test_time) self.hass.block_till_done() call = turn_on_calls[-1] assert call.data[light.ATTR_BRIGHTNESS] == 163 assert call.data[light.ATTR_XY_COLOR] == [0.46, 0.376] call = turn_on_calls[-2] assert call.data[light.ATTR_BRIGHTNESS] == 163 assert call.data[light.ATTR_XY_COLOR] == [0.46, 0.376] call = turn_on_calls[-3] assert call.data[light.ATTR_BRIGHTNESS] == 163 assert call.data[light.ATTR_XY_COLOR] == [0.46, 0.376]
def test_setup_missing_password(self, mock_client): """Test the setup with existing username and missing password.""" config = {'influxdb': {'username': '******'}} assert not setup_component(self.hass, influxdb.DOMAIN, config)
def test_state_changed(self, mock_connection, mock_client): """Test event listener.""" self.hass.bus.listen = mock.MagicMock() assert setup_component( self.hass, datadog.DOMAIN, { datadog.DOMAIN: { "host": "host", "prefix": "ha", "rate": datadog.DEFAULT_RATE, } }, ) assert self.hass.bus.listen.called handler_method = self.hass.bus.listen.call_args_list[1][0][1] valid = {"1": 1, "1.0": 1.0, STATE_ON: 1, STATE_OFF: 0} attributes = {"elevation": 3.2, "temperature": 5.0, "up": True, "down": False} for in_, out in valid.items(): state = mock.MagicMock( domain="sensor", entity_id="sensor.foo.bar", state=in_, attributes=attributes, ) handler_method(mock.MagicMock(data={"new_state": state})) assert mock_client.gauge.call_count == 5 for attribute, value in attributes.items(): value = int(value) if isinstance(value, bool) else value mock_client.gauge.assert_has_calls( [ mock.call( f"ha.sensor.{attribute}", value, sample_rate=1, tags=[f"entity:{state.entity_id}"], ) ] ) assert mock_client.gauge.call_args == mock.call( "ha.sensor", out, sample_rate=1, tags=[f"entity:{state.entity_id}"], ) mock_client.gauge.reset_mock() for invalid in ("foo", "", object): handler_method( mock.MagicMock(data={"new_state": ha.State("domain.test", invalid, {})}) ) assert not mock_client.gauge.called
def test_event_listener_component_override_measurement(self, mock_client): """Test the event listener with overridden measurements.""" config = { 'influxdb': { 'host': 'host', 'username': '******', 'password': '******', 'component_config': { 'sensor.fake_humidity': { 'override_measurement': 'humidity' } }, 'component_config_glob': { 'binary_sensor.*motion': { 'override_measurement': 'motion' } }, 'component_config_domain': { 'climate': { 'override_measurement': 'hvac' } } } } assert setup_component(self.hass, influxdb.DOMAIN, config) self.handler_method = self.hass.bus.listen.call_args_list[0][0][1] test_components = [ { 'domain': 'sensor', 'id': 'fake_humidity', 'res': 'humidity' }, { 'domain': 'binary_sensor', 'id': 'fake_motion', 'res': 'motion' }, { 'domain': 'climate', 'id': 'fake_thermostat', 'res': 'hvac' }, { 'domain': 'other', 'id': 'just_fake', 'res': 'other.just_fake' }, ] for comp in test_components: state = mock.MagicMock(state=1, domain=comp['domain'], entity_id=comp['domain'] + '.' + comp['id'], object_id=comp['id'], attributes={}) event = mock.MagicMock(data={'new_state': state}, time_fired=12345) body = [{ 'measurement': comp['res'], 'tags': { 'domain': comp['domain'], 'entity_id': comp['id'] }, 'time': 12345, 'fields': { 'value': 1, }, }] self.handler_method(event) self.hass.data[influxdb.DOMAIN].block_till_done() self.assertEqual(mock_client.return_value.write_points.call_count, 1) self.assertEqual(mock_client.return_value.write_points.call_args, mock.call(body)) mock_client.return_value.write_points.reset_mock()
def setup_component(): """Set up the component.""" setup.setup_component(self.hass, "comp", {})
def test_invalid_config(self): """Test invalid configuration.""" with assert_setup_component(0): assert not setup_component( self.hass, datadog.DOMAIN, {datadog.DOMAIN: {"host1": "host1"}} )
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_config_valid_keys(self): """Return True when provided with the correct keys.""" with assert_setup_component(0, 'sensor'): assert setup_component(self.hass, 'sensor', TEST_CONFIG)
def test_setup_max_entries(self): """Test the setup of this component with max entries.""" assert setup_component(self.hass, feedreader.DOMAIN, VALID_CONFIG_3)
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 setUp(self): """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() self.assertTrue(setup_component(self.hass, remote.DOMAIN, {'remote': { 'platform': 'demo', }}))
def test_ms_identify_process_image(self, poll_mock, aioclient_mock): """Set up and scan a picture and test plates from event.""" aioclient_mock.get( self.endpoint_url.format("persongroups"), text=load_fixture('microsoft_face_persongroups.json')) aioclient_mock.get( self.endpoint_url.format("persongroups/test_group1/persons"), text=load_fixture('microsoft_face_persons.json')) aioclient_mock.get( self.endpoint_url.format("persongroups/test_group2/persons"), text=load_fixture('microsoft_face_persons.json')) setup_component(self.hass, ip.DOMAIN, self.config) state = self.hass.states.get('camera.demo_camera') url = "{0}{1}".format(self.hass.config.api.base_url, state.attributes.get(ATTR_ENTITY_PICTURE)) face_events = [] @callback def mock_face_event(event): """Mock event.""" face_events.append(event) self.hass.bus.listen('image_processing.detect_face', mock_face_event) aioclient_mock.get(url, content=b'image') aioclient_mock.post(self.endpoint_url.format("detect"), text=load_fixture('microsoft_face_detect.json')) aioclient_mock.post(self.endpoint_url.format("identify"), text=load_fixture('microsoft_face_identify.json')) common.scan(self.hass, entity_id='image_processing.test_local') self.hass.block_till_done() state = self.hass.states.get('image_processing.test_local') assert len(face_events) == 1 assert state.attributes.get('total_faces') == 2 assert state.state == 'David' assert face_events[0].data['name'] == 'David' assert face_events[0].data['confidence'] == float(92) assert face_events[0].data['entity_id'] == \ 'image_processing.test_local' # Test that later, if a request is made that results in no face # being detected, that this is reflected in the state object aioclient_mock.clear_requests() aioclient_mock.post(self.endpoint_url.format("detect"), text="[]") common.scan(self.hass, entity_id='image_processing.test_local') self.hass.block_till_done() state = self.hass.states.get('image_processing.test_local') # No more face events were fired assert len(face_events) == 1 # Total faces and actual qualified number of faces reset to zero assert state.attributes.get('total_faces') == 0 assert state.state == STATE_UNKNOWN