Skip to content

Commit

Permalink
Add last triggered to script (#5261)
Browse files Browse the repository at this point in the history
* Add last triggered to script

* Add tests for script last_triggered
  • Loading branch information
Danielhiversen authored and balloob committed Jan 11, 2017
1 parent 82d037a commit 467cb18
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 0 deletions.
2 changes: 2 additions & 0 deletions homeassistant/components/script.py
Expand Up @@ -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__)
Expand Down Expand Up @@ -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:
Expand Down
2 changes: 2 additions & 0 deletions homeassistant/helpers/script.py
Expand Up @@ -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
Expand All @@ -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
Expand Down
19 changes: 19 additions & 0 deletions tests/helpers/test_script.py
Expand Up @@ -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

0 comments on commit 467cb18

Please sign in to comment.