desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Test tilt via method invocation.'
def test_tilt_position(self):
self.assertTrue(setup_component(self.hass, cover.DOMAIN, {cover.DOMAIN: {'platform': 'mqtt', 'name': 'test', 'state_topic': 'state-topic', 'command_topic': 'command-topic', 'qos': 0, 'payload_open': 'OPEN', 'payload_close': 'CLOSE', 'payload_stop': 'STOP', 'tilt_command_topic': 'tilt-command-topic', 'tilt_status_topic': 'tilt-status-topic', 'tilt_opened_value': 400, 'tilt_closed_value': 125}})) cover.set_cover_tilt_position(self.hass, 50, 'cover.test') self.hass.block_till_done() self.assertEqual(('tilt-command-topic', 50, 0, False), self.mock_publish.mock_calls[(-2)][1])
'Test tilt via method invocation with altered range.'
def test_tilt_position_altered_range(self):
self.assertTrue(setup_component(self.hass, cover.DOMAIN, {cover.DOMAIN: {'platform': 'mqtt', 'name': 'test', 'state_topic': 'state-topic', 'command_topic': 'command-topic', 'qos': 0, 'payload_open': 'OPEN', 'payload_close': 'CLOSE', 'payload_stop': 'STOP', 'tilt_command_topic': 'tilt-command-topic', 'tilt_status_topic': 'tilt-status-topic', 'tilt_opened_value': 400, 'tilt_closed_value': 125, 'tilt_min': 0, 'tilt_max': 50}})) cover.set_cover_tilt_position(self.hass, 50, 'cover.test') self.hass.block_till_done() self.assertEqual(('tilt-command-topic', 25, 0, False), self.mock_publish.mock_calls[(-2)][1])
'Test find percentage in range with default range.'
def test_find_percentage_in_range_defaults(self):
mqtt_cover = MqttCover('cover.test', 'foo', 'bar', 'fooBar', 'fooBarBaz', 0, False, 'OPEN', 'CLOSE', 'OPEN', 'CLOSE', 'STOP', False, None, 100, 0, 0, 100, False, False, None, None) self.assertEqual(44, mqtt_cover.find_percentage_in_range(44))
'Test find percentage in range with altered range.'
def test_find_percentage_in_range_altered(self):
mqtt_cover = MqttCover('cover.test', 'foo', 'bar', 'fooBar', 'fooBarBaz', 0, False, 'OPEN', 'CLOSE', 'OPEN', 'CLOSE', 'STOP', False, None, 180, 80, 80, 180, False, False, None, None) self.assertEqual(40, mqtt_cover.find_percentage_in_range(120))
'Test find percentage in range with default range but inverted.'
def test_find_percentage_in_range_defaults_inverted(self):
mqtt_cover = MqttCover('cover.test', 'foo', 'bar', 'fooBar', 'fooBarBaz', 0, False, 'OPEN', 'CLOSE', 'OPEN', 'CLOSE', 'STOP', False, None, 100, 0, 0, 100, False, True, None, None) self.assertEqual(56, mqtt_cover.find_percentage_in_range(44))
'Test find percentage in range with altered range and inverted.'
def test_find_percentage_in_range_altered_inverted(self):
mqtt_cover = MqttCover('cover.test', 'foo', 'bar', 'fooBar', 'fooBarBaz', 0, False, 'OPEN', 'CLOSE', 'OPEN', 'CLOSE', 'STOP', False, None, 180, 80, 80, 180, False, True, None, None) self.assertEqual(60, mqtt_cover.find_percentage_in_range(120))
'Test find in range with default range.'
def test_find_in_range_defaults(self):
mqtt_cover = MqttCover('cover.test', 'foo', 'bar', 'fooBar', 'fooBarBaz', 0, False, 'OPEN', 'CLOSE', 'OPEN', 'CLOSE', 'STOP', False, None, 100, 0, 0, 100, False, False, None, None) self.assertEqual(44, mqtt_cover.find_in_range_from_percent(44))
'Test find in range with altered range.'
def test_find_in_range_altered(self):
mqtt_cover = MqttCover('cover.test', 'foo', 'bar', 'fooBar', 'fooBarBaz', 0, False, 'OPEN', 'CLOSE', 'OPEN', 'CLOSE', 'STOP', False, None, 180, 80, 80, 180, False, False, None, None) self.assertEqual(120, mqtt_cover.find_in_range_from_percent(40))
'Test find in range with default range but inverted.'
def test_find_in_range_defaults_inverted(self):
mqtt_cover = MqttCover('cover.test', 'foo', 'bar', 'fooBar', 'fooBarBaz', 0, False, 'OPEN', 'CLOSE', 'OPEN', 'CLOSE', 'STOP', False, None, 100, 0, 0, 100, False, True, None, None) self.assertEqual(44, mqtt_cover.find_in_range_from_percent(56))
'Test find in range with altered range and inverted.'
def test_find_in_range_altered_inverted(self):
mqtt_cover = MqttCover('cover.test', 'foo', 'bar', 'fooBar', 'fooBarBaz', 0, False, 'OPEN', 'CLOSE', 'OPEN', 'CLOSE', 'STOP', False, None, 180, 80, 80, 180, False, True, None, None) self.assertEqual(120, mqtt_cover.find_in_range_from_percent(60))
'Setup things to be run when tests are started.'
def setup_method(self, method):
self.hass = get_test_home_assistant() self.calls = [] @callback def record_call(service): 'Track function calls..' self.calls.append(service) self.hass.services.register('test', 'automation', record_call)
'Stop everything that was started.'
def teardown_method(self, method):
self.hass.stop()
'Test the state text of a template.'
def test_template_state_text(self):
with assert_setup_component(1, 'cover'): assert setup.setup_component(self.hass, 'cover', {'cover': {'platform': 'template', 'covers': {'test_template_cover': {'value_template': '{{ states.cover.test_state.state }}', 'open_cover': {'service': 'cover.open_cover', 'entity_id': 'cover.test_state'}, 'close_cover': {'service': 'cover.close_cover', 'entity_id': 'cover.test_state'}}}}}) self.hass.start() self.hass.block_till_done() state = self.hass.states.set('cover.test_state', STATE_OPEN) self.hass.block_till_done() state = self.hass.states.get('cover.test_template_cover') assert (state.state == STATE_OPEN) state = self.hass.states.set('cover.test_state', STATE_CLOSED) self.hass.block_till_done() state = self.hass.states.get('cover.test_template_cover') assert (state.state == STATE_CLOSED)
'Test the value_template attribute.'
def test_template_state_boolean(self):
with assert_setup_component(1, 'cover'): assert setup.setup_component(self.hass, 'cover', {'cover': {'platform': 'template', 'covers': {'test_template_cover': {'value_template': '{{ 1 == 1 }}', 'open_cover': {'service': 'cover.open_cover', 'entity_id': 'cover.test_state'}, 'close_cover': {'service': 'cover.close_cover', 'entity_id': 'cover.test_state'}}}}}) self.hass.start() self.hass.block_till_done() state = self.hass.states.get('cover.test_template_cover') assert (state.state == STATE_OPEN)
'Test the position_template attribute.'
def test_template_position(self):
with assert_setup_component(1, 'cover'): assert setup.setup_component(self.hass, 'cover', {'cover': {'platform': 'template', 'covers': {'test_template_cover': {'position_template': '{{ states.cover.test.attributes.position }}', 'open_cover': {'service': 'cover.open_cover', 'entity_id': 'cover.test'}, 'close_cover': {'service': 'cover.close_cover', 'entity_id': 'cover.test'}}}}}) self.hass.start() self.hass.block_till_done() state = self.hass.states.set('cover.test', STATE_CLOSED) self.hass.block_till_done() entity = self.hass.states.get('cover.test') attrs = dict() attrs['position'] = 42 self.hass.states.async_set(entity.entity_id, entity.state, attributes=attrs) self.hass.block_till_done() state = self.hass.states.get('cover.test_template_cover') assert (state.attributes.get('current_position') == 42.0) assert (state.state == STATE_OPEN) state = self.hass.states.set('cover.test', STATE_OPEN) self.hass.block_till_done() entity = self.hass.states.get('cover.test') attrs['position'] = 0.0 self.hass.states.async_set(entity.entity_id, entity.state, attributes=attrs) self.hass.block_till_done() state = self.hass.states.get('cover.test_template_cover') assert (state.attributes.get('current_position') == 0.0) assert (state.state == STATE_CLOSED)
'Test the tilt_template attribute.'
def test_template_tilt(self):
with assert_setup_component(1, 'cover'): assert setup.setup_component(self.hass, 'cover', {'cover': {'platform': 'template', 'covers': {'test_template_cover': {'value_template': '{{ 1 == 1 }}', 'tilt_template': '{{ 42 }}', 'open_cover': {'service': 'cover.open_cover', 'entity_id': 'cover.test_state'}, 'close_cover': {'service': 'cover.close_cover', 'entity_id': 'cover.test_state'}}}}}) self.hass.start() self.hass.block_till_done() state = self.hass.states.get('cover.test_template_cover') assert (state.attributes.get('current_tilt_position') == 42.0)
'Test template out-of-bounds condition.'
def test_template_out_of_bounds(self):
with assert_setup_component(1, 'cover'): assert setup.setup_component(self.hass, 'cover', {'cover': {'platform': 'template', 'covers': {'test_template_cover': {'position_template': '{{ -1 }}', 'tilt_template': '{{ 110 }}', 'open_cover': {'service': 'cover.open_cover', 'entity_id': 'cover.test_state'}, 'close_cover': {'service': 'cover.close_cover', 'entity_id': 'cover.test_state'}}}}}) self.hass.start() self.hass.block_till_done() state = self.hass.states.get('cover.test_template_cover') assert (state.attributes.get('current_tilt_position') is None) assert (state.attributes.get('current_position') is None)
'Test that only value or position template can be used.'
def test_template_mutex(self):
with assert_setup_component(0, 'cover'): assert setup.setup_component(self.hass, 'cover', {'cover': {'platform': 'template', 'covers': {'test_template_cover': {'value_template': '{{ 1 == 1 }}', 'position_template': '{{ 42 }}', 'open_cover': {'service': 'cover.open_cover', 'entity_id': 'cover.test_state'}, 'close_cover': {'service': 'cover.close_cover', 'entity_id': 'cover.test_state'}, 'icon_template': '{% if states.cover.test_state.state %}mdi:check{% endif %}'}}}}) self.hass.start() self.hass.block_till_done() assert (self.hass.states.all() == [])
'Test that at least one of value or position template is used.'
def test_template_position_or_value(self):
with assert_setup_component(1, 'cover'): assert setup.setup_component(self.hass, 'cover', {'cover': {'platform': 'template', 'covers': {'test_template_cover': {'open_cover': {'service': 'cover.open_cover', 'entity_id': 'cover.test_state'}, 'close_cover': {'service': 'cover.close_cover', 'entity_id': 'cover.test_state'}}}}}) self.hass.start() self.hass.block_till_done() assert (self.hass.states.all() == [])
'Test that at least one of open_cover or set_position is used.'
def test_template_open_or_position(self):
with assert_setup_component(1, 'cover'): assert setup.setup_component(self.hass, 'cover', {'cover': {'platform': 'template', 'covers': {'test_template_cover': {'value_template': '{{ 1 == 1 }}'}}}}) self.hass.start() self.hass.block_till_done() assert (self.hass.states.all() == [])
'Test that if open_cover is specified, cose_cover is too.'
def test_template_open_and_close(self):
with assert_setup_component(0, 'cover'): assert setup.setup_component(self.hass, 'cover', {'cover': {'platform': 'template', 'covers': {'test_template_cover': {'value_template': '{{ 1 == 1 }}', 'open_cover': {'service': 'cover.open_cover', 'entity_id': 'cover.test_state'}}}}}) self.hass.start() self.hass.block_till_done() assert (self.hass.states.all() == [])
'Test that tilt_template values are numeric.'
def test_template_non_numeric(self):
with assert_setup_component(1, 'cover'): assert setup.setup_component(self.hass, 'cover', {'cover': {'platform': 'template', 'covers': {'test_template_cover': {'position_template': '{{ on }}', 'tilt_template': '{% if states.cover.test_state.state %}on{% else %}off{% endif %}', 'open_cover': {'service': 'cover.open_cover', 'entity_id': 'cover.test_state'}, 'close_cover': {'service': 'cover.close_cover', 'entity_id': 'cover.test_state'}}}}}) self.hass.start() self.hass.block_till_done() state = self.hass.states.get('cover.test_template_cover') assert (state.attributes.get('current_tilt_position') is None) assert (state.attributes.get('current_position') is None)
'Test the open_cover command.'
def test_open_action(self):
with assert_setup_component(1, 'cover'): assert setup.setup_component(self.hass, 'cover', {'cover': {'platform': 'template', 'covers': {'test_template_cover': {'position_template': '{{ 0 }}', 'open_cover': {'service': 'test.automation'}, 'close_cover': {'service': 'cover.close_cover', 'entity_id': 'cover.test_state'}}}}}) self.hass.start() self.hass.block_till_done() state = self.hass.states.get('cover.test_template_cover') assert (state.state == STATE_CLOSED) cover.open_cover(self.hass, 'cover.test_template_cover') self.hass.block_till_done() assert (len(self.calls) == 1)
'Test the close-cover and stop_cover commands.'
def test_close_stop_action(self):
with assert_setup_component(1, 'cover'): assert setup.setup_component(self.hass, 'cover', {'cover': {'platform': 'template', 'covers': {'test_template_cover': {'position_template': '{{ 100 }}', 'open_cover': {'service': 'cover.open_cover', 'entity_id': 'cover.test_state'}, 'close_cover': {'service': 'test.automation'}, 'stop_cover': {'service': 'test.automation'}}}}}) self.hass.start() self.hass.block_till_done() state = self.hass.states.get('cover.test_template_cover') assert (state.state == STATE_OPEN) cover.close_cover(self.hass, 'cover.test_template_cover') self.hass.block_till_done() cover.stop_cover(self.hass, 'cover.test_template_cover') self.hass.block_till_done() assert (len(self.calls) == 2)
'Test the set_position command.'
def test_set_position(self):
with assert_setup_component(1, 'cover'): assert setup.setup_component(self.hass, 'input_slider', {'input_slider': {'test': {'min': '0', 'max': '100', 'initial': '42'}}}) assert setup.setup_component(self.hass, 'cover', {'cover': {'platform': 'template', 'covers': {'test_template_cover': {'position_template': '{{ states.input_slider.test.state | int }}', 'set_cover_position': {'service': 'input_slider.select_value', 'entity_id': 'input_slider.test', 'data_template': {'value': '{{ position }}'}}}}}}) self.hass.start() self.hass.block_till_done() state = self.hass.states.set('input_slider.test', 42) self.hass.block_till_done() state = self.hass.states.get('cover.test_template_cover') assert (state.state == STATE_OPEN) cover.open_cover(self.hass, 'cover.test_template_cover') self.hass.block_till_done() state = self.hass.states.get('cover.test_template_cover') assert (state.attributes.get('current_position') == 100.0) cover.close_cover(self.hass, 'cover.test_template_cover') self.hass.block_till_done() state = self.hass.states.get('cover.test_template_cover') assert (state.attributes.get('current_position') == 0.0) cover.set_cover_position(self.hass, 25, 'cover.test_template_cover') self.hass.block_till_done() state = self.hass.states.get('cover.test_template_cover') assert (state.attributes.get('current_position') == 25.0)
'Test the set_tilt_position command.'
def test_set_tilt_position(self):
with assert_setup_component(1, 'cover'): assert setup.setup_component(self.hass, 'cover', {'cover': {'platform': 'template', 'covers': {'test_template_cover': {'position_template': '{{ 100 }}', 'open_cover': {'service': 'cover.open_cover', 'entity_id': 'cover.test_state'}, 'close_cover': {'service': 'cover.close_cover', 'entity_id': 'cover.test_state'}, 'set_cover_tilt_position': {'service': 'test.automation'}}}}}) self.hass.start() self.hass.block_till_done() cover.set_cover_tilt_position(self.hass, 42, 'cover.test_template_cover') self.hass.block_till_done() assert (len(self.calls) == 1)
'Test the open_cover_tilt command.'
def test_open_tilt_action(self):
with assert_setup_component(1, 'cover'): assert setup.setup_component(self.hass, 'cover', {'cover': {'platform': 'template', 'covers': {'test_template_cover': {'position_template': '{{ 100 }}', 'open_cover': {'service': 'cover.open_cover', 'entity_id': 'cover.test_state'}, 'close_cover': {'service': 'cover.close_cover', 'entity_id': 'cover.test_state'}, 'set_cover_tilt_position': {'service': 'test.automation'}}}}}) self.hass.start() self.hass.block_till_done() cover.open_cover_tilt(self.hass, 'cover.test_template_cover') self.hass.block_till_done() assert (len(self.calls) == 1)
'Test the close_cover_tilt command.'
def test_close_tilt_action(self):
with assert_setup_component(1, 'cover'): assert setup.setup_component(self.hass, 'cover', {'cover': {'platform': 'template', 'covers': {'test_template_cover': {'position_template': '{{ 100 }}', 'open_cover': {'service': 'cover.open_cover', 'entity_id': 'cover.test_state'}, 'close_cover': {'service': 'cover.close_cover', 'entity_id': 'cover.test_state'}, 'set_cover_tilt_position': {'service': 'test.automation'}}}}}) self.hass.start() self.hass.block_till_done() cover.close_cover_tilt(self.hass, 'cover.test_template_cover') self.hass.block_till_done() assert (len(self.calls) == 1)
'Test icon template.'
def test_icon_template(self):
with assert_setup_component(1, 'cover'): assert setup.setup_component(self.hass, 'cover', {'cover': {'platform': 'template', 'covers': {'test_template_cover': {'value_template': '{{ states.cover.test_state.state }}', 'open_cover': {'service': 'cover.open_cover', 'entity_id': 'cover.test_state'}, 'close_cover': {'service': 'cover.close_cover', 'entity_id': 'cover.test_state'}, 'icon_template': '{% if states.cover.test_state.state %}mdi:check{% endif %}'}}}}) self.hass.start() self.hass.block_till_done() state = self.hass.states.get('cover.test_template_cover') assert (state.attributes.get('icon') == '') state = self.hass.states.set('cover.test_state', STATE_OPEN) self.hass.block_till_done() state = self.hass.states.get('cover.test_template_cover') assert (state.attributes['icon'] == 'mdi:check')
'Setup things to be run when tests are started.'
def setUp(self):
self.hass = get_test_home_assistant() mock_component('rfxtrx')
'Stop everything that was started.'
def tearDown(self):
rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS = [] rfxtrx_core.RFX_DEVICES = {} if rfxtrx_core.RFXOBJECT: rfxtrx_core.RFXOBJECT.close_connection() self.hass.stop()
'Test configuration.'
def test_valid_config(self):
self.assertTrue(setup_component(self.hass, 'cover', {'cover': {'platform': 'rfxtrx', 'automatic_add': True, 'devices': {'0b1100cd0213c7f210010f51': {'name': 'Test', rfxtrx_core.ATTR_FIREEVENT: True}}}}))
'Test configuration.'
def test_invalid_config_capital_letters(self):
self.assertFalse(setup_component(self.hass, 'cover', {'cover': {'platform': 'rfxtrx', 'automatic_add': True, 'devices': {'2FF7f216': {'name': 'Test', 'packetid': '0b1100cd0213c7f210010f51', 'signal_repetitions': 3}}}}))
'Test configuration.'
def test_invalid_config_extra_key(self):
self.assertFalse(setup_component(self.hass, 'cover', {'cover': {'platform': 'rfxtrx', 'automatic_add': True, 'invalid_key': 'afda', 'devices': {'213c7f216': {'name': 'Test', 'packetid': '0b1100cd0213c7f210010f51', rfxtrx_core.ATTR_FIREEVENT: True}}}}))
'Test configuration.'
def test_invalid_config_capital_packetid(self):
self.assertFalse(setup_component(self.hass, 'cover', {'cover': {'platform': 'rfxtrx', 'automatic_add': True, 'devices': {'213c7f216': {'name': 'Test', 'packetid': 'AA1100cd0213c7f210010f51', rfxtrx_core.ATTR_FIREEVENT: True}}}}))
'Test configuration.'
def test_invalid_config_missing_packetid(self):
self.assertFalse(setup_component(self.hass, 'cover', {'cover': {'platform': 'rfxtrx', 'automatic_add': True, 'devices': {'213c7f216': {'name': 'Test', rfxtrx_core.ATTR_FIREEVENT: True}}}}))
'Test with 0 cover.'
def test_default_config(self):
self.assertTrue(setup_component(self.hass, 'cover', {'cover': {'platform': 'rfxtrx', 'devices': {}}})) self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES))
'Test with 1 cover.'
def test_one_cover(self):
self.assertTrue(setup_component(self.hass, 'cover', {'cover': {'platform': 'rfxtrx', 'devices': {'0b1400cd0213c7f210010f51': {'name': 'Test'}}}})) import RFXtrx as rfxtrxmod rfxtrx_core.RFXOBJECT = rfxtrxmod.Core('', transport_protocol=rfxtrxmod.DummyTransport) self.assertEqual(1, len(rfxtrx_core.RFX_DEVICES)) for id in rfxtrx_core.RFX_DEVICES: entity = rfxtrx_core.RFX_DEVICES[id] self.assertEqual(entity.signal_repetitions, 1) self.assertFalse(entity.should_fire_event) self.assertFalse(entity.should_poll) entity.open_cover() entity.close_cover() entity.stop_cover()
'Test with 3 covers.'
def test_several_covers(self):
self.assertTrue(setup_component(self.hass, 'cover', {'cover': {'platform': 'rfxtrx', 'signal_repetitions': 3, 'devices': {'0b1100cd0213c7f230010f71': {'name': 'Test'}, '0b1100100118cdea02010f70': {'name': 'Bath'}, '0b1100101118cdea02010f70': {'name': 'Living'}}}})) self.assertEqual(3, len(rfxtrx_core.RFX_DEVICES)) device_num = 0 for id in rfxtrx_core.RFX_DEVICES: entity = rfxtrx_core.RFX_DEVICES[id] self.assertEqual(entity.signal_repetitions, 3) if (entity.name == 'Living'): device_num = (device_num + 1) elif (entity.name == 'Bath'): device_num = (device_num + 1) elif (entity.name == 'Test'): device_num = (device_num + 1) self.assertEqual(3, device_num)
'Test with discovery of covers.'
def test_discover_covers(self):
self.assertTrue(setup_component(self.hass, 'cover', {'cover': {'platform': 'rfxtrx', 'automatic_add': True, 'devices': {}}})) event = rfxtrx_core.get_rfx_object('0a140002f38cae010f0070') event.data = bytearray([10, 20, 0, 2, 243, 140, 174, 1, 15, 0, 112]) for evt_sub in rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS: evt_sub(event) self.assertEqual(1, len(rfxtrx_core.RFX_DEVICES)) event = rfxtrx_core.get_rfx_object('0a1400adf394ab020e0060') event.data = bytearray([10, 20, 0, 173, 243, 148, 171, 2, 14, 0, 96]) for evt_sub in rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS: evt_sub(event) self.assertEqual(2, len(rfxtrx_core.RFX_DEVICES)) event = rfxtrx_core.get_rfx_object('0a52085e070100b31b0279') event.data = bytearray('\nR\x08^\x07\x01\x00\xb3\x1b\x02y') for evt_sub in rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS: evt_sub(event) self.assertEqual(2, len(rfxtrx_core.RFX_DEVICES)) event = rfxtrx_core.get_rfx_object('0b1100100118cdea02010f70') event.data = bytearray([11, 17, 17, 16, 1, 24, 205, 234, 1, 2, 15, 112]) for evt_sub in rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS: evt_sub(event) self.assertEqual(2, len(rfxtrx_core.RFX_DEVICES))
'Test with discovery of cover when auto add is False.'
def test_discover_cover_noautoadd(self):
self.assertTrue(setup_component(self.hass, 'cover', {'cover': {'platform': 'rfxtrx', 'automatic_add': False, 'devices': {}}})) event = rfxtrx_core.get_rfx_object('0a1400adf394ab010d0060') event.data = bytearray([10, 20, 0, 173, 243, 148, 171, 1, 13, 0, 96]) for evt_sub in rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS: evt_sub(event) self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) event = rfxtrx_core.get_rfx_object('0a1400adf394ab020e0060') event.data = bytearray([10, 20, 0, 173, 243, 148, 171, 2, 14, 0, 96]) for evt_sub in rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS: evt_sub(event) self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) event = rfxtrx_core.get_rfx_object('0a52085e070100b31b0279') event.data = bytearray('\nR\x08^\x07\x01\x00\xb3\x1b\x02y') for evt_sub in rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS: evt_sub(event) self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES)) event = rfxtrx_core.get_rfx_object('0b1100100118cdea02010f70') event.data = bytearray([11, 17, 17, 16, 1, 24, 205, 234, 1, 2, 15, 112]) for evt_sub in rfxtrx_core.RECEIVED_EVT_SUBSCRIBERS: evt_sub(event) self.assertEqual(0, len(rfxtrx_core.RFX_DEVICES))
'Setup things to be run when tests are started.'
def setUp(self):
self.hass = get_test_home_assistant() self.assertTrue(setup_component(self.hass, cover.DOMAIN, {'cover': {'platform': 'demo'}}))
'Stop down everything that was started.'
def tearDown(self):
self.hass.stop()
'Test cover supported features.'
def test_supported_features(self):
state = self.hass.states.get('cover.garage_door') self.assertEqual(3, state.attributes.get('supported_features')) state = self.hass.states.get('cover.kitchen_window') self.assertEqual(11, state.attributes.get('supported_features')) state = self.hass.states.get('cover.hall_window') self.assertEqual(15, state.attributes.get('supported_features')) state = self.hass.states.get('cover.living_room_window') self.assertEqual(255, state.attributes.get('supported_features'))
'Test closing the cover.'
def test_close_cover(self):
state = self.hass.states.get(ENTITY_COVER) self.assertEqual(state.state, 'open') self.assertEqual(70, state.attributes.get('current_position')) cover.close_cover(self.hass, ENTITY_COVER) self.hass.block_till_done() state = self.hass.states.get(ENTITY_COVER) self.assertEqual(state.state, 'closing') for _ in range(7): future = (dt_util.utcnow() + timedelta(seconds=1)) fire_time_changed(self.hass, future) self.hass.block_till_done() state = self.hass.states.get(ENTITY_COVER) self.assertEqual(state.state, 'closed') self.assertEqual(0, state.attributes.get('current_position'))
'Test opening the cover.'
def test_open_cover(self):
state = self.hass.states.get(ENTITY_COVER) self.assertEqual(state.state, 'open') self.assertEqual(70, state.attributes.get('current_position')) cover.open_cover(self.hass, ENTITY_COVER) self.hass.block_till_done() state = self.hass.states.get(ENTITY_COVER) self.assertEqual(state.state, 'opening') for _ in range(7): future = (dt_util.utcnow() + timedelta(seconds=1)) fire_time_changed(self.hass, future) self.hass.block_till_done() state = self.hass.states.get(ENTITY_COVER) self.assertEqual(state.state, 'open') self.assertEqual(100, state.attributes.get('current_position'))
'Test moving the cover to a specific position.'
def test_set_cover_position(self):
state = self.hass.states.get(ENTITY_COVER) self.assertEqual(70, state.attributes.get('current_position')) cover.set_cover_position(self.hass, 10, ENTITY_COVER) self.hass.block_till_done() for _ in range(6): future = (dt_util.utcnow() + timedelta(seconds=1)) fire_time_changed(self.hass, future) self.hass.block_till_done() state = self.hass.states.get(ENTITY_COVER) self.assertEqual(10, state.attributes.get('current_position'))
'Test stopping the cover.'
def test_stop_cover(self):
state = self.hass.states.get(ENTITY_COVER) self.assertEqual(70, state.attributes.get('current_position')) cover.open_cover(self.hass, ENTITY_COVER) self.hass.block_till_done() future = (dt_util.utcnow() + timedelta(seconds=1)) fire_time_changed(self.hass, future) self.hass.block_till_done() cover.stop_cover(self.hass, ENTITY_COVER) self.hass.block_till_done() fire_time_changed(self.hass, future) state = self.hass.states.get(ENTITY_COVER) self.assertEqual(80, state.attributes.get('current_position'))
'Test closing the cover tilt.'
def test_close_cover_tilt(self):
state = self.hass.states.get(ENTITY_COVER) self.assertEqual(50, state.attributes.get('current_tilt_position')) cover.close_cover_tilt(self.hass, ENTITY_COVER) self.hass.block_till_done() for _ in range(7): future = (dt_util.utcnow() + timedelta(seconds=1)) fire_time_changed(self.hass, future) self.hass.block_till_done() state = self.hass.states.get(ENTITY_COVER) self.assertEqual(0, state.attributes.get('current_tilt_position'))
'Test opening the cover tilt.'
def test_open_cover_tilt(self):
state = self.hass.states.get(ENTITY_COVER) self.assertEqual(50, state.attributes.get('current_tilt_position')) cover.open_cover_tilt(self.hass, ENTITY_COVER) self.hass.block_till_done() for _ in range(7): future = (dt_util.utcnow() + timedelta(seconds=1)) fire_time_changed(self.hass, future) self.hass.block_till_done() state = self.hass.states.get(ENTITY_COVER) self.assertEqual(100, state.attributes.get('current_tilt_position'))
'Test moving the cover til to a specific position.'
def test_set_cover_tilt_position(self):
state = self.hass.states.get(ENTITY_COVER) self.assertEqual(50, state.attributes.get('current_tilt_position')) cover.set_cover_tilt_position(self.hass, 90, ENTITY_COVER) self.hass.block_till_done() for _ in range(7): future = (dt_util.utcnow() + timedelta(seconds=1)) fire_time_changed(self.hass, future) self.hass.block_till_done() state = self.hass.states.get(ENTITY_COVER) self.assertEqual(90, state.attributes.get('current_tilt_position'))
'Test stopping the cover tilt.'
def test_stop_cover_tilt(self):
state = self.hass.states.get(ENTITY_COVER) self.assertEqual(50, state.attributes.get('current_tilt_position')) cover.close_cover_tilt(self.hass, ENTITY_COVER) self.hass.block_till_done() future = (dt_util.utcnow() + timedelta(seconds=1)) fire_time_changed(self.hass, future) self.hass.block_till_done() cover.stop_cover_tilt(self.hass, ENTITY_COVER) self.hass.block_till_done() fire_time_changed(self.hass, future) state = self.hass.states.get(ENTITY_COVER) self.assertEqual(40, state.attributes.get('current_tilt_position'))
'Setup things to be run when tests are started.'
def setup_method(self, method):
self.hass = get_test_home_assistant() self.rs = cmd_rs.CommandCover(self.hass, 'foo', 'command_open', 'command_close', 'command_stop', 'command_state', None)
'Stop down everything that was started.'
def teardown_method(self, method):
self.hass.stop()
'Test the setting of polling.'
def test_should_poll(self):
self.assertTrue(self.rs.should_poll) self.rs._command_state = None self.assertFalse(self.rs.should_poll)
'Test with state value.'
def test_query_state_value(self):
with mock.patch('subprocess.check_output') as mock_run: mock_run.return_value = ' foo bar ' result = self.rs._query_state_value('runme') self.assertEqual('foo bar', result) self.assertEqual(mock_run.call_count, 1) self.assertEqual(mock_run.call_args, mock.call('runme', shell=True))
'Test with state value.'
def test_state_value(self):
with tempfile.TemporaryDirectory() as tempdirname: path = os.path.join(tempdirname, 'cover_status') test_cover = {'command_state': 'cat {}'.format(path), 'command_open': 'echo 1 > {}'.format(path), 'command_close': 'echo 1 > {}'.format(path), 'command_stop': 'echo 0 > {}'.format(path), 'value_template': '{{ value }}'} self.assertTrue(setup_component(self.hass, cover.DOMAIN, {'cover': {'platform': 'command_line', 'covers': {'test': test_cover}}})) state = self.hass.states.get('cover.test') self.assertEqual('unknown', state.state) cover.open_cover(self.hass, 'cover.test') self.hass.block_till_done() state = self.hass.states.get('cover.test') self.assertEqual('open', state.state) cover.close_cover(self.hass, 'cover.test') self.hass.block_till_done() state = self.hass.states.get('cover.test') self.assertEqual('open', state.state) cover.stop_cover(self.hass, 'cover.test') self.hass.block_till_done() state = self.hass.states.get('cover.test') self.assertEqual('closed', state.state)
'Setup things to be run when tests are started.'
def setUp(self):
self.hass = get_test_home_assistant() init_recorder_component(self.hass) self.hass.start()
'Stop everything that was started.'
def tearDown(self):
self.hass.stop()
'Add multiple states to the db for testing.'
def _add_test_states(self):
now = datetime.now() five_days_ago = (now - timedelta(days=5)) attributes = {'test_attr': 5, 'test_attr_10': 'nice'} self.hass.block_till_done() self.hass.data[DATA_INSTANCE].block_till_done() with recorder.session_scope(hass=self.hass) as session: for event_id in range(5): if (event_id < 3): timestamp = five_days_ago state = 'purgeme' else: timestamp = now state = 'dontpurgeme' session.add(States(entity_id='test.recorder2', domain='sensor', state=state, attributes=json.dumps(attributes), last_changed=timestamp, last_updated=timestamp, created=timestamp, event_id=(event_id + 1000)))
'Add a few events for testing.'
def _add_test_events(self):
now = datetime.now() five_days_ago = (now - timedelta(days=5)) event_data = {'test_attr': 5, 'test_attr_10': 'nice'} self.hass.block_till_done() self.hass.data[DATA_INSTANCE].block_till_done() with recorder.session_scope(hass=self.hass) as session: for event_id in range(5): if (event_id < 2): timestamp = five_days_ago event_type = 'EVENT_TEST_PURGE' else: timestamp = now event_type = 'EVENT_TEST' session.add(Events(event_type=event_type, event_data=json.dumps(event_data), origin='LOCAL', created=timestamp, time_fired=timestamp))
'Test deleting old states.'
def test_purge_old_states(self):
self._add_test_states() with session_scope(hass=self.hass) as session: states = session.query(States) self.assertEqual(states.count(), 5) purge_old_data(self.hass.data[DATA_INSTANCE], 4) self.assertEqual(states.count(), 2)
'Test deleting old events.'
def test_purge_old_events(self):
self._add_test_events() with session_scope(hass=self.hass) as session: events = session.query(Events).filter(Events.event_type.like('EVENT_TEST%')) self.assertEqual(events.count(), 5) purge_old_data(self.hass.data[DATA_INSTANCE], 4) self.assertEqual(events.count(), 3)
'Create an event database object from a native event.'
@staticmethod def from_event(event):
return Events(event_type=event.event_type, event_data=json.dumps(event.data, cls=JSONEncoder), origin=str(event.origin), time_fired=event.time_fired)
'Convert to a natve HA Event.'
def to_native(self):
try: return Event(self.event_type, json.loads(self.event_data), EventOrigin(self.origin), _process_timestamp(self.time_fired)) except ValueError: _LOGGER.exception('Error converting to event: %s', self) return None
'Create object from a state_changed event.'
@staticmethod def from_event(event):
entity_id = event.data['entity_id'] state = event.data.get('new_state') dbstate = States(entity_id=entity_id) if (state is None): dbstate.state = '' dbstate.domain = split_entity_id(entity_id)[0] dbstate.attributes = '{}' dbstate.last_changed = event.time_fired dbstate.last_updated = event.time_fired else: dbstate.domain = state.domain dbstate.state = state.state dbstate.attributes = json.dumps(dict(state.attributes), cls=JSONEncoder) dbstate.last_changed = state.last_changed dbstate.last_updated = state.last_updated return dbstate
'Convert to an HA state object.'
def to_native(self):
try: return State(self.entity_id, self.state, json.loads(self.attributes), _process_timestamp(self.last_changed), _process_timestamp(self.last_updated)) except ValueError: _LOGGER.exception('Error converting row to state: %s', self) return None
'Return the entity ids that existed in this run. Specify point_in_time if you want to know which existed at that point in time inside the run.'
def entity_ids(self, point_in_time=None):
from sqlalchemy.orm.session import Session session = Session.object_session(self) assert (session is not None), 'RecorderRuns need to be persisted' query = session.query(distinct(States.entity_id)).filter((States.last_updated >= self.start)) if (point_in_time is not None): query = query.filter((States.last_updated < point_in_time)) elif (self.end is not None): query = query.filter((States.last_updated < self.end)) return [row[0] for row in query]
'Return self, native format is this model.'
def to_native(self):
return self
'Test converting event to db event.'
def test_from_event(self):
event = ha.Event('test_event', {'some_data': 15}) assert (event == Events.from_event(event).to_native())
'Test converting event to db state.'
def test_from_event(self):
state = ha.State('sensor.temperature', '18') event = ha.Event(EVENT_STATE_CHANGED, {'entity_id': 'sensor.temperature', 'old_state': None, 'new_state': state}) assert (state == States.from_event(event).to_native())
'Test converting deleting state event to db state.'
def test_from_event_to_delete_state(self):
event = ha.Event(EVENT_STATE_CHANGED, {'entity_id': 'sensor.temperature', 'old_state': ha.State('sensor.temperature', '18'), 'new_state': None}) db_state = States.from_event(event) assert (db_state.entity_id == 'sensor.temperature') assert (db_state.domain == 'sensor') assert (db_state.state == '') assert (db_state.last_changed == event.time_fired) assert (db_state.last_updated == event.time_fired)
'Set up recorder runs.'
def setUp(self):
self.session = session = SESSION() session.query(Events).delete() session.query(States).delete() session.query(RecorderRuns).delete()
'Clean up.'
def tearDown(self):
self.session.rollback()
'Test if entity ids helper method works.'
def test_entity_ids(self):
run = RecorderRuns(start=datetime(2016, 7, 9, 11, 0, 0, tzinfo=dt.UTC), end=datetime(2016, 7, 9, 23, 0, 0, tzinfo=dt.UTC), closed_incorrect=False, created=datetime(2016, 7, 9, 11, 0, 0, tzinfo=dt.UTC)) self.session.add(run) self.session.commit() before_run = datetime(2016, 7, 9, 8, 0, 0, tzinfo=dt.UTC) in_run = datetime(2016, 7, 9, 13, 0, 0, tzinfo=dt.UTC) in_run2 = datetime(2016, 7, 9, 15, 0, 0, tzinfo=dt.UTC) in_run3 = datetime(2016, 7, 9, 18, 0, 0, tzinfo=dt.UTC) after_run = datetime(2016, 7, 9, 23, 30, 0, tzinfo=dt.UTC) assert (run.to_native() == run) assert (run.entity_ids() == []) self.session.add(States(entity_id='sensor.temperature', state='20', last_changed=before_run, last_updated=before_run)) self.session.add(States(entity_id='sensor.sound', state='10', last_changed=after_run, last_updated=after_run)) self.session.add(States(entity_id='sensor.humidity', state='76', last_changed=in_run, last_updated=in_run)) self.session.add(States(entity_id='sensor.lux', state='5', last_changed=in_run3, last_updated=in_run3)) assert (sorted(run.entity_ids()) == ['sensor.humidity', 'sensor.lux']) assert (run.entity_ids(in_run2) == ['sensor.humidity'])
'Setup things to be run when tests are started.'
def setUp(self):
self.hass = get_test_home_assistant() init_recorder_component(self.hass) self.hass.start()
'Stop everything that was started.'
def tearDown(self):
self.hass.stop()
'Test saving and restoring a state.'
def test_saving_state(self):
entity_id = 'test.recorder' state = 'restoring_from_db' attributes = {'test_attr': 5, 'test_attr_10': 'nice'} self.hass.states.set(entity_id, state, attributes) self.hass.block_till_done() self.hass.data[DATA_INSTANCE].block_till_done() with session_scope(hass=self.hass) as session: db_states = list(session.query(States)) assert (len(db_states) == 1) state = db_states[0].to_native() assert (state == self.hass.states.get(entity_id))
'Test saving and restoring an event.'
def test_saving_event(self):
event_type = 'EVENT_TEST' event_data = {'test_attr': 5, 'test_attr_10': 'nice'} events = [] @callback def event_listener(event): 'Record events from eventbus.' if (event.event_type == event_type): events.append(event) self.hass.bus.listen(MATCH_ALL, event_listener) self.hass.bus.fire(event_type, event_data) self.hass.block_till_done() assert (len(events) == 1) event = events[0] self.hass.data[DATA_INSTANCE].block_till_done() with session_scope(hass=self.hass) as session: db_events = list(session.query(Events).filter_by(event_type=event_type)) assert (len(db_events) == 1) db_event = db_events[0].to_native() assert (event.event_type == db_event.event_type) assert (event.data == db_event.data) assert (event.origin == db_event.origin) assert (event.time_fired.replace(microsecond=0) == db_event.time_fired.replace(microsecond=0))
'Stop everything that was started.'
def tearDown(self):
hass.block_till_done()
'Test when action is not completed.'
def test_intent_action_incomplete(self):
data = {'id': REQUEST_ID, 'timestamp': REQUEST_TIMESTAMP, 'result': {'source': 'agent', 'resolvedQuery': 'my zodiac sign is virgo', 'speech': '', 'action': 'GetZodiacHoroscopeIntent', 'actionIncomplete': True, 'parameters': {'ZodiacSign': 'virgo'}, 'metadata': {'intentId': INTENT_ID, 'webhookUsed': 'true', 'webhookForSlotFillingUsed': 'false', 'intentName': INTENT_NAME}, 'fulfillment': {'speech': '', 'messages': [{'type': 0, 'speech': ''}]}, 'score': 1}, 'status': {'code': 200, 'errorType': 'success'}, 'sessionId': SESSION_ID, 'originalRequest': None} req = _intent_req(data) self.assertEqual(200, req.status_code) self.assertEqual('', req.text)
'Test when API.AI asks for slot-filling return none.'
def test_intent_slot_filling(self):
data = {'id': REQUEST_ID, 'timestamp': REQUEST_TIMESTAMP, 'result': {'source': 'agent', 'resolvedQuery': 'my zodiac sign is', 'speech': '', 'action': 'GetZodiacHoroscopeIntent', 'actionIncomplete': True, 'parameters': {'ZodiacSign': ''}, 'contexts': [{'name': CONTEXT_NAME, 'parameters': {'ZodiacSign.original': '', 'ZodiacSign': ''}, 'lifespan': 2}, {'name': 'tests_ha_dialog_context', 'parameters': {'ZodiacSign.original': '', 'ZodiacSign': ''}, 'lifespan': 2}, {'name': 'tests_ha_dialog_params_zodiacsign', 'parameters': {'ZodiacSign.original': '', 'ZodiacSign': ''}, 'lifespan': 1}], 'metadata': {'intentId': INTENT_ID, 'webhookUsed': 'true', 'webhookForSlotFillingUsed': 'true', 'intentName': INTENT_NAME}, 'fulfillment': {'speech': 'What is the ZodiacSign?', 'messages': [{'type': 0, 'speech': 'What is the ZodiacSign?'}]}, 'score': 0.77}, 'status': {'code': 200, 'errorType': 'success'}, 'sessionId': SESSION_ID, 'originalRequest': None} req = _intent_req(data) self.assertEqual(200, req.status_code) self.assertEqual('', req.text)
'Test a request with parameters.'
def test_intent_request_with_parameters(self):
data = {'id': REQUEST_ID, 'timestamp': REQUEST_TIMESTAMP, 'result': {'source': 'agent', 'resolvedQuery': 'my zodiac sign is virgo', 'speech': '', 'action': 'GetZodiacHoroscopeIntent', 'actionIncomplete': False, 'parameters': {'ZodiacSign': 'virgo'}, 'contexts': [], 'metadata': {'intentId': INTENT_ID, 'webhookUsed': 'true', 'webhookForSlotFillingUsed': 'false', 'intentName': INTENT_NAME}, 'fulfillment': {'speech': '', 'messages': [{'type': 0, 'speech': ''}]}, 'score': 1}, 'status': {'code': 200, 'errorType': 'success'}, 'sessionId': SESSION_ID, 'originalRequest': None} req = _intent_req(data) self.assertEqual(200, req.status_code) text = req.json().get('speech') self.assertEqual('You told us your sign is virgo.', text)
'Test a request with parameters but empty value.'
def test_intent_request_with_parameters_but_empty(self):
data = {'id': REQUEST_ID, 'timestamp': REQUEST_TIMESTAMP, 'result': {'source': 'agent', 'resolvedQuery': 'my zodiac sign is virgo', 'speech': '', 'action': 'GetZodiacHoroscopeIntent', 'actionIncomplete': False, 'parameters': {'ZodiacSign': ''}, 'contexts': [], 'metadata': {'intentId': INTENT_ID, 'webhookUsed': 'true', 'webhookForSlotFillingUsed': 'false', 'intentName': INTENT_NAME}, 'fulfillment': {'speech': '', 'messages': [{'type': 0, 'speech': ''}]}, 'score': 1}, 'status': {'code': 200, 'errorType': 'success'}, 'sessionId': SESSION_ID, 'originalRequest': None} req = _intent_req(data) self.assertEqual(200, req.status_code) text = req.json().get('speech') self.assertEqual('You told us your sign is .', text)
'Test a request without slots.'
def test_intent_request_without_slots(self):
data = {'id': REQUEST_ID, 'timestamp': REQUEST_TIMESTAMP, 'result': {'source': 'agent', 'resolvedQuery': 'where are we', 'speech': '', 'action': 'WhereAreWeIntent', 'actionIncomplete': False, 'parameters': {}, 'contexts': [], 'metadata': {'intentId': INTENT_ID, 'webhookUsed': 'true', 'webhookForSlotFillingUsed': 'false', 'intentName': INTENT_NAME}, 'fulfillment': {'speech': '', 'messages': [{'type': 0, 'speech': ''}]}, 'score': 1}, 'status': {'code': 200, 'errorType': 'success'}, 'sessionId': SESSION_ID, 'originalRequest': None} req = _intent_req(data) self.assertEqual(200, req.status_code) text = req.json().get('speech') self.assertEqual('Anne Therese is at unknown and Paulus is at unknown', text) hass.states.set('device_tracker.paulus', 'home') hass.states.set('device_tracker.anne_therese', 'home') req = _intent_req(data) self.assertEqual(200, req.status_code) text = req.json().get('speech') self.assertEqual('You are both home, you silly', text)
'Test a request for calling a service. If this request is done async the test could finish before the action has been executed. Hard to test because it will be a race condition.'
def test_intent_request_calling_service(self):
data = {'id': REQUEST_ID, 'timestamp': REQUEST_TIMESTAMP, 'result': {'source': 'agent', 'resolvedQuery': 'my zodiac sign is virgo', 'speech': '', 'action': 'CallServiceIntent', 'actionIncomplete': False, 'parameters': {'ZodiacSign': 'virgo'}, 'contexts': [], 'metadata': {'intentId': INTENT_ID, 'webhookUsed': 'true', 'webhookForSlotFillingUsed': 'false', 'intentName': INTENT_NAME}, 'fulfillment': {'speech': '', 'messages': [{'type': 0, 'speech': ''}]}, 'score': 1}, 'status': {'code': 200, 'errorType': 'success'}, 'sessionId': SESSION_ID, 'originalRequest': None} call_count = len(calls) req = _intent_req(data) self.assertEqual(200, req.status_code) self.assertEqual((call_count + 1), len(calls)) call = calls[(-1)] self.assertEqual('test', call.domain) self.assertEqual('apiai', call.service) self.assertEqual(['switch.test'], call.data.get('entity_id')) self.assertEqual('virgo', call.data.get('hello'))
'Test a intent with no defined action.'
def test_intent_with_no_action(self):
data = {'id': REQUEST_ID, 'timestamp': REQUEST_TIMESTAMP, 'result': {'source': 'agent', 'resolvedQuery': 'my zodiac sign is virgo', 'speech': '', 'action': '', 'actionIncomplete': False, 'parameters': {'ZodiacSign': ''}, 'contexts': [], 'metadata': {'intentId': INTENT_ID, 'webhookUsed': 'true', 'webhookForSlotFillingUsed': 'false', 'intentName': INTENT_NAME}, 'fulfillment': {'speech': '', 'messages': [{'type': 0, 'speech': ''}]}, 'score': 1}, 'status': {'code': 200, 'errorType': 'success'}, 'sessionId': SESSION_ID, 'originalRequest': None} req = _intent_req(data) self.assertEqual(200, req.status_code) text = req.json().get('speech') self.assertEqual('You have not defined an action in your api.ai intent.', text)
'Test a intent with an action not defined in the conf.'
def test_intent_with_unknown_action(self):
data = {'id': REQUEST_ID, 'timestamp': REQUEST_TIMESTAMP, 'result': {'source': 'agent', 'resolvedQuery': 'my zodiac sign is virgo', 'speech': '', 'action': 'unknown', 'actionIncomplete': False, 'parameters': {'ZodiacSign': ''}, 'contexts': [], 'metadata': {'intentId': INTENT_ID, 'webhookUsed': 'true', 'webhookForSlotFillingUsed': 'false', 'intentName': INTENT_NAME}, 'fulfillment': {'speech': '', 'messages': [{'type': 0, 'speech': ''}]}, 'score': 1}, 'status': {'code': 200, 'errorType': 'success'}, 'sessionId': SESSION_ID, 'originalRequest': None} req = _intent_req(data) self.assertEqual(200, req.status_code) text = req.json().get('speech') self.assertEqual('This intent is not yet configured within Home Assistant.', text)
'Setup things to be run when tests are started.'
def setUp(self):
self.hass = get_test_home_assistant() _base_mock = MagicMock() pykira = _base_mock.pykira pykira.__file__ = 'test' self._module_patcher = patch.dict('sys.modules', {'pykira': pykira}) self._module_patcher.start() self.work_dir = tempfile.mkdtemp()
'Stop everything that was started.'
def tearDown(self):
self.hass.stop() self._module_patcher.stop() shutil.rmtree(self.work_dir, ignore_errors=True)
'Kira component should load a default sensor.'
def test_kira_empty_config(self):
setup_component(self.hass, kira.DOMAIN, {}) assert (len(self.hass.data[kira.DOMAIN]['sensor']) == 1)
'Ensure platforms are loaded correctly.'
def test_kira_setup(self):
setup_component(self.hass, kira.DOMAIN, TEST_CONFIG) assert (len(self.hass.data[kira.DOMAIN]['sensor']) == 2) assert (sorted(self.hass.data[kira.DOMAIN]['sensor'].keys()) == ['kira', 'kira_1']) assert (len(self.hass.data[kira.DOMAIN]['remote']) == 2) assert (sorted(self.hass.data[kira.DOMAIN]['remote'].keys()) == ['kira', 'kira_1'])
'Kira module should create codes file if missing.'
def test_kira_creates_codes(self):
code_path = os.path.join(self.work_dir, 'codes.yaml') kira.load_codes(code_path) assert os.path.exists(code_path), "Kira component didn't create codes file"
'Kira should ignore invalid codes.'
def test_load_codes(self):
code_path = os.path.join(self.work_dir, 'codes.yaml') with open(code_path, 'w') as code_file: code_file.write(KIRA_CODES) res = kira.load_codes(code_path) assert (len(res) == 1), 'Expected exactly 1 valid Kira code'
'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 configuration with defaults.'
def test_invalid_config(self):
config = {'statsd': {'host1': 'host1'}} with self.assertRaises(vol.Invalid): statsd.CONFIG_SCHEMA(None) with self.assertRaises(vol.Invalid): statsd.CONFIG_SCHEMA(config)
'Test setup with all data.'
@mock.patch('statsd.StatsClient') def test_statsd_setup_full(self, mock_connection):
config = {'statsd': {'host': 'host', 'port': 123, 'rate': 1, 'prefix': 'foo'}} self.hass.bus.listen = mock.MagicMock() self.assertTrue(setup_component(self.hass, statsd.DOMAIN, config)) self.assertEqual(mock_connection.call_count, 1) self.assertEqual(mock_connection.call_args, mock.call(host='host', port=123, prefix='foo')) self.assertTrue(self.hass.bus.listen.called) self.assertEqual(EVENT_STATE_CHANGED, self.hass.bus.listen.call_args_list[0][0][0])
'Test setup with defaults.'
@mock.patch('statsd.StatsClient') def test_statsd_setup_defaults(self, mock_connection):
config = {'statsd': {'host': 'host'}} config['statsd'][statsd.CONF_PORT] = statsd.DEFAULT_PORT config['statsd'][statsd.CONF_PREFIX] = statsd.DEFAULT_PREFIX self.hass.bus.listen = mock.MagicMock() self.assertTrue(setup_component(self.hass, statsd.DOMAIN, config)) self.assertEqual(mock_connection.call_count, 1) self.assertEqual(mock_connection.call_args, mock.call(host='host', port=8125, prefix='hass')) self.assertTrue(self.hass.bus.listen.called)
'Test event listener.'
@mock.patch('statsd.StatsClient') def test_event_listener_defaults(self, mock_client):
config = {'statsd': {'host': 'host', 'value_mapping': {'custom': 3}}} config['statsd'][statsd.CONF_RATE] = statsd.DEFAULT_RATE self.hass.bus.listen = mock.MagicMock() setup_component(self.hass, statsd.DOMAIN, config) self.assertTrue(self.hass.bus.listen.called) handler_method = self.hass.bus.listen.call_args_list[0][0][1] valid = {'1': 1, '1.0': 1.0, 'custom': 3, STATE_ON: 1, STATE_OFF: 0} for (in_, out) in valid.items(): state = mock.MagicMock(state=in_, attributes={'attribute key': 3.2}) handler_method(mock.MagicMock(data={'new_state': state})) mock_client.return_value.gauge.assert_has_calls([mock.call(state.entity_id, out, statsd.DEFAULT_RATE)]) mock_client.return_value.gauge.reset_mock() self.assertEqual(mock_client.return_value.incr.call_count, 1) self.assertEqual(mock_client.return_value.incr.call_args, mock.call(state.entity_id, rate=statsd.DEFAULT_RATE)) mock_client.return_value.incr.reset_mock() for invalid in ('foo', '', object): handler_method(mock.MagicMock(data={'new_state': ha.State('domain.test', invalid, {})})) self.assertFalse(mock_client.return_value.gauge.called) self.assertTrue(mock_client.return_value.incr.called)