From 467cb18625da9323f743ed62a342e446a79fb05b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20H=C3=B8yer=20Iversen?= Date: Wed, 11 Jan 2017 16:23:05 +0100 Subject: [PATCH] Add last triggered to script (#5261) * Add last triggered to script * Add tests for script last_triggered --- homeassistant/components/script.py | 2 ++ homeassistant/helpers/script.py | 2 ++ tests/helpers/test_script.py | 19 +++++++++++++++++++ 3 files changed, 23 insertions(+) diff --git a/homeassistant/components/script.py b/homeassistant/components/script.py index df46fb5a03dd85..05cbc5d0a807c2 100644 --- a/homeassistant/components/script.py +++ b/homeassistant/components/script.py @@ -31,6 +31,7 @@ ATTR_VARIABLES = 'variables' ATTR_LAST_ACTION = 'last_action' +ATTR_LAST_TRIGGERED = 'last_triggered' ATTR_CAN_CANCEL = 'can_cancel' _LOGGER = logging.getLogger(__name__) @@ -155,6 +156,7 @@ def name(self): def state_attributes(self): """Return the state attributes.""" attrs = {} + attrs[ATTR_LAST_TRIGGERED] = self.script.last_triggered if self.script.can_cancel: attrs[ATTR_CAN_CANCEL] = self.script.can_cancel if self.script.last_action: diff --git a/homeassistant/helpers/script.py b/homeassistant/helpers/script.py index 4d6a2b01df7a1e..46703d86450038 100644 --- a/homeassistant/helpers/script.py +++ b/homeassistant/helpers/script.py @@ -46,6 +46,7 @@ def __init__(self, hass: HomeAssistant, sequence, name: str=None, self._change_listener = change_listener self._cur = -1 self.last_action = None + self.last_triggered = None self.can_cancel = any(CONF_DELAY in action for action in self.sequence) self._async_unsub_delay_listener = None @@ -68,6 +69,7 @@ def async_run(self, variables: Optional[Sequence]=None) -> None: This method is a coroutine. """ + self.last_triggered = date_util.utcnow() if self._cur == -1: self._log('Running script') self._cur = 0 diff --git a/tests/helpers/test_script.py b/tests/helpers/test_script.py index 8787ff7b514652..6eee484097b1d7 100644 --- a/tests/helpers/test_script.py +++ b/tests/helpers/test_script.py @@ -353,3 +353,22 @@ def record_event(event): script_obj.run() self.hass.block_till_done() assert len(script_obj._config_cache) == 2 + + def test_last_triggered(self): + """Test the last_triggered.""" + event = 'test_event' + + script_obj = script.Script(self.hass, cv.SCRIPT_SCHEMA([ + {'event': event}, + {'delay': {'seconds': 5}}, + {'event': event}])) + + assert script_obj.last_triggered is None + + time = dt_util.utcnow() + with mock.patch('homeassistant.helpers.script.date_util.utcnow', + return_value=time): + script_obj.run() + self.hass.block_till_done() + + assert script_obj.last_triggered == time