Allow returning a script variable from a script (#95346)

* Allow returning a script variable from a script

* Don't allow returning a template result

* Raise if response variable is undefined

* Add test

* Update homeassistant/helpers/script.py

Co-authored-by: Paulus Schoutsen <balloob@gmail.com>

* Format code

---------

Co-authored-by: Paulus Schoutsen <balloob@gmail.com>
This commit is contained in:
Erik Montnemery 2023-06-27 17:13:53 +02:00 committed by GitHub
parent e19b29d6ae
commit cb22fb16f8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 100 additions and 19 deletions

View file

@ -25,7 +25,7 @@ from homeassistant.core import (
callback,
split_entity_id,
)
from homeassistant.exceptions import ServiceNotFound
from homeassistant.exceptions import HomeAssistantError, ServiceNotFound
from homeassistant.helpers import entity_registry as er, template
from homeassistant.helpers.event import async_track_state_change
from homeassistant.helpers.script import (
@ -1515,10 +1515,15 @@ async def test_responses(hass: HomeAssistant, response: Any) -> None:
{
"script": {
"test": {
"sequence": {
"stop": "done",
"response": response,
}
"sequence": [
{
"variables": {"test_var": {"response": response}},
},
{
"stop": "done",
"response_variable": "test_var",
},
]
}
}
},
@ -1526,7 +1531,40 @@ async def test_responses(hass: HomeAssistant, response: Any) -> None:
assert await hass.services.async_call(
DOMAIN, "test", {"greeting": "world"}, blocking=True, return_response=True
) == {"value": 5}
) == {"response": response}
# Validate we can also call it without return_response
assert (
await hass.services.async_call(
DOMAIN, "test", {"greeting": "world"}, blocking=True, return_response=False
)
is None
)
async def test_responses_error(hass: HomeAssistant) -> None:
"""Test response variable not set."""
mock_restore_cache(hass, ())
assert await async_setup_component(
hass,
"script",
{
"script": {
"test": {
"sequence": [
{
"stop": "done",
"response_variable": "test_var",
},
]
}
}
},
)
with pytest.raises(HomeAssistantError):
assert await hass.services.async_call(
DOMAIN, "test", {"greeting": "world"}, blocking=True, return_response=True
)
# Validate we can also call it without return_response
assert (
await hass.services.async_call(