Fix missing context when running script from template entity (#113523)

Co-authored-by: J. Nick Koston <nick@koston.org>
This commit is contained in:
Erik Montnemery 2024-03-16 23:37:24 +01:00 committed by GitHub
parent 0725ff34b1
commit d0352ed91d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 14 additions and 2 deletions

View File

@ -4,7 +4,7 @@ from collections.abc import Callable
import logging
from homeassistant.const import EVENT_HOMEASSISTANT_START
from homeassistant.core import CoreState, callback
from homeassistant.core import Context, CoreState, callback
from homeassistant.helpers import discovery, trigger as trigger_helper
from homeassistant.helpers.script import Script
from homeassistant.helpers.typing import ConfigType
@ -91,7 +91,10 @@ class TriggerUpdateCoordinator(DataUpdateCoordinator):
)
async def _handle_triggered_with_script(self, run_variables, context=None):
if script_result := await self._script.async_run(run_variables, context):
# Create a context referring to the trigger context.
trigger_context_id = None if context is None else context.id
script_context = Context(parent_id=trigger_context_id)
if script_result := await self._script.async_run(run_variables, script_context):
run_variables = script_result.variables
self._handle_triggered(run_variables, context)

View File

@ -30,6 +30,7 @@ import homeassistant.util.dt as dt_util
from tests.common import (
MockConfigEntry,
assert_setup_component,
async_capture_events,
async_fire_time_changed,
mock_restore_cache_with_extra_data,
)
@ -1849,6 +1850,7 @@ async def test_trigger_entity_restore_state(
"my_variable": "{{ trigger.event.data.beer + 1 }}"
},
},
{"event": "test_event2", "event_data": {"hello": "world"}},
],
"sensor": [
{
@ -1865,6 +1867,10 @@ async def test_trigger_action(
hass: HomeAssistant, start_ha, entity_registry: er.EntityRegistry
) -> None:
"""Test trigger entity with an action works."""
event = "test_event2"
context = Context()
events = async_capture_events(hass, event)
state = hass.states.get("sensor.hello_name")
assert state is not None
assert state.state == STATE_UNKNOWN
@ -1876,3 +1882,6 @@ async def test_trigger_action(
state = hass.states.get("sensor.hello_name")
assert state.state == "3"
assert state.context is context
assert len(events) == 1
assert events[0].context.parent_id == context.id