desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Stay always Connected.'
| def connect(self):
| return True
|
'Get the next email.'
| def read_next(self):
| if (len(self._messages) == 0):
return None
return self._messages.popleft()
|
'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 emails from allowed sender.'
| def test_allowed_sender(self):
| test_message = email.message.Message()
test_message['From'] = '[email protected]'
test_message['Subject'] = 'Test'
test_message['Date'] = datetime.datetime(2016, 1, 1, 12, 44, 57)
test_message.set_payload('Test Message')
sensor = imap_email_content.EmailContentSensor(self.hass, FakeEMailReader(deque([test_message])), 'test_emails_sensor', ['[email protected]'], None)
sensor.entity_id = 'sensor.emailtest'
sensor.schedule_update_ha_state(True)
self.hass.block_till_done()
self.assertEqual('Test Message', sensor.state)
self.assertEqual('[email protected]', sensor.device_state_attributes['from'])
self.assertEqual('Test', sensor.device_state_attributes['subject'])
self.assertEqual(datetime.datetime(2016, 1, 1, 12, 44, 57), sensor.device_state_attributes['date'])
|
'Test multi part emails.'
| def test_multi_part_with_text(self):
| msg = MIMEMultipart('alternative')
msg['Subject'] = 'Link'
msg['From'] = '[email protected]'
text = 'Test Message'
html = '<html><head></head><body>Test Message</body></html>'
textPart = MIMEText(text, 'plain')
htmlPart = MIMEText(html, 'html')
msg.attach(textPart)
msg.attach(htmlPart)
sensor = imap_email_content.EmailContentSensor(self.hass, FakeEMailReader(deque([msg])), 'test_emails_sensor', ['[email protected]'], None)
sensor.entity_id = 'sensor.emailtest'
sensor.schedule_update_ha_state(True)
self.hass.block_till_done()
self.assertEqual('Test Message', sensor.state)
|
'Test multi part emails with only HTML.'
| def test_multi_part_only_html(self):
| msg = MIMEMultipart('alternative')
msg['Subject'] = 'Link'
msg['From'] = '[email protected]'
html = '<html><head></head><body>Test Message</body></html>'
htmlPart = MIMEText(html, 'html')
msg.attach(htmlPart)
sensor = imap_email_content.EmailContentSensor(self.hass, FakeEMailReader(deque([msg])), 'test_emails_sensor', ['[email protected]'], None)
sensor.entity_id = 'sensor.emailtest'
sensor.schedule_update_ha_state(True)
self.hass.block_till_done()
self.assertEqual('<html><head></head><body>Test Message</body></html>', sensor.state)
|
'Test multi part emails with only other text.'
| def test_multi_part_only_other_text(self):
| msg = MIMEMultipart('alternative')
msg['Subject'] = 'Link'
msg['From'] = '[email protected]'
other = 'Test Message'
htmlPart = MIMEText(other, 'other')
msg.attach(htmlPart)
sensor = imap_email_content.EmailContentSensor(self.hass, FakeEMailReader(deque([msg])), 'test_emails_sensor', ['[email protected]'], None)
sensor.entity_id = 'sensor.emailtest'
sensor.schedule_update_ha_state(True)
self.hass.block_till_done()
self.assertEqual('Test Message', sensor.state)
|
'Test multiple emails.'
| def test_multiple_emails(self):
| states = []
test_message1 = email.message.Message()
test_message1['From'] = '[email protected]'
test_message1['Subject'] = 'Test'
test_message1['Date'] = datetime.datetime(2016, 1, 1, 12, 44, 57)
test_message1.set_payload('Test Message')
test_message2 = email.message.Message()
test_message2['From'] = '[email protected]'
test_message2['Subject'] = 'Test 2'
test_message2['Date'] = datetime.datetime(2016, 1, 1, 12, 44, 57)
test_message2.set_payload('Test Message 2')
def state_changed_listener(entity_id, from_s, to_s):
states.append(to_s)
track_state_change(self.hass, ['sensor.emailtest'], state_changed_listener)
sensor = imap_email_content.EmailContentSensor(self.hass, FakeEMailReader(deque([test_message1, test_message2])), 'test_emails_sensor', ['[email protected]'], None)
sensor.entity_id = 'sensor.emailtest'
sensor.schedule_update_ha_state(True)
self.hass.block_till_done()
sensor.schedule_update_ha_state(True)
self.hass.block_till_done()
self.assertEqual('Test Message', states[0].state)
self.assertEqual('Test Message 2', states[1].state)
self.assertEqual('Test Message 2', sensor.state)
|
'Test not whitelisted emails.'
| def test_sender_not_allowed(self):
| test_message = email.message.Message()
test_message['From'] = '[email protected]'
test_message['Subject'] = 'Test'
test_message['Date'] = datetime.datetime(2016, 1, 1, 12, 44, 57)
test_message.set_payload('Test Message')
sensor = imap_email_content.EmailContentSensor(self.hass, FakeEMailReader(deque([test_message])), 'test_emails_sensor', ['[email protected]'], None)
sensor.entity_id = 'sensor.emailtest'
sensor.schedule_update_ha_state(True)
self.hass.block_till_done()
self.assertEqual(None, sensor.state)
|
'Test value template.'
| def test_template(self):
| test_message = email.message.Message()
test_message['From'] = '[email protected]'
test_message['Subject'] = 'Test'
test_message['Date'] = datetime.datetime(2016, 1, 1, 12, 44, 57)
test_message.set_payload('Test Message')
sensor = imap_email_content.EmailContentSensor(self.hass, FakeEMailReader(deque([test_message])), 'test_emails_sensor', ['[email protected]'], Template('{{ subject }} from {{ from }} with message {{ body }}', self.hass))
sensor.entity_id = 'sensor.emailtest'
sensor.schedule_update_ha_state(True)
self.hass.block_till_done()
self.assertEqual('Test from [email protected] with message Test Message', sensor.state)
|
'Set up things to be run when tests are started.'
| def setUp(self):
| self.hass = get_test_home_assistant()
self.time_zone = dt_util.get_time_zone('America/New_York')
config = {'sensor': {'platform': 'worldclock', 'time_zone': 'America/New_York'}}
self.assertTrue(setup_component(self.hass, 'sensor', config))
|
'Stop everything that was started.'
| def tearDown(self):
| self.hass.stop()
|
'Test the time at a different location.'
| def test_time(self):
| state = self.hass.states.get('sensor.worldclock_sensor')
assert (state is not None)
assert (state.state == dt_util.now(time_zone=self.time_zone).strftime('%H:%M'))
|
'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.DEFAULT_TIME_ZONE = dt_util.DEFAULT_TIME_ZONE
|
'Stop everything that was started.'
| def tearDown(self):
| dt_util.set_default_time_zone(self.DEFAULT_TIME_ZONE)
self.hass.stop()
|
'Test timing intervals of sensors.'
| def test_intervals(self):
| device = time_date.TimeDateSensor(self.hass, 'time')
now = dt_util.utc_from_timestamp(45)
next_time = device.get_next_interval(now)
assert (next_time == dt_util.utc_from_timestamp(60))
device = time_date.TimeDateSensor(self.hass, 'date')
now = dt_util.utc_from_timestamp(12345)
next_time = device.get_next_interval(now)
assert (next_time == dt_util.utc_from_timestamp(86400))
device = time_date.TimeDateSensor(self.hass, 'beat')
now = dt_util.utc_from_timestamp(29)
next_time = device.get_next_interval(now)
assert (next_time == dt_util.utc_from_timestamp(86.4))
device = time_date.TimeDateSensor(self.hass, 'date_time')
now = dt_util.utc_from_timestamp(1495068899)
next_time = device.get_next_interval(now)
assert (next_time == dt_util.utc_from_timestamp(1495068900))
now = dt_util.utcnow()
device = time_date.TimeDateSensor(self.hass, 'time_date')
next_time = device.get_next_interval()
assert (next_time > now)
|
'Test states of sensors.'
| def test_states(self):
| now = dt_util.utc_from_timestamp(1495068856)
device = time_date.TimeDateSensor(self.hass, 'time')
device._update_internal_state(now)
assert (device.state == '00:54')
device = time_date.TimeDateSensor(self.hass, 'date')
device._update_internal_state(now)
assert (device.state == '2017-05-18')
device = time_date.TimeDateSensor(self.hass, 'time_utc')
device._update_internal_state(now)
assert (device.state == '00:54')
device = time_date.TimeDateSensor(self.hass, 'beat')
device._update_internal_state(now)
assert (device.state == '@079')
|
'Test date sensor behavior in a timezone besides UTC.'
| def test_timezone_intervals(self):
| new_tz = dt_util.get_time_zone('America/New_York')
assert (new_tz is not None)
dt_util.set_default_time_zone(new_tz)
device = time_date.TimeDateSensor(self.hass, 'date')
now = dt_util.utc_from_timestamp(50000)
next_time = device.get_next_interval(now)
assert (next_time.timestamp() == 104400)
|
'Test attributes of sensors.'
| def test_icons(self):
| device = time_date.TimeDateSensor(self.hass, 'time')
assert (device.icon == 'mdi:clock')
device = time_date.TimeDateSensor(self.hass, 'date')
assert (device.icon == 'mdi:calendar')
device = time_date.TimeDateSensor(self.hass, 'date_time')
assert (device.icon == 'mdi:calendar-clock')
|
'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 with configuration missing required entries.'
| def test_setup_missing_config(self):
| with assert_setup_component(0):
assert setup_component(self.hass, sensor.DOMAIN, {'sensor': {'platform': 'rest'}})
|
'Test setup with resource missing schema.'
| def test_setup_missing_schema(self):
| with self.assertRaises(MissingSchema):
rest.setup_platform(self.hass, {'platform': 'rest', 'resource': 'localhost', 'method': 'GET'}, None)
|
'Test setup when connection error occurs.'
| @patch('requests.Session.send', side_effect=requests.exceptions.ConnectionError())
def test_setup_failed_connect(self, mock_req):
| self.assertFalse(rest.setup_platform(self.hass, {'platform': 'rest', 'resource': 'http://localhost'}, None))
|
'Test setup when connection timeout occurs.'
| @patch('requests.Session.send', side_effect=Timeout())
def test_setup_timeout(self, mock_req):
| self.assertFalse(rest.setup_platform(self.hass, {'platform': 'rest', 'resource': 'http://localhost'}, None))
|
'Test setup with minimum configuration.'
| @requests_mock.Mocker()
def test_setup_minimum(self, mock_req):
| mock_req.get('http://localhost', status_code=200)
self.assertTrue(setup_component(self.hass, 'sensor', {'sensor': {'platform': 'rest', 'resource': 'http://localhost'}}))
self.assertEqual(2, mock_req.call_count)
assert_setup_component(1, 'switch')
|
'Test setup with valid configuration.'
| @requests_mock.Mocker()
def test_setup_get(self, mock_req):
| mock_req.get('http://localhost', status_code=200)
self.assertTrue(setup_component(self.hass, 'sensor', {'sensor': {'platform': 'rest', 'resource': 'http://localhost', 'method': 'GET', 'value_template': '{{ value_json.key }}', 'name': 'foo', 'unit_of_measurement': 'MB', 'verify_ssl': 'true', 'authentication': 'basic', 'username': 'my username', 'password': 'my password', 'headers': {'Accept': 'application/json'}}}))
self.assertEqual(2, mock_req.call_count)
assert_setup_component(1, 'sensor')
|
'Test setup with valid configuration.'
| @requests_mock.Mocker()
def test_setup_post(self, mock_req):
| mock_req.post('http://localhost', status_code=200)
self.assertTrue(setup_component(self.hass, 'sensor', {'sensor': {'platform': 'rest', 'resource': 'http://localhost', 'method': 'POST', 'value_template': '{{ value_json.key }}', 'payload': '{ "device": "toaster"}', 'name': 'foo', 'unit_of_measurement': 'MB', 'verify_ssl': 'true', 'authentication': 'basic', 'username': 'my username', 'password': 'my password', 'headers': {'Accept': 'application/json'}}}))
self.assertEqual(2, mock_req.call_count)
assert_setup_component(1, 'sensor')
|
'Setup things to be run when tests are started.'
| def setUp(self):
| self.hass = get_test_home_assistant()
self.initial_state = 'initial_state'
self.rest = Mock('rest.RestData')
self.rest.update = Mock('rest.RestData.update', side_effect=self.update_side_effect((('{ "key": "' + self.initial_state) + '" }')))
self.name = 'foo'
self.unit_of_measurement = 'MB'
self.value_template = template('{{ value_json.key }}')
self.value_template.hass = self.hass
self.sensor = rest.RestSensor(self.hass, self.rest, self.name, self.unit_of_measurement, self.value_template)
|
'Stop everything that was started.'
| def tearDown(self):
| self.hass.stop()
|
'Side effect function for mocking RestData.update().'
| def update_side_effect(self, data):
| self.rest.data = data
|
'Test the name.'
| def test_name(self):
| self.assertEqual(self.name, self.sensor.name)
|
'Test the unit of measurement.'
| def test_unit_of_measurement(self):
| self.assertEqual(self.unit_of_measurement, self.sensor.unit_of_measurement)
|
'Test the initial state.'
| def test_state(self):
| self.sensor.update()
self.assertEqual(self.initial_state, self.sensor.state)
|
'Test state gets updated to unknown when sensor returns no data.'
| def test_update_when_value_is_none(self):
| self.rest.update = Mock('rest.RestData.update', side_effect=self.update_side_effect(None))
self.sensor.update()
self.assertEqual(STATE_UNKNOWN, self.sensor.state)
|
'Test state gets updated when sensor returns a new status.'
| def test_update_when_value_changed(self):
| self.rest.update = Mock('rest.RestData.update', side_effect=self.update_side_effect('{ "key": "updated_state" }'))
self.sensor.update()
self.assertEqual('updated_state', self.sensor.state)
|
'Test update when there is no value template.'
| def test_update_with_no_template(self):
| self.rest.update = Mock('rest.RestData.update', side_effect=self.update_side_effect('plain_state'))
self.sensor = rest.RestSensor(self.hass, self.rest, self.name, self.unit_of_measurement, None)
self.sensor.update()
self.assertEqual('plain_state', self.sensor.state)
|
'Setup things to be run when tests are started.'
| def setUp(self):
| self.method = 'GET'
self.resource = 'http://localhost'
self.verify_ssl = True
self.rest = rest.RestData(self.method, self.resource, None, None, None, self.verify_ssl)
|
'Test update.'
| @requests_mock.Mocker()
def test_update(self, mock_req):
| mock_req.get('http://localhost', text='test data')
self.rest.update()
self.assertEqual('test data', self.rest.data)
|
'Test update when a request exception occurs.'
| @patch('requests.Session', side_effect=RequestException)
def test_update_request_exception(self, mock_req):
| self.rest.update()
self.assertEqual(None, self.rest.data)
|
'Mock add devices.'
| def add_devices(self, devices, update):
| for device in devices:
self.DEVICES.append(device)
|
'Initialize values for this testcase class.'
| def setUp(self):
| self.DEVICES = []
self.hass = get_test_home_assistant()
self.hass.config.time_zone = 'America/Los_Angeles'
|
'Stop everything that was started.'
| def tearDown(self):
| self.hass.stop()
|
'Test getting all disk space.'
| @unittest.mock.patch('requests.get', side_effect=mocked_requests_get)
def test_diskspace_no_paths(self, req_mock):
| config = {'platform': 'radarr', 'api_key': 'foo', 'days': '2', 'unit': 'GB', 'include_paths': [], 'monitored_conditions': ['diskspace']}
radarr.setup_platform(self.hass, config, self.add_devices, None)
for device in self.DEVICES:
device.update()
self.assertEqual('263.10', device.state)
self.assertEqual('mdi:harddisk', device.icon)
self.assertEqual('GB', device.unit_of_measurement)
self.assertEqual('Radarr Disk Space', device.name)
self.assertEqual('263.10/465.42GB (56.53%)', device.device_state_attributes['/data'])
|
'Test getting diskspace for included paths.'
| @unittest.mock.patch('requests.get', side_effect=mocked_requests_get)
def test_diskspace_paths(self, req_mock):
| config = {'platform': 'radarr', 'api_key': 'foo', 'days': '2', 'unit': 'GB', 'include_paths': ['/data'], 'monitored_conditions': ['diskspace']}
radarr.setup_platform(self.hass, config, self.add_devices, None)
for device in self.DEVICES:
device.update()
self.assertEqual('263.10', device.state)
self.assertEqual('mdi:harddisk', device.icon)
self.assertEqual('GB', device.unit_of_measurement)
self.assertEqual('Radarr Disk Space', device.name)
self.assertEqual('263.10/465.42GB (56.53%)', device.device_state_attributes['/data'])
|
'Test getting running commands.'
| @unittest.mock.patch('requests.get', side_effect=mocked_requests_get)
def test_commands(self, req_mock):
| config = {'platform': 'radarr', 'api_key': 'foo', 'days': '2', 'unit': 'GB', 'include_paths': ['/data'], 'monitored_conditions': ['commands']}
radarr.setup_platform(self.hass, config, self.add_devices, None)
for device in self.DEVICES:
device.update()
self.assertEqual(1, device.state)
self.assertEqual('mdi:code-braces', device.icon)
self.assertEqual('Commands', device.unit_of_measurement)
self.assertEqual('Radarr Commands', device.name)
self.assertEqual('pending', device.device_state_attributes['RescanMovie'])
|
'Test getting the number of movies.'
| @unittest.mock.patch('requests.get', side_effect=mocked_requests_get)
def test_movies(self, req_mock):
| config = {'platform': 'radarr', 'api_key': 'foo', 'days': '2', 'unit': 'GB', 'include_paths': ['/data'], 'monitored_conditions': ['movies']}
radarr.setup_platform(self.hass, config, self.add_devices, None)
for device in self.DEVICES:
device.update()
self.assertEqual(1, device.state)
self.assertEqual('mdi:television', device.icon)
self.assertEqual('Movies', device.unit_of_measurement)
self.assertEqual('Radarr Movies', device.name)
self.assertEqual('false', device.device_state_attributes["Assassin's Creed (2016)"])
|
'Test the upcoming movies for multiple days.'
| @unittest.mock.patch('requests.get', side_effect=mocked_requests_get)
def test_upcoming_multiple_days(self, req_mock):
| config = {'platform': 'radarr', 'api_key': 'foo', 'days': '2', 'unit': 'GB', 'include_paths': ['/data'], 'monitored_conditions': ['upcoming']}
radarr.setup_platform(self.hass, config, self.add_devices, None)
for device in self.DEVICES:
device.update()
self.assertEqual(1, device.state)
self.assertEqual('mdi:television', device.icon)
self.assertEqual('Movies', device.unit_of_measurement)
self.assertEqual('Radarr Upcoming', device.name)
self.assertEqual('2017-01-27T00:00:00Z', device.device_state_attributes['Resident Evil (2017)'])
|
'Test filtering for a single day.
Radarr needs to respond with at least 2 days.'
| @pytest.mark.skip
@unittest.mock.patch('requests.get', side_effect=mocked_requests_get)
def test_upcoming_today(self, req_mock):
| config = {'platform': 'radarr', 'api_key': 'foo', 'days': '1', 'unit': 'GB', 'include_paths': ['/data'], 'monitored_conditions': ['upcoming']}
radarr.setup_platform(self.hass, config, self.add_devices, None)
for device in self.DEVICES:
device.update()
self.assertEqual(1, device.state)
self.assertEqual('mdi:television', device.icon)
self.assertEqual('Movies', device.unit_of_measurement)
self.assertEqual('Radarr Upcoming', device.name)
self.assertEqual('2017-01-27T00:00:00Z', device.device_state_attributes['Resident Evil (2017)'])
|
'Test the getting of the system status.'
| @unittest.mock.patch('requests.get', side_effect=mocked_requests_get)
def test_system_status(self, req_mock):
| config = {'platform': 'radarr', 'api_key': 'foo', 'days': '2', 'unit': 'GB', 'include_paths': ['/data'], 'monitored_conditions': ['status']}
radarr.setup_platform(self.hass, config, self.add_devices, None)
for device in self.DEVICES:
device.update()
self.assertEqual('0.2.0.210', device.state)
self.assertEqual('mdi:information', device.icon)
self.assertEqual('Radarr Status', device.name)
self.assertEqual('4.8.13.1', device.device_state_attributes['osVersion'])
|
'Test SSL being enabled.'
| @pytest.mark.skip
@unittest.mock.patch('requests.get', side_effect=mocked_requests_get)
def test_ssl(self, req_mock):
| config = {'platform': 'radarr', 'api_key': 'foo', 'days': '1', 'unit': 'GB', 'include_paths': ['/data'], 'monitored_conditions': ['upcoming'], 'ssl': 'true'}
radarr.setup_platform(self.hass, config, self.add_devices, None)
for device in self.DEVICES:
device.update()
self.assertEqual(1, device.state)
self.assertEqual('s', device.ssl)
self.assertEqual('mdi:television', device.icon)
self.assertEqual('Movies', device.unit_of_measurement)
self.assertEqual('Radarr Upcoming', device.name)
self.assertEqual('2017-01-27T00:00:00Z', device.device_state_attributes['Resident Evil (2017)'])
|
'Test exception being handled.'
| @unittest.mock.patch('requests.get', side_effect=mocked_exception)
def test_exception_handling(self, req_mock):
| config = {'platform': 'radarr', 'api_key': 'foo', 'days': '1', 'unit': 'GB', 'include_paths': ['/data'], 'monitored_conditions': ['upcoming']}
radarr.setup_platform(self.hass, config, self.add_devices, None)
for device in self.DEVICES:
device.update()
self.assertEqual(None, device.state)
|
'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()
|
'Check a valid configuration and call add_devices with sensor.'
| @patch('homeassistant.components.sensor.tcp.TcpSensor.update')
def test_setup_platform_valid_config(self, mock_update):
| with assert_setup_component(0, 'sensor'):
assert setup_component(self.hass, 'sensor', TEST_CONFIG)
add_devices = Mock()
tcp.setup_platform(None, TEST_CONFIG['sensor'], add_devices)
assert add_devices.called
assert isinstance(add_devices.call_args[0][0][0], tcp.TcpSensor)
|
'Check an invalid configuration.'
| def test_setup_platform_invalid_config(self):
| with assert_setup_component(0):
assert setup_component(self.hass, 'sensor', {'sensor': {'platform': 'tcp', 'porrt': 1234}})
|
'Return the name if set in the configuration.'
| @patch('homeassistant.components.sensor.tcp.TcpSensor.update')
def test_name(self, mock_update):
| sensor = tcp.TcpSensor(self.hass, TEST_CONFIG['sensor'])
assert (sensor.name == TEST_CONFIG['sensor'][tcp.CONF_NAME])
|
'Return the superclass name property if not set in configuration.'
| @patch('homeassistant.components.sensor.tcp.TcpSensor.update')
def test_name_not_set(self, mock_update):
| config = copy(TEST_CONFIG['sensor'])
del config[tcp.CONF_NAME]
entity = Entity()
sensor = tcp.TcpSensor(self.hass, config)
assert (sensor.name == entity.name)
|
'Return the contents of _state.'
| @patch('homeassistant.components.sensor.tcp.TcpSensor.update')
def test_state(self, mock_update):
| sensor = tcp.TcpSensor(self.hass, TEST_CONFIG['sensor'])
uuid = str(uuid4())
sensor._state = uuid
assert (sensor.state == uuid)
|
'Return the configured unit of measurement.'
| @patch('homeassistant.components.sensor.tcp.TcpSensor.update')
def test_unit_of_measurement(self, mock_update):
| sensor = tcp.TcpSensor(self.hass, TEST_CONFIG['sensor'])
assert (sensor.unit_of_measurement == TEST_CONFIG['sensor'][tcp.CONF_UNIT_OF_MEASUREMENT])
|
'Store valid keys in _config.'
| @patch('homeassistant.components.sensor.tcp.TcpSensor.update')
def test_config_valid_keys(self, *args):
| sensor = tcp.TcpSensor(self.hass, TEST_CONFIG['sensor'])
del TEST_CONFIG['sensor']['platform']
for key in TEST_CONFIG['sensor']:
assert (key in sensor._config)
|
'Return True when provided with the correct keys.'
| def test_validate_config_valid_keys(self):
| with assert_setup_component(0, 'sensor'):
assert setup_component(self.hass, 'sensor', TEST_CONFIG)
|
'Shouldn\'t store invalid keys in _config.'
| @patch('homeassistant.components.sensor.tcp.TcpSensor.update')
def test_config_invalid_keys(self, mock_update):
| config = copy(TEST_CONFIG['sensor'])
config.update({'a': 'test_a', 'b': 'test_b', 'c': 'test_c'})
sensor = tcp.TcpSensor(self.hass, config)
for invalid_key in 'abc':
assert (invalid_key not in sensor._config)
|
'Test with invalid keys plus some extra.'
| def test_validate_config_invalid_keys(self):
| config = copy(TEST_CONFIG['sensor'])
config.update({'a': 'test_a', 'b': 'test_b', 'c': 'test_c'})
with assert_setup_component(0, 'sensor'):
assert setup_component(self.hass, 'sensor', {'tcp': config})
|
'Check if defaults were set.'
| @patch('homeassistant.components.sensor.tcp.TcpSensor.update')
def test_config_uses_defaults(self, mock_update):
| config = copy(TEST_CONFIG['sensor'])
for key in KEYS_AND_DEFAULTS:
del config[key]
with assert_setup_component(1) as result_config:
assert setup_component(self.hass, 'sensor', {'sensor': config})
sensor = tcp.TcpSensor(self.hass, result_config['sensor'][0])
for (key, default) in KEYS_AND_DEFAULTS.items():
assert (sensor._config[key] == default)
|
'Return True when defaulted keys are not provided.'
| def test_validate_config_missing_defaults(self):
| config = copy(TEST_CONFIG['sensor'])
for key in KEYS_AND_DEFAULTS:
del config[key]
with assert_setup_component(0, 'sensor'):
assert setup_component(self.hass, 'sensor', {'tcp': config})
|
'Return False when required config items are missing.'
| def test_validate_config_missing_required(self):
| for key in TEST_CONFIG['sensor']:
if (key in KEYS_AND_DEFAULTS):
continue
config = copy(TEST_CONFIG['sensor'])
del config[key]
with assert_setup_component(0, 'sensor'):
assert setup_component(self.hass, 'sensor', {'tcp': config})
|
'Call update() method during __init__().'
| @patch('homeassistant.components.sensor.tcp.TcpSensor.update')
def test_init_calls_update(self, mock_update):
| tcp.TcpSensor(self.hass, TEST_CONFIG)
assert mock_update.called
|
'Connect to the configured host and port.'
| @patch('socket.socket')
@patch('select.select', return_value=(True, False, False))
def test_update_connects_to_host_and_port(self, mock_select, mock_socket):
| tcp.TcpSensor(self.hass, TEST_CONFIG['sensor'])
mock_socket = mock_socket().__enter__()
assert (mock_socket.connect.mock_calls[0][1] == ((TEST_CONFIG['sensor'][tcp.CONF_HOST], TEST_CONFIG['sensor'][tcp.CONF_PORT]),))
|
'Return if connecting to host fails.'
| @patch('socket.socket.connect', side_effect=socket.error())
def test_update_returns_if_connecting_fails(self, *args):
| with patch('homeassistant.components.sensor.tcp.TcpSensor.update'):
sensor = tcp.TcpSensor(self.hass, TEST_CONFIG['sensor'])
assert (sensor.update() is None)
|
'Return if sending fails.'
| @patch('socket.socket.connect')
@patch('socket.socket.send', side_effect=socket.error())
def test_update_returns_if_sending_fails(self, *args):
| with patch('homeassistant.components.sensor.tcp.TcpSensor.update'):
sensor = tcp.TcpSensor(self.hass, TEST_CONFIG['sensor'])
assert (sensor.update() is None)
|
'Return if select fails to return a socket.'
| @patch('socket.socket.connect')
@patch('socket.socket.send')
@patch('select.select', return_value=(False, False, False))
def test_update_returns_if_select_fails(self, *args):
| with patch('homeassistant.components.sensor.tcp.TcpSensor.update'):
sensor = tcp.TcpSensor(self.hass, TEST_CONFIG['sensor'])
assert (sensor.update() is None)
|
'Send the configured payload as bytes.'
| @patch('socket.socket')
@patch('select.select', return_value=(True, False, False))
def test_update_sends_payload(self, mock_select, mock_socket):
| tcp.TcpSensor(self.hass, TEST_CONFIG['sensor'])
mock_socket = mock_socket().__enter__()
mock_socket.send.assert_called_with(TEST_CONFIG['sensor'][tcp.CONF_PAYLOAD].encode())
|
'Provide the timeout argument to select.'
| @patch('socket.socket')
@patch('select.select', return_value=(True, False, False))
def test_update_calls_select_with_timeout(self, mock_select, mock_socket):
| tcp.TcpSensor(self.hass, TEST_CONFIG['sensor'])
mock_socket = mock_socket().__enter__()
mock_select.assert_called_with([mock_socket], [], [], TEST_CONFIG['sensor'][tcp.CONF_TIMEOUT])
|
'Test the response from the socket and set it as the state.'
| @patch('socket.socket')
@patch('select.select', return_value=(True, False, False))
def test_update_receives_packet_and_sets_as_state(self, mock_select, mock_socket):
| test_value = 'test_value'
mock_socket = mock_socket().__enter__()
mock_socket.recv.return_value = test_value.encode()
config = copy(TEST_CONFIG['sensor'])
del config[tcp.CONF_VALUE_TEMPLATE]
sensor = tcp.TcpSensor(self.hass, config)
assert (sensor._state == test_value)
|
'Render the value in the provided template.'
| @patch('socket.socket')
@patch('select.select', return_value=(True, False, False))
def test_update_renders_value_in_template(self, mock_select, mock_socket):
| test_value = 'test_value'
mock_socket = mock_socket().__enter__()
mock_socket.recv.return_value = test_value.encode()
config = copy(TEST_CONFIG['sensor'])
config[tcp.CONF_VALUE_TEMPLATE] = Template('{{ value }} {{ 1+1 }}')
sensor = tcp.TcpSensor(self.hass, config)
assert (sensor._state == ('%s 2' % test_value))
|
'Return None if rendering the template fails.'
| @patch('socket.socket')
@patch('select.select', return_value=(True, False, False))
def test_update_returns_if_template_render_fails(self, mock_select, mock_socket):
| test_value = 'test_value'
mock_socket = mock_socket().__enter__()
mock_socket.recv.return_value = test_value.encode()
config = copy(TEST_CONFIG['sensor'])
config[tcp.CONF_VALUE_TEMPLATE] = Template("{{ this won't work")
sensor = tcp.TcpSensor(self.hass, config)
assert (sensor.update() is None)
|
'Set up 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 the Randowm number sensor.'
| def test_random_sensor(self):
| config = {'sensor': {'platform': 'random', 'name': 'test', 'minimum': 10, 'maximum': 20}}
assert setup_component(self.hass, 'sensor', config)
state = self.hass.states.get('sensor.test')
self.assertLessEqual(int(state.state), config['sensor']['maximum'])
self.assertGreaterEqual(int(state.state), config['sensor']['minimum'])
|
'Initialize values for this testcase class.'
| def setUp(self):
| self.hass = get_test_home_assistant()
self.config = {'sensor': {'platform': 'openhardwaremonitor', 'host': 'localhost', 'port': 8085}}
|
'Stop everything that was started.'
| def tearDown(self):
| self.hass.stop()
|
'Test for successfully setting up the platform.'
| @requests_mock.Mocker()
def test_setup(self, mock_req):
| mock_req.get('http://localhost:8085/data.json', text=load_fixture('openhardwaremonitor.json'))
self.assertTrue(setup_component(self.hass, 'sensor', self.config))
entities = self.hass.states.async_entity_ids('sensor')
self.assertEqual(len(entities), 38)
state = self.hass.states.get('sensor.testpc_intel_core_i77700_clocks_bus_speed')
self.assertIsNot(state, None)
self.assertEqual(state.state, '100')
|
'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 configuration missing required entries.'
| def test_setup_missing_config(self):
| with assert_setup_component(0):
assert setup_component(self.hass, DOMAIN, {'sensor': {'platform': 'mhz19'}})
|
'Test setup when connection error occurs.'
| @patch('pmsensor.co2sensor.read_mh_z19', side_effect=OSError('test error'))
def test_setup_failed_connect(self, mock_co2):
| self.assertFalse(mhz19.setup_platform(self.hass, {'platform': 'mhz19', mhz19.CONF_SERIAL_DEVICE: 'test.serial'}, None))
|
'Test setup when connection succeeds.'
| def test_setup_connected(self):
| with patch.multiple('pmsensor.co2sensor', read_mh_z19=DEFAULT, read_mh_z19_with_temperature=DEFAULT):
from pmsensor.co2sensor import read_mh_z19_with_temperature
read_mh_z19_with_temperature.return_value = None
mock_add = Mock()
self.assertTrue(mhz19.setup_platform(self.hass, {'platform': 'mhz19', 'monitored_conditions': ['co2', 'temperature'], mhz19.CONF_SERIAL_DEVICE: 'test.serial'}, mock_add))
self.assertEqual(1, mock_add.call_count)
|
'Test MHZClient when library throws OSError.'
| @patch('pmsensor.co2sensor.read_mh_z19_with_temperature', side_effect=OSError('test error'))
def test_client_update_oserror(self, mock_function):
| from pmsensor import co2sensor
client = mhz19.MHZClient(co2sensor, 'test.serial')
client.update()
self.assertEqual({}, client.data)
|
'Test MHZClient when ppm is too high.'
| @patch('pmsensor.co2sensor.read_mh_z19_with_temperature', return_value=(5001, 24))
def test_client_update_ppm_overflow(self, mock_function):
| from pmsensor import co2sensor
client = mhz19.MHZClient(co2sensor, 'test.serial')
client.update()
self.assertIsNone(client.data.get('co2'))
|
'Test MHZClient when ppm is too high.'
| @patch('pmsensor.co2sensor.read_mh_z19_with_temperature', return_value=(1000, 24))
def test_client_update_good_read(self, mock_function):
| from pmsensor import co2sensor
client = mhz19.MHZClient(co2sensor, 'test.serial')
client.update()
self.assertEqual({'temperature': 24, 'co2': 1000}, client.data)
|
'Test CO2 sensor.'
| @patch('pmsensor.co2sensor.read_mh_z19_with_temperature', return_value=(1000, 24))
def test_co2_sensor(self, mock_function):
| from pmsensor import co2sensor
client = mhz19.MHZClient(co2sensor, 'test.serial')
sensor = mhz19.MHZ19Sensor(client, mhz19.SENSOR_CO2, None, 'name')
sensor.update()
self.assertEqual('name: CO2', sensor.name)
self.assertEqual(1000, sensor.state)
self.assertEqual('ppm', sensor.unit_of_measurement)
self.assertTrue(sensor.should_poll)
self.assertEqual({'temperature': 24}, sensor.device_state_attributes)
|
'Test temperature sensor.'
| @patch('pmsensor.co2sensor.read_mh_z19_with_temperature', return_value=(1000, 24))
def test_temperature_sensor(self, mock_function):
| from pmsensor import co2sensor
client = mhz19.MHZClient(co2sensor, 'test.serial')
sensor = mhz19.MHZ19Sensor(client, mhz19.SENSOR_TEMPERATURE, None, 'name')
sensor.update()
self.assertEqual('name: Temperature', sensor.name)
self.assertEqual(24, sensor.state)
self.assertEqual('\xc2\xb0C', sensor.unit_of_measurement)
self.assertTrue(sensor.should_poll)
self.assertEqual({'co2_concentration': 1000}, sensor.device_state_attributes)
|
'Test temperature sensor.'
| @patch('pmsensor.co2sensor.read_mh_z19_with_temperature', return_value=(1000, 24))
def test_temperature_sensor_f(self, mock_function):
| from pmsensor import co2sensor
client = mhz19.MHZClient(co2sensor, 'test.serial')
sensor = mhz19.MHZ19Sensor(client, mhz19.SENSOR_TEMPERATURE, TEMP_FAHRENHEIT, 'name')
sensor.update()
self.assertEqual(75.2, sensor.state)
|
'Set up things to be run when tests are started.'
| def setup_method(self, method):
| self.hass = get_test_home_assistant()
self.values = [17, 20, 15.3]
self.count = len(self.values)
self.min = min(self.values)
self.max = max(self.values)
self.mean = round((sum(self.values) / self.count), 2)
self.mean_1_digit = round((sum(self.values) / self.count), 1)
self.mean_4_digits = round((sum(self.values) / self.count), 4)
|
'Stop everything that was started.'
| def teardown_method(self, method):
| self.hass.stop()
|
'Test the min sensor.'
| def test_min_sensor(self):
| config = {'sensor': {'platform': 'min_max', 'name': 'test_min', 'type': 'min', 'entity_ids': ['sensor.test_1', 'sensor.test_2', 'sensor.test_3']}}
assert setup_component(self.hass, 'sensor', config)
entity_ids = config['sensor']['entity_ids']
for (entity_id, value) in dict(zip(entity_ids, self.values)).items():
self.hass.states.set(entity_id, value)
self.hass.block_till_done()
state = self.hass.states.get('sensor.test_min')
self.assertEqual(str(float(self.min)), state.state)
self.assertEqual(self.max, state.attributes.get('max_value'))
self.assertEqual(self.mean, state.attributes.get('mean'))
|
'Test the max sensor.'
| def test_max_sensor(self):
| config = {'sensor': {'platform': 'min_max', 'name': 'test_max', 'type': 'max', 'entity_ids': ['sensor.test_1', 'sensor.test_2', 'sensor.test_3']}}
assert setup_component(self.hass, 'sensor', config)
entity_ids = config['sensor']['entity_ids']
for (entity_id, value) in dict(zip(entity_ids, self.values)).items():
self.hass.states.set(entity_id, value)
self.hass.block_till_done()
state = self.hass.states.get('sensor.test_max')
self.assertEqual(str(float(self.max)), state.state)
self.assertEqual(self.min, state.attributes.get('min_value'))
self.assertEqual(self.mean, state.attributes.get('mean'))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.