Event trigger nested conditions (#9732)

* Test to supported nested event triggers

* Update event trigger to allow nested data tests
This commit is contained in:
Adam Mills 2017-10-07 16:13:32 -04:00 committed by Paulus Schoutsen
parent af3ea5a321
commit 4342d7aa17
2 changed files with 44 additions and 10 deletions

View File

@ -21,7 +21,7 @@ _LOGGER = logging.getLogger(__name__)
TRIGGER_SCHEMA = vol.Schema({ TRIGGER_SCHEMA = vol.Schema({
vol.Required(CONF_PLATFORM): 'event', vol.Required(CONF_PLATFORM): 'event',
vol.Required(CONF_EVENT_TYPE): cv.string, vol.Required(CONF_EVENT_TYPE): cv.string,
vol.Optional(CONF_EVENT_DATA): dict, vol.Optional(CONF_EVENT_DATA, default={}): dict,
}) })
@ -29,18 +29,24 @@ TRIGGER_SCHEMA = vol.Schema({
def async_trigger(hass, config, action): def async_trigger(hass, config, action):
"""Listen for events based on configuration.""" """Listen for events based on configuration."""
event_type = config.get(CONF_EVENT_TYPE) event_type = config.get(CONF_EVENT_TYPE)
event_data = config.get(CONF_EVENT_DATA) event_data_schema = vol.Schema(
config.get(CONF_EVENT_DATA),
extra=vol.ALLOW_EXTRA)
@callback @callback
def handle_event(event): def handle_event(event):
"""Listen for events and calls the action when data matches.""" """Listen for events and calls the action when data matches."""
if not event_data or all(val == event.data.get(key) for key, val try:
in event_data.items()): event_data_schema(event.data)
hass.async_run_job(action, { except vol.Invalid:
'trigger': { # If event data doesn't match requested schema, skip event
'platform': 'event', return
'event': event,
}, hass.async_run_job(action, {
}) 'trigger': {
'platform': 'event',
'event': event,
},
})
return hass.bus.async_listen(event_type, handle_event) return hass.bus.async_listen(event_type, handle_event)

View File

@ -74,6 +74,34 @@ class TestAutomationEvent(unittest.TestCase):
self.hass.block_till_done() self.hass.block_till_done()
self.assertEqual(1, len(self.calls)) self.assertEqual(1, len(self.calls))
def test_if_fires_on_event_with_nested_data(self):
"""Test the firing of events with nested data."""
assert setup_component(self.hass, automation.DOMAIN, {
automation.DOMAIN: {
'trigger': {
'platform': 'event',
'event_type': 'test_event',
'event_data': {
'parent_attr': {
'some_attr': 'some_value'
}
}
},
'action': {
'service': 'test.automation',
}
}
})
self.hass.bus.fire('test_event', {
'parent_attr': {
'some_attr': 'some_value',
'another': 'value'
}
})
self.hass.block_till_done()
self.assertEqual(1, len(self.calls))
def test_if_not_fires_if_event_data_not_matches(self): def test_if_not_fires_if_event_data_not_matches(self):
"""Test firing of event if no match.""" """Test firing of event if no match."""
assert setup_component(self.hass, automation.DOMAIN, { assert setup_component(self.hass, automation.DOMAIN, {