From 26863284b6245e9552ac9a7839cd279cc04ad393 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Thu, 21 Apr 2016 21:42:20 -0400 Subject: [PATCH] Script helper: support variables --- homeassistant/helpers/script.py | 10 ++++---- tests/helpers/test_script.py | 44 +++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 5 deletions(-) diff --git a/homeassistant/helpers/script.py b/homeassistant/helpers/script.py index e4cf2f6756d..0025ddd61df 100644 --- a/homeassistant/helpers/script.py +++ b/homeassistant/helpers/script.py @@ -47,7 +47,7 @@ class Script(): """Return true if script is on.""" return self._cur != -1 - def run(self): + def run(self, variables=None): """Run script.""" with self._lock: if self._cur == -1: @@ -66,7 +66,7 @@ class Script(): def script_delay(now): """Called after delay is done.""" self._delay_listener = None - self.run() + self.run(variables) self._delay_listener = track_point_in_utc_time( self.hass, script_delay, @@ -77,7 +77,7 @@ class Script(): return elif service.validate_service_call(action) is None: - self._call_service(action) + self._call_service(action, variables) elif CONF_EVENT in action: self._fire_event(action) @@ -98,11 +98,11 @@ class Script(): if self._change_listener: self._change_listener() - def _call_service(self, action): + def _call_service(self, action, variables): """Call the service specified in the action.""" self.last_action = action.get(CONF_ALIAS, 'call service') self._log("Executing step %s", self.last_action) - service.call_from_config(self.hass, action, True) + service.call_from_config(self.hass, action, True, variables) def _fire_event(self, action): """Fire an event.""" diff --git a/tests/helpers/test_script.py b/tests/helpers/test_script.py index 90e438047bb..492b62906df 100644 --- a/tests/helpers/test_script.py +++ b/tests/helpers/test_script.py @@ -173,3 +173,47 @@ class TestScriptHelper(unittest.TestCase): assert not script_obj.is_running assert len(events) == 0 + + def test_passing_variables_to_script(self): + """Test if we can pass variables to script.""" + calls = [] + + def record_call(service): + """Add recorded event to set.""" + calls.append(service) + + self.hass.services.register('test', 'script', record_call) + + script_obj = script.Script(self.hass, [ + { + 'service': 'test.script', + 'data_template': { + 'hello': '{{ greeting }}', + }, + }, + {'delay': {'seconds': 5}}, + { + 'service': 'test.script', + 'data_template': { + 'hello': '{{ greeting2 }}', + }, + }]) + + script_obj.run({ + 'greeting': 'world', + 'greeting2': 'universe', + }) + + self.hass.pool.block_till_done() + + assert script_obj.is_running + assert len(calls) == 1 + assert calls[-1].data['hello'] == 'world' + + future = dt_util.utcnow() + timedelta(seconds=5) + fire_time_changed(self.hass, future) + self.hass.pool.block_till_done() + + assert not script_obj.is_running + assert len(calls) == 2 + assert calls[-1].data['hello'] == 'universe'