desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'"Test the setup with full configuration.'
@mock.patch('uvcclient.nvr.UVCRemote') @mock.patch.object(uvc, 'UnifiVideoCamera') def test_setup_full_config(self, mock_uvc, mock_remote):
config = {'platform': 'uvc', 'nvr': 'foo', 'password': 'bar', 'port': 123, 'key': 'secret'} fake_cameras = [{'uuid': 'one', 'name': 'Front', 'id': 'id1'}, {'uuid': 'two', 'name': 'Back', 'id': 'id2'}, {'uuid': 'three', 'name': 'Old AirCam', 'id': 'id3'}] def fake_get_camera(uuid): '"Create a fake camera.' if (uuid == 'id3'): return {'model': 'airCam'} else: return {'model': 'UVC'} mock_remote.return_value.index.return_value = fake_cameras mock_remote.return_value.get_camera.side_effect = fake_get_camera mock_remote.return_value.server_version = (3, 2, 0) assert setup_component(self.hass, 'camera', {'camera': config}) self.assertEqual(mock_remote.call_count, 1) self.assertEqual(mock_remote.call_args, mock.call('foo', 123, 'secret')) mock_uvc.assert_has_calls([mock.call(mock_remote.return_value, 'id1', 'Front', 'bar'), mock.call(mock_remote.return_value, 'id2', 'Back', 'bar')])
'"Test the setup with partial configuration.'
@mock.patch('uvcclient.nvr.UVCRemote') @mock.patch.object(uvc, 'UnifiVideoCamera') def test_setup_partial_config(self, mock_uvc, mock_remote):
config = {'platform': 'uvc', 'nvr': 'foo', 'key': 'secret'} fake_cameras = [{'uuid': 'one', 'name': 'Front', 'id': 'id1'}, {'uuid': 'two', 'name': 'Back', 'id': 'id2'}] mock_remote.return_value.index.return_value = fake_cameras mock_remote.return_value.get_camera.return_value = {'model': 'UVC'} mock_remote.return_value.server_version = (3, 2, 0) assert setup_component(self.hass, 'camera', {'camera': config}) self.assertEqual(mock_remote.call_count, 1) self.assertEqual(mock_remote.call_args, mock.call('foo', 7080, 'secret')) mock_uvc.assert_has_calls([mock.call(mock_remote.return_value, 'id1', 'Front', 'ubnt'), mock.call(mock_remote.return_value, 'id2', 'Back', 'ubnt')])
'Test the setup with a v3.1.x server.'
@mock.patch('uvcclient.nvr.UVCRemote') @mock.patch.object(uvc, 'UnifiVideoCamera') def test_setup_partial_config_v31x(self, mock_uvc, mock_remote):
config = {'platform': 'uvc', 'nvr': 'foo', 'key': 'secret'} fake_cameras = [{'uuid': 'one', 'name': 'Front', 'id': 'id1'}, {'uuid': 'two', 'name': 'Back', 'id': 'id2'}] mock_remote.return_value.index.return_value = fake_cameras mock_remote.return_value.get_camera.return_value = {'model': 'UVC'} mock_remote.return_value.server_version = (3, 1, 3) assert setup_component(self.hass, 'camera', {'camera': config}) self.assertEqual(mock_remote.call_count, 1) self.assertEqual(mock_remote.call_args, mock.call('foo', 7080, 'secret')) mock_uvc.assert_has_calls([mock.call(mock_remote.return_value, 'one', 'Front', 'ubnt'), mock.call(mock_remote.return_value, 'two', 'Back', 'ubnt')])
'Test the setup with incomplete configuration.'
@mock.patch.object(uvc, 'UnifiVideoCamera') def test_setup_incomplete_config(self, mock_uvc):
assert setup_component(self.hass, 'camera', {'platform': 'uvc', 'nvr': 'foo'}) assert (not mock_uvc.called) assert setup_component(self.hass, 'camera', {'platform': 'uvc', 'key': 'secret'}) assert (not mock_uvc.called) assert setup_component(self.hass, 'camera', {'platform': 'uvc', 'port': 'invalid'}) assert (not mock_uvc.called)
'Test for NVR errors.'
@mock.patch.object(uvc, 'UnifiVideoCamera') @mock.patch('uvcclient.nvr.UVCRemote') def test_setup_nvr_errors(self, mock_remote, mock_uvc):
errors = [nvr.NotAuthorized, nvr.NvrError, requests.exceptions.ConnectionError] config = {'platform': 'uvc', 'nvr': 'foo', 'key': 'secret'} for error in errors: mock_remote.return_value.index.side_effect = error assert setup_component(self.hass, 'camera', config) assert (not mock_uvc.called)
'"Setup the mock camera.'
def setup_method(self, method):
self.nvr = mock.MagicMock() self.uuid = 'uuid' self.name = 'name' self.password = 'seekret' self.uvc = uvc.UnifiVideoCamera(self.nvr, self.uuid, self.name, self.password) self.nvr.get_camera.return_value = {'model': 'UVC Fake', 'recordingSettings': {'fullTimeRecordEnabled': True}, 'host': 'host-a', 'internalHost': 'host-b', 'username': 'admin'} self.nvr.server_version = (3, 2, 0)
'"Test the properties.'
def test_properties(self):
self.assertEqual(self.name, self.uvc.name) self.assertTrue(self.uvc.is_recording) self.assertEqual('Ubiquiti', self.uvc.brand) self.assertEqual('UVC Fake', self.uvc.model)
'"Test the login.'
@mock.patch('uvcclient.store.get_info_store') @mock.patch('uvcclient.camera.UVCCameraClientV320') def test_login(self, mock_camera, mock_store):
self.uvc._login() self.assertEqual(mock_camera.call_count, 1) self.assertEqual(mock_camera.call_args, mock.call('host-a', 'admin', 'seekret')) self.assertEqual(mock_camera.return_value.login.call_count, 1) self.assertEqual(mock_camera.return_value.login.call_args, mock.call())
'Test login with v3.1.x server.'
@mock.patch('uvcclient.store.get_info_store') @mock.patch('uvcclient.camera.UVCCameraClient') def test_login_v31x(self, mock_camera, mock_store):
self.nvr.server_version = (3, 1, 3) self.uvc._login() self.assertEqual(mock_camera.call_count, 1) self.assertEqual(mock_camera.call_args, mock.call('host-a', 'admin', 'seekret')) self.assertEqual(mock_camera.return_value.login.call_count, 1) self.assertEqual(mock_camera.return_value.login.call_args, mock.call())
'"Test the login tries.'
@mock.patch('uvcclient.store.get_info_store') @mock.patch('uvcclient.camera.UVCCameraClientV320') def test_login_tries_both_addrs_and_caches(self, mock_camera, mock_store):
responses = [0] def fake_login(*a): 'Fake login.' try: responses.pop(0) raise socket.error except IndexError: pass mock_store.return_value.get_camera_password.return_value = None mock_camera.return_value.login.side_effect = fake_login self.uvc._login() self.assertEqual(2, mock_camera.call_count) self.assertEqual('host-b', self.uvc._connect_addr) mock_camera.reset_mock() self.uvc._login() self.assertEqual(mock_camera.call_count, 1) self.assertEqual(mock_camera.call_args, mock.call('host-b', 'admin', 'seekret')) self.assertEqual(mock_camera.return_value.login.call_count, 1) self.assertEqual(mock_camera.return_value.login.call_args, mock.call())
'"Test if login fails properly.'
@mock.patch('uvcclient.store.get_info_store') @mock.patch('uvcclient.camera.UVCCameraClientV320') def test_login_fails_both_properly(self, mock_camera, mock_store):
mock_camera.return_value.login.side_effect = socket.error self.assertEqual(None, self.uvc._login()) self.assertEqual(None, self.uvc._connect_addr)
'"Test retrieving failure.'
def test_camera_image_tries_login_bails_on_failure(self):
with mock.patch.object(self.uvc, '_login') as mock_login: mock_login.return_value = False self.assertEqual(None, self.uvc.camera_image()) self.assertEqual(mock_login.call_count, 1) self.assertEqual(mock_login.call_args, mock.call())
'"Test the login state.'
def test_camera_image_logged_in(self):
self.uvc._camera = mock.MagicMock() self.assertEqual(self.uvc._camera.get_snapshot.return_value, self.uvc.camera_image())
'"Test the camera image error.'
def test_camera_image_error(self):
self.uvc._camera = mock.MagicMock() self.uvc._camera.get_snapshot.side_effect = camera.CameraConnectError self.assertEqual(None, self.uvc.camera_image())
'"Test the re-authentication.'
def test_camera_image_reauths(self):
responses = [0] def fake_snapshot(): 'Fake snapshot.' try: responses.pop() raise camera.CameraAuthError() except IndexError: pass return 'image' self.uvc._camera = mock.MagicMock() self.uvc._camera.get_snapshot.side_effect = fake_snapshot with mock.patch.object(self.uvc, '_login') as mock_login: self.assertEqual('image', self.uvc.camera_image()) self.assertEqual(mock_login.call_count, 1) self.assertEqual(mock_login.call_args, mock.call()) self.assertEqual([], responses)
'"Test if the re-authentication only happens once.'
def test_camera_image_reauths_only_once(self):
self.uvc._camera = mock.MagicMock() self.uvc._camera.get_snapshot.side_effect = camera.CameraAuthError with mock.patch.object(self.uvc, '_login') as mock_login: self.assertRaises(camera.CameraAuthError, self.uvc.camera_image) self.assertEqual(mock_login.call_count, 1) self.assertEqual(mock_login.call_args, mock.call())
'Setup things to be run when tests are started.'
def setup_method(self):
self.hass = get_test_home_assistant()
'Stop everything that was started.'
def teardown_method(self):
self.hass.stop()
'Setup demo platfrom on camera component.'
def test_setup_component(self):
config = {camera.DOMAIN: {'platform': 'demo'}} with assert_setup_component(1, camera.DOMAIN): setup_component(self.hass, camera.DOMAIN, config)
'Setup things to be run when tests are started.'
def setup_method(self):
self.hass = get_test_home_assistant() setup_component(self.hass, http.DOMAIN, {http.DOMAIN: {http.CONF_SERVER_PORT: get_test_instance_port()}}) config = {camera.DOMAIN: {'platform': 'demo'}} setup_component(self.hass, camera.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))
'Stop everything that was started.'
def teardown_method(self):
self.hass.stop()
'Grab a image from camera entity.'
@patch('homeassistant.components.camera.demo.DemoCamera.camera_image', autospec=True, return_value='Test') def test_get_image_from_camera(self, mock_camera):
self.hass.start() image = run_coroutine_threadsafe(camera.async_get_image(self.hass, 'camera.demo_camera'), self.hass.loop).result() assert mock_camera.called assert (image == 'Test')
'Try to get image without exists camera.'
def test_get_image_without_exists_camera(self):
self.hass.states.remove('camera.demo_camera') with pytest.raises(HomeAssistantError): run_coroutine_threadsafe(camera.async_get_image(self.hass, 'camera.demo_camera'), self.hass.loop).result()
'Try to get image with timeout.'
def test_get_image_with_timeout(self, aioclient_mock):
aioclient_mock.get(self.url, exc=asyncio.TimeoutError()) with pytest.raises(HomeAssistantError): run_coroutine_threadsafe(camera.async_get_image(self.hass, 'camera.demo_camera'), self.hass.loop).result() assert (len(aioclient_mock.mock_calls) == 1)
'Try to get image with bad http status.'
def test_get_image_with_bad_http_state(self, aioclient_mock):
aioclient_mock.get(self.url, status=400) with pytest.raises(HomeAssistantError): run_coroutine_threadsafe(camera.async_get_image(self.hass, 'camera.demo_camera'), self.hass.loop).result() assert (len(aioclient_mock.mock_calls) == 1)
'Setup things to be run when tests are started.'
def setup_method(self, method):
self.hass = get_test_home_assistant()
'Stop everything that was started.'
def teardown_method(self, method):
self.hass.stop()
'Test setup with wrong configuration.'
def test_wrong_config(self):
to_try = [{'invalid space': {'url': 'https://home-assistant.io'}}, {'router': {'url': 'not-a-url'}}] for conf in to_try: assert (not setup.setup_component(self.hass, 'panel_iframe', {'panel_iframe': conf}))
'Test correct config.'
@patch.dict('homeassistant.components.frontend.FINGERPRINTS', {'panels/ha-panel-iframe.html': 'md5md5'}) def test_correct_config(self):
assert setup.setup_component(self.hass, 'panel_iframe', {'panel_iframe': {'router': {'icon': 'mdi:network-wireless', 'title': 'Router', 'url': 'http://192.168.1.1'}, 'weather': {'icon': 'mdi:weather', 'title': 'Weather', 'url': 'https://www.wunderground.com/us/ca/san-diego'}}}) assert (self.hass.data[frontend.DATA_PANELS].get('router') == {'component_name': 'iframe', 'config': {'url': 'http://192.168.1.1'}, 'icon': 'mdi:network-wireless', 'title': 'Router', 'url': '/frontend/panels/iframe-md5md5.html', 'url_path': 'router'}) assert (self.hass.data[frontend.DATA_PANELS].get('weather') == {'component_name': 'iframe', 'config': {'url': 'https://www.wunderground.com/us/ca/san-diego'}, 'icon': 'mdi:weather', 'title': 'Weather', 'url': '/frontend/panels/iframe-md5md5.html', 'url_path': 'weather'})
'Setup things to be run when tests are started.'
@mock.patch('pylitejet.LiteJet') def setup_method(self, method, mock_pylitejet):
self.hass = get_test_home_assistant() self.hass.start() def get_scene_name(number): return ('Mock Scene #' + str(number)) self.mock_lj = mock_pylitejet.return_value self.mock_lj.loads.return_value = range(0) self.mock_lj.button_switches.return_value = range(0) self.mock_lj.all_switches.return_value = range(0) self.mock_lj.scenes.return_value = range(1, 3) self.mock_lj.get_scene_name.side_effect = get_scene_name assert setup.setup_component(self.hass, litejet.DOMAIN, {'litejet': {'port': '/tmp/this_will_be_mocked'}}) self.hass.block_till_done()
'Stop everything that was started.'
def teardown_method(self, method):
self.hass.stop()
'Get the current scene.'
def scene(self):
return self.hass.states.get(ENTITY_SCENE)
'Get the other scene.'
def other_scene(self):
return self.hass.states.get(ENTITY_OTHER_SCENE)
'Test activating the scene.'
def test_activate(self):
scene.activate(self.hass, ENTITY_SCENE) self.hass.block_till_done() self.mock_lj.activate_scene.assert_called_once_with(ENTITY_SCENE_NUMBER)
'Setup things to be run when tests are started.'
def setUp(self):
self.hass = get_test_home_assistant() test_light = loader.get_component('light.test') test_light.init() self.assertTrue(setup_component(self.hass, light.DOMAIN, {light.DOMAIN: {'platform': 'test'}})) (self.light_1, self.light_2) = test_light.DEVICES[0:2] light.turn_off(self.hass, [self.light_1.entity_id, self.light_2.entity_id]) self.hass.block_till_done() self.assertFalse(self.light_1.is_on) self.assertFalse(self.light_2.is_on)
'Stop everything that was started.'
def tearDown(self):
self.hass.stop()
'Test the usage of YAML aliases and anchors. The following test scene configuration is equivalent to: scene: - name: test entities: light_1: &light_1_state state: \'on\' brightness: 100 light_2: *light_1_state When encountering a YAML alias/anchor, the PyYAML parser will use a reference to the original dictionary, instead of creating a copy, so care needs to be taken to not modify the original.'
def test_config_yaml_alias_anchor(self):
entity_state = {'state': 'on', 'brightness': 100} self.assertTrue(setup_component(self.hass, scene.DOMAIN, {'scene': [{'name': 'test', 'entities': {self.light_1.entity_id: entity_state, self.light_2.entity_id: entity_state}}]})) scene.activate(self.hass, 'scene.test') self.hass.block_till_done() self.assertTrue(self.light_1.is_on) self.assertTrue(self.light_2.is_on) self.assertEqual(100, self.light_1.last_call('turn_on')[1].get('brightness')) self.assertEqual(100, self.light_2.last_call('turn_on')[1].get('brightness'))
'Test parsing of booleans in yaml config.'
def test_config_yaml_bool(self):
config = 'scene:\n - name: test\n entities:\n {0}: on\n {1}:\n state: on\n brightness: 100\n'.format(self.light_1.entity_id, self.light_2.entity_id) with io.StringIO(config) as file: doc = yaml.yaml.safe_load(file) self.assertTrue(setup_component(self.hass, scene.DOMAIN, doc)) scene.activate(self.hass, 'scene.test') self.hass.block_till_done() self.assertTrue(self.light_1.is_on) self.assertTrue(self.light_2.is_on) self.assertEqual(100, self.light_2.last_call('turn_on')[1].get('brightness'))
'Test active scene.'
def test_activate_scene(self):
self.assertTrue(setup_component(self.hass, scene.DOMAIN, {'scene': [{'name': 'test', 'entities': {self.light_1.entity_id: 'on', self.light_2.entity_id: {'state': 'on', 'brightness': 100}}}]})) scene.activate(self.hass, 'scene.test') self.hass.block_till_done() self.assertTrue(self.light_1.is_on) self.assertTrue(self.light_2.is_on) self.assertEqual(100, self.light_2.last_call('turn_on')[1].get('brightness'))
'Setup things to be run when tests are started.'
def setUp(self):
self.hass = get_test_home_assistant()
'Stop everything that was started.'
def tearDown(self):
self.hass.stop()
'Test retrieving sun setting and rising.'
def test_setting_rising(self):
utc_now = datetime(2016, 11, 1, 8, 0, 0, tzinfo=dt_util.UTC) with patch('homeassistant.helpers.condition.dt_util.utcnow', return_value=utc_now): setup_component(self.hass, sun.DOMAIN, {sun.DOMAIN: {sun.CONF_ELEVATION: 0}}) self.hass.block_till_done() state = self.hass.states.get(sun.ENTITY_ID) from astral import Astral astral = Astral() utc_today = utc_now.date() latitude = self.hass.config.latitude longitude = self.hass.config.longitude mod = (-1) while True: next_dawn = astral.dawn_utc((utc_today + timedelta(days=mod)), latitude, longitude) if (next_dawn > utc_now): break mod += 1 mod = (-1) while True: next_dusk = astral.dusk_utc((utc_today + timedelta(days=mod)), latitude, longitude) if (next_dusk > utc_now): break mod += 1 mod = (-1) while True: next_midnight = astral.solar_midnight_utc((utc_today + timedelta(days=mod)), longitude) if (next_midnight > utc_now): break mod += 1 mod = (-1) while True: next_noon = astral.solar_noon_utc((utc_today + timedelta(days=mod)), longitude) if (next_noon > utc_now): break mod += 1 mod = (-1) while True: next_rising = astral.sunrise_utc((utc_today + timedelta(days=mod)), latitude, longitude) if (next_rising > utc_now): break mod += 1 mod = (-1) while True: next_setting = astral.sunset_utc((utc_today + timedelta(days=mod)), latitude, longitude) if (next_setting > utc_now): break mod += 1 self.assertEqual(next_dawn, dt_util.parse_datetime(state.attributes[sun.STATE_ATTR_NEXT_DAWN])) self.assertEqual(next_dusk, dt_util.parse_datetime(state.attributes[sun.STATE_ATTR_NEXT_DUSK])) self.assertEqual(next_midnight, dt_util.parse_datetime(state.attributes[sun.STATE_ATTR_NEXT_MIDNIGHT])) self.assertEqual(next_noon, dt_util.parse_datetime(state.attributes[sun.STATE_ATTR_NEXT_NOON])) self.assertEqual(next_rising, dt_util.parse_datetime(state.attributes[sun.STATE_ATTR_NEXT_RISING])) self.assertEqual(next_setting, dt_util.parse_datetime(state.attributes[sun.STATE_ATTR_NEXT_SETTING]))
'Test if the state changes at next setting/rising.'
def test_state_change(self):
now = datetime(2016, 6, 1, 8, 0, 0, tzinfo=dt_util.UTC) with patch('homeassistant.helpers.condition.dt_util.utcnow', return_value=now): setup_component(self.hass, sun.DOMAIN, {sun.DOMAIN: {sun.CONF_ELEVATION: 0}}) self.hass.block_till_done() test_time = dt_util.parse_datetime(self.hass.states.get(sun.ENTITY_ID).attributes[sun.STATE_ATTR_NEXT_RISING]) self.assertIsNotNone(test_time) self.assertEqual(sun.STATE_BELOW_HORIZON, self.hass.states.get(sun.ENTITY_ID).state) self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {ha.ATTR_NOW: (test_time + timedelta(seconds=5))}) self.hass.block_till_done() self.assertEqual(sun.STATE_ABOVE_HORIZON, self.hass.states.get(sun.ENTITY_ID).state)
'Test location in Norway where the sun doesn\'t set in summer.'
def test_norway_in_june(self):
self.hass.config.latitude = 69.6 self.hass.config.longitude = 18.8 june = datetime(2016, 6, 1, tzinfo=dt_util.UTC) with patch('homeassistant.helpers.condition.dt_util.utcnow', return_value=june): assert setup_component(self.hass, sun.DOMAIN, {sun.DOMAIN: {sun.CONF_ELEVATION: 0}}) state = self.hass.states.get(sun.ENTITY_ID) assert (state is not None) assert (dt_util.parse_datetime(state.attributes[sun.STATE_ATTR_NEXT_RISING]) == datetime(2016, 7, 25, 23, 23, 39, tzinfo=dt_util.UTC)) assert (dt_util.parse_datetime(state.attributes[sun.STATE_ATTR_NEXT_SETTING]) == datetime(2016, 7, 26, 22, 19, 1, tzinfo=dt_util.UTC))
'Mock add devices.'
def add_devices(self, devices):
for device in devices: self.DEVICES.append(device)
'Initialize values for this testcase class.'
def setUp(self):
self.hass = get_test_home_assistant() self.mock_kira = MagicMock() self.hass.data[kira.DOMAIN] = {kira.CONF_REMOTE: {}} self.hass.data[kira.DOMAIN][kira.CONF_REMOTE]['kira'] = self.mock_kira
'Stop everything that was started.'
def tearDown(self):
self.hass.stop()
'Test Kira\'s ability to send commands.'
def test_service_call(self):
kira.setup_platform(self.hass, TEST_CONFIG, self.add_devices, DISCOVERY_INFO) assert (len(self.DEVICES) == 1) remote = self.DEVICES[0] assert (remote.name == 'kira') command = ['FAKE_COMMAND'] device = 'FAKE_DEVICE' commandTuple = (command[0], device) remote.send_command(device=device, command=command) self.mock_kira.sendCode.assert_called_with(commandTuple)
'Setup things to be run when tests are started.'
def setUp(self):
self.hass = get_test_home_assistant()
'Stop everything that was started.'
def tearDown(self):
self.hass.stop()
'Test is_on.'
def test_is_on(self):
self.hass.states.set('remote.test', STATE_ON) self.assertTrue(remote.is_on(self.hass, 'remote.test')) self.hass.states.set('remote.test', STATE_OFF) self.assertFalse(remote.is_on(self.hass, 'remote.test')) self.hass.states.set(remote.ENTITY_ID_ALL_REMOTES, STATE_ON) self.assertTrue(remote.is_on(self.hass)) self.hass.states.set(remote.ENTITY_ID_ALL_REMOTES, STATE_OFF) self.assertFalse(remote.is_on(self.hass))
'Test turn_on.'
def test_turn_on(self):
turn_on_calls = mock_service(self.hass, remote.DOMAIN, SERVICE_TURN_ON) remote.turn_on(self.hass, entity_id='entity_id_val') self.hass.block_till_done() self.assertEqual(1, len(turn_on_calls)) call = turn_on_calls[(-1)] self.assertEqual(remote.DOMAIN, call.domain)
'Test turn_off.'
def test_turn_off(self):
turn_off_calls = mock_service(self.hass, remote.DOMAIN, SERVICE_TURN_OFF) remote.turn_off(self.hass, entity_id='entity_id_val') self.hass.block_till_done() self.assertEqual(1, len(turn_off_calls)) call = turn_off_calls[(-1)] self.assertEqual(remote.DOMAIN, call.domain) self.assertEqual(SERVICE_TURN_OFF, call.service) self.assertEqual('entity_id_val', call.data[ATTR_ENTITY_ID])
'Test send_command.'
def test_send_command(self):
send_command_calls = mock_service(self.hass, remote.DOMAIN, SERVICE_SEND_COMMAND) remote.send_command(self.hass, entity_id='entity_id_val', device='test_device', command=['test_command'], num_repeats='4', delay_secs='0.6') self.hass.block_till_done() self.assertEqual(1, len(send_command_calls)) call = send_command_calls[(-1)] self.assertEqual(remote.DOMAIN, call.domain) self.assertEqual(SERVICE_SEND_COMMAND, call.service) self.assertEqual('entity_id_val', call.data[ATTR_ENTITY_ID])
'Test the provided services.'
def test_services(self):
self.assertTrue(setup_component(self.hass, remote.DOMAIN, TEST_PLATFORM))
'Setup things to be run when tests are started.'
def setUp(self):
self.hass = get_test_home_assistant() self.assertTrue(setup_component(self.hass, remote.DOMAIN, {'remote': {'platform': 'demo'}}))
'Stop down everything that was started.'
def tearDown(self):
self.hass.stop()
'Test if services call the entity methods as expected.'
def test_methods(self):
remote.turn_on(self.hass, entity_id=ENTITY_ID) self.hass.block_till_done() state = self.hass.states.get(ENTITY_ID) self.assertEqual(state.state, STATE_ON) remote.turn_off(self.hass, entity_id=ENTITY_ID) self.hass.block_till_done() state = self.hass.states.get(ENTITY_ID) self.assertEqual(state.state, STATE_OFF) remote.turn_on(self.hass, entity_id=ENTITY_ID) self.hass.block_till_done() state = self.hass.states.get(ENTITY_ID) self.assertEqual(state.state, STATE_ON) remote.send_command(self.hass, 'test', entity_id=ENTITY_ID) self.hass.block_till_done() state = self.hass.states.get(ENTITY_ID) self.assertEqual(state.attributes, {'friendly_name': 'Remote One', 'last_command_sent': 'test'})
'Setup things to be run when tests are started.'
def setUp(self):
self.hass = get_test_home_assistant() self.scanner = loader.get_component('device_tracker.test').get_scanner(None, None) self.scanner.reset() self.scanner.come_home('DEV1') loader.get_component('light.test').init() with patch('homeassistant.components.device_tracker.load_yaml_config_file', return_value={'device_1': {'hide_if_away': False, 'mac': 'DEV1', 'name': 'Unnamed Device', 'picture': 'http://example.com/dev1.jpg', 'track': True, 'vendor': None}, 'device_2': {'hide_if_away': False, 'mac': 'DEV2', 'name': 'Unnamed Device', 'picture': 'http://example.com/dev2.jpg', 'track': True, 'vendor': None}}): self.assertTrue(setup_component(self.hass, device_tracker.DOMAIN, {device_tracker.DOMAIN: {CONF_PLATFORM: 'test'}})) self.assertTrue(setup_component(self.hass, light.DOMAIN, {light.DOMAIN: {CONF_PLATFORM: 'test'}}))
'Stop everything that was started.'
def tearDown(self):
self.hass.stop()
'Test lights go on when there is someone home and the sun sets.'
def test_lights_on_when_sun_sets(self):
test_time = datetime(2017, 4, 5, 1, 2, 3, tzinfo=dt_util.UTC) with patch('homeassistant.util.dt.utcnow', return_value=test_time): self.assertTrue(setup_component(self.hass, device_sun_light_trigger.DOMAIN, {device_sun_light_trigger.DOMAIN: {}})) light.turn_off(self.hass) self.hass.block_till_done() test_time = test_time.replace(hour=3) with patch('homeassistant.util.dt.utcnow', return_value=test_time): fire_time_changed(self.hass, test_time) self.hass.block_till_done() self.assertTrue(light.is_on(self.hass))
'Test lights turn off when everyone leaves the house.'
def test_lights_turn_off_when_everyone_leaves(self):
light.turn_on(self.hass) self.hass.block_till_done() self.assertTrue(setup_component(self.hass, device_sun_light_trigger.DOMAIN, {device_sun_light_trigger.DOMAIN: {}})) self.hass.states.set(device_tracker.ENTITY_ID_ALL_DEVICES, STATE_NOT_HOME) self.hass.block_till_done() self.assertFalse(light.is_on(self.hass))
'Test lights turn on when coming home after sun set.'
def test_lights_turn_on_when_coming_home_after_sun_set(self):
test_time = datetime(2017, 4, 5, 3, 2, 3, tzinfo=dt_util.UTC) with patch('homeassistant.util.dt.utcnow', return_value=test_time): light.turn_off(self.hass) self.hass.block_till_done() self.assertTrue(setup_component(self.hass, device_sun_light_trigger.DOMAIN, {device_sun_light_trigger.DOMAIN: {}})) self.hass.states.set(device_tracker.ENTITY_ID_FORMAT.format('device_2'), STATE_HOME) self.hass.block_till_done() self.assertTrue(light.is_on(self.hass))
'Setup things to be run when tests are started.'
def setUp(self):
self.hass = get_test_home_assistant()
'Stop everything that was started.'
def tearDown(self):
self.hass.stop()
'Test setup component.'
@patch('homeassistant.components.google.do_authentication') def test_setup_component(self, mock_do_auth):
config = {'google': {'client_id': 'id', 'client_secret': 'secret'}} self.assertTrue(setup_component(self.hass, 'google', config))
'Test getting the calendar info.'
def test_get_calendar_info(self):
calendar = {'id': '[email protected]', 'etag': '"3584134138943410"', 'timeZone': 'UTC', 'accessRole': 'reader', 'foregroundColor': '#000000', 'selected': True, 'kind': 'calendar#calendarListEntry', 'backgroundColor': '#16a765', 'description': 'Test Calendar', 'summary': 'We are, we are, a... Test Calendar', 'colorId': '8', 'defaultReminders': [], 'track': True} calendar_info = google.get_calendar_info(self.hass, calendar) self.assertEqual(calendar_info, {'cal_id': '[email protected]', 'entities': [{'device_id': 'we_are_we_are_a_test_calendar', 'name': 'We are, we are, a... Test Calendar', 'track': True}]})
'Test when a calendar is found.'
def test_found_calendar(self):
calendar_service = google.GoogleCalendarService(self.hass.config.path(google.TOKEN_FILE)) self.assertTrue(google.setup_services(self.hass, True, calendar_service))
'Setup things to be run when tests are started.'
def setup_method(self, method):
self.hass = get_test_home_assistant() self.gf = graphite.GraphiteFeeder(self.hass, 'foo', 123, 'ha')
'Stop everything that was started.'
def teardown_method(self, method):
self.hass.stop()
'Test setup.'
@patch('socket.socket') def test_setup(self, mock_socket):
assert setup_component(self.hass, graphite.DOMAIN, {'graphite': {}}) self.assertEqual(mock_socket.call_count, 1) self.assertEqual(mock_socket.call_args, mock.call(socket.AF_INET, socket.SOCK_STREAM))
'Test setup with full configuration.'
@patch('socket.socket') @patch('homeassistant.components.graphite.GraphiteFeeder') def test_full_config(self, mock_gf, mock_socket):
config = {'graphite': {'host': 'foo', 'port': 123, 'prefix': 'me'}} self.assertTrue(setup_component(self.hass, graphite.DOMAIN, config)) self.assertEqual(mock_gf.call_count, 1) self.assertEqual(mock_gf.call_args, mock.call(self.hass, 'foo', 123, 'me')) self.assertEqual(mock_socket.call_count, 1) self.assertEqual(mock_socket.call_args, mock.call(socket.AF_INET, socket.SOCK_STREAM))
'Test setup with invalid port.'
@patch('socket.socket') @patch('homeassistant.components.graphite.GraphiteFeeder') def test_config_port(self, mock_gf, mock_socket):
config = {'graphite': {'host': 'foo', 'port': 2003}} self.assertTrue(setup_component(self.hass, graphite.DOMAIN, config)) self.assertTrue(mock_gf.called) self.assertEqual(mock_socket.call_count, 1) self.assertEqual(mock_socket.call_args, mock.call(socket.AF_INET, socket.SOCK_STREAM))
'Test the subscription.'
def test_subscribe(self):
fake_hass = mock.MagicMock() gf = graphite.GraphiteFeeder(fake_hass, 'foo', 123, 'ha') fake_hass.bus.listen_once.has_calls([mock.call(EVENT_HOMEASSISTANT_START, gf.start_listen), mock.call(EVENT_HOMEASSISTANT_STOP, gf.shutdown)]) self.assertEqual(fake_hass.bus.listen.call_count, 1) self.assertEqual(fake_hass.bus.listen.call_args, mock.call(EVENT_STATE_CHANGED, gf.event_listener))
'Test the start.'
def test_start(self):
with mock.patch.object(self.gf, 'start') as mock_start: self.gf.start_listen('event') self.assertEqual(mock_start.call_count, 1) self.assertEqual(mock_start.call_args, mock.call())
'Test the shutdown.'
def test_shutdown(self):
with mock.patch.object(self.gf, '_queue') as mock_queue: self.gf.shutdown('event') self.assertEqual(mock_queue.put.call_count, 1) self.assertEqual(mock_queue.put.call_args, mock.call(self.gf._quit_object))
'Test the event listener.'
def test_event_listener(self):
with mock.patch.object(self.gf, '_queue') as mock_queue: self.gf.event_listener('foo') self.assertEqual(mock_queue.put.call_count, 1) self.assertEqual(mock_queue.put.call_args, mock.call('foo'))
'Test the reporting with attributes.'
@patch('time.time') def test_report_attributes(self, mock_time):
mock_time.return_value = 12345 attrs = {'foo': 1, 'bar': 2.0, 'baz': True, 'bat': 'NaN'} expected = ['ha.entity.state 0.000000 12345', 'ha.entity.foo 1.000000 12345', 'ha.entity.bar 2.000000 12345', 'ha.entity.baz 1.000000 12345'] state = mock.MagicMock(state=0, attributes=attrs) with mock.patch.object(self.gf, '_send_to_graphite') as mock_send: self.gf._report_attributes('entity', state) actual = mock_send.call_args_list[0][0][0].split('\n') self.assertEqual(sorted(expected), sorted(actual))
'Test the reporting with strings.'
@patch('time.time') def test_report_with_string_state(self, mock_time):
mock_time.return_value = 12345 expected = ['ha.entity.foo 1.000000 12345', 'ha.entity.state 1.000000 12345'] state = mock.MagicMock(state='above_horizon', attributes={'foo': 1.0}) with mock.patch.object(self.gf, '_send_to_graphite') as mock_send: self.gf._report_attributes('entity', state) actual = mock_send.call_args_list[0][0][0].split('\n') self.assertEqual(sorted(expected), sorted(actual))
'Test the reporting with binary state.'
@patch('time.time') def test_report_with_binary_state(self, mock_time):
mock_time.return_value = 12345 state = ha.State('domain.entity', STATE_ON, {'foo': 1.0}) with mock.patch.object(self.gf, '_send_to_graphite') as mock_send: self.gf._report_attributes('entity', state) expected = ['ha.entity.foo 1.000000 12345', 'ha.entity.state 1.000000 12345'] actual = mock_send.call_args_list[0][0][0].split('\n') self.assertEqual(sorted(expected), sorted(actual)) state.state = STATE_OFF with mock.patch.object(self.gf, '_send_to_graphite') as mock_send: self.gf._report_attributes('entity', state) expected = ['ha.entity.foo 1.000000 12345', 'ha.entity.state 0.000000 12345'] actual = mock_send.call_args_list[0][0][0].split('\n') self.assertEqual(sorted(expected), sorted(actual))
'Test the sending with errors.'
@patch('time.time') def test_send_to_graphite_errors(self, mock_time):
mock_time.return_value = 12345 state = ha.State('domain.entity', STATE_ON, {'foo': 1.0}) with mock.patch.object(self.gf, '_send_to_graphite') as mock_send: mock_send.side_effect = socket.error self.gf._report_attributes('entity', state) mock_send.side_effect = socket.gaierror self.gf._report_attributes('entity', state)
'Test the sending of data.'
@patch('socket.socket') def test_send_to_graphite(self, mock_socket):
self.gf._send_to_graphite('foo') self.assertEqual(mock_socket.call_count, 1) self.assertEqual(mock_socket.call_args, mock.call(socket.AF_INET, socket.SOCK_STREAM)) sock = mock_socket.return_value self.assertEqual(sock.connect.call_count, 1) self.assertEqual(sock.connect.call_args, mock.call(('foo', 123))) self.assertEqual(sock.sendall.call_count, 1) self.assertEqual(sock.sendall.call_args, mock.call('foo'.encode('ascii'))) self.assertEqual(sock.send.call_count, 1) self.assertEqual(sock.send.call_args, mock.call('\n'.encode('ascii'))) self.assertEqual(sock.close.call_count, 1) self.assertEqual(sock.close.call_args, mock.call())
'Test the stops.'
def test_run_stops(self):
with mock.patch.object(self.gf, '_queue') as mock_queue: mock_queue.get.return_value = self.gf._quit_object self.assertEqual(None, self.gf.run()) self.assertEqual(mock_queue.get.call_count, 1) self.assertEqual(mock_queue.get.call_args, mock.call()) self.assertEqual(mock_queue.task_done.call_count, 1) self.assertEqual(mock_queue.task_done.call_args, mock.call())
'Test the running.'
def test_run(self):
runs = [] event = mock.MagicMock(event_type=EVENT_STATE_CHANGED, data={'entity_id': 'entity', 'new_state': mock.MagicMock()}) def fake_get(): if (len(runs) >= 2): return self.gf._quit_object elif runs: runs.append(1) return mock.MagicMock(event_type='somethingelse', data={'new_event': None}) else: runs.append(1) return event with mock.patch.object(self.gf, '_queue') as mock_queue: with mock.patch.object(self.gf, '_report_attributes') as mock_r: mock_queue.get.side_effect = fake_get self.gf.run() self.assertEqual(3, mock_queue.task_done.call_count) self.assertEqual(mock_r.call_count, 1) self.assertEqual(mock_r.call_args, mock.call('entity', event.data['new_state']))
'Setup things to be run when tests are started.'
def setup_method(self):
self.hass = get_test_home_assistant() self.config = {mf.DOMAIN: {'api_key': '12345678abcdef'}} self.endpoint_url = 'https://westus.{0}'.format(mf.FACE_API_URL)
'Stop everything that was started.'
def teardown_method(self):
self.hass.stop()
'Setup component.'
@patch('homeassistant.components.microsoft_face.MicrosoftFace.update_store', return_value=mock_coro()) def test_setup_component(self, mock_update):
with assert_setup_component(3, mf.DOMAIN): setup_component(self.hass, mf.DOMAIN, self.config)
'Setup component without api key.'
@patch('homeassistant.components.microsoft_face.MicrosoftFace.update_store', return_value=mock_coro()) def test_setup_component_wrong_api_key(self, mock_update):
with assert_setup_component(0, mf.DOMAIN): setup_component(self.hass, mf.DOMAIN, {mf.DOMAIN: {}})
'Setup component.'
@patch('homeassistant.components.microsoft_face.MicrosoftFace.update_store', return_value=mock_coro()) def test_setup_component_test_service(self, mock_update):
with assert_setup_component(3, mf.DOMAIN): setup_component(self.hass, mf.DOMAIN, self.config) assert self.hass.services.has_service(mf.DOMAIN, 'create_group') assert self.hass.services.has_service(mf.DOMAIN, 'delete_group') assert self.hass.services.has_service(mf.DOMAIN, 'train_group') assert self.hass.services.has_service(mf.DOMAIN, 'create_person') assert self.hass.services.has_service(mf.DOMAIN, 'delete_person') assert self.hass.services.has_service(mf.DOMAIN, 'face_person')
'Setup component.'
def test_setup_component_test_entities(self, aioclient_mock):
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')
'Setup component, test groups services.'
@patch('homeassistant.components.microsoft_face.MicrosoftFace.update_store', return_value=mock_coro()) def test_service_groups(self, mock_update, aioclient_mock):
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) mf.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) mf.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)
'Setup component, test person services.'
def test_service_person(self, aioclient_mock):
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) aioclient_mock.post(self.endpoint_url.format('persongroups/test_group1/persons'), text=load_fixture('microsoft_face_create_person.json')) aioclient_mock.delete(self.endpoint_url.format('persongroups/test_group1/persons/25985303-c537-4467-b41d-bdb45cd95ca1'), status=200, text='{}') mf.create_person(self.hass, 'test group1', 'Hans') self.hass.block_till_done() entity_group1 = self.hass.states.get('microsoft_face.test_group1') assert (len(aioclient_mock.mock_calls) == 4) assert (entity_group1 is not None) assert (entity_group1.attributes['Hans'] == '25985303-c537-4467-b41d-bdb45cd95ca1') mf.delete_person(self.hass, 'test group1', 'Hans') self.hass.block_till_done() entity_group1 = self.hass.states.get('microsoft_face.test_group1') assert (len(aioclient_mock.mock_calls) == 5) assert (entity_group1 is not None) assert ('Hans' not in entity_group1.attributes)
'Setup component, test train groups services.'
@patch('homeassistant.components.microsoft_face.MicrosoftFace.update_store', return_value=mock_coro()) def test_service_train(self, mock_update, aioclient_mock):
with assert_setup_component(3, mf.DOMAIN): setup_component(self.hass, mf.DOMAIN, self.config) aioclient_mock.post(self.endpoint_url.format('persongroups/service_group/train'), status=200, text='{}') mf.train_group(self.hass, 'Service Group') self.hass.block_till_done() assert (len(aioclient_mock.mock_calls) == 1)
'Setup component, test person face services.'
@patch('homeassistant.components.camera.async_get_image', return_value=mock_coro('Test')) def test_service_face(self, camera_mock, aioclient_mock):
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='{}') mf.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] == 'Test')
'Setup component, test groups services with error.'
@patch('homeassistant.components.microsoft_face.MicrosoftFace.update_store', return_value=mock_coro()) def test_service_status_400(self, mock_update, aioclient_mock):
aioclient_mock.put(self.endpoint_url.format('persongroups/service_group'), status=400, text="{'error': {'message': 'Error'}}") with assert_setup_component(3, mf.DOMAIN): setup_component(self.hass, mf.DOMAIN, self.config) mf.create_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) == 1)
'Setup component, test groups services with timeout.'
@patch('homeassistant.components.microsoft_face.MicrosoftFace.update_store', return_value=mock_coro()) def test_service_status_timeout(self, mock_update, aioclient_mock):
aioclient_mock.put(self.endpoint_url.format('persongroups/service_group'), status=400, exc=asyncio.TimeoutError()) with assert_setup_component(3, mf.DOMAIN): setup_component(self.hass, mf.DOMAIN, self.config) mf.create_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) == 1)
'Setup the class.'
@classmethod def setUpClass(cls):
cls.hass = hass = get_test_home_assistant() run_coroutine_threadsafe(core_components.async_setup(hass, {core.DOMAIN: {}}), hass.loop).result() setup.setup_component(hass, http.DOMAIN, {http.DOMAIN: {http.CONF_SERVER_PORT: HTTP_SERVER_PORT}}) with patch('homeassistant.components.emulated_hue.UPNPResponderThread'): setup.setup_component(hass, emulated_hue.DOMAIN, {emulated_hue.DOMAIN: {emulated_hue.CONF_LISTEN_PORT: BRIDGE_SERVER_PORT}}) cls.hass.start()
'Stop the class.'
@classmethod def tearDownClass(cls):
cls.hass.stop()
'Test the description.'
def test_description_xml(self):
import xml.etree.ElementTree as ET result = requests.get(BRIDGE_URL_BASE.format('/description.xml'), timeout=5) self.assertEqual(result.status_code, 200) self.assertTrue(('text/xml' in result.headers['content-type'])) try: ET.fromstring(result.text) except: self.fail('description.xml is not valid XML!')
'Test the creation of an username.'
def test_create_username(self):
request_json = {'devicetype': 'my_device'} result = requests.post(BRIDGE_URL_BASE.format('/api'), data=json.dumps(request_json), timeout=5) self.assertEqual(result.status_code, 200) self.assertTrue(('application/json' in result.headers['content-type'])) resp_json = result.json() success_json = resp_json[0] self.assertTrue(('success' in success_json)) self.assertTrue(('username' in success_json['success']))