Validate state in template helper preview (#99455)

* Validate state in template helper preview

* Deduplicate state validation
This commit is contained in:
Erik Montnemery 2023-09-04 14:10:43 +02:00 committed by GitHub
parent 709ce7e0af
commit 7c595ee2da
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 28 additions and 8 deletions

View File

@ -25,6 +25,7 @@ from homeassistant.core import (
HomeAssistant,
State,
callback,
validate_state,
)
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
@ -413,8 +414,8 @@ class TemplateEntity(Entity):
return
for update in updates:
for attr in self._template_attrs[update.template]:
attr.handle_result(
for template_attr in self._template_attrs[update.template]:
template_attr.handle_result(
event, update.template, update.last_result, update.result
)
@ -422,7 +423,13 @@ class TemplateEntity(Entity):
self.async_write_ha_state()
return
self._preview_callback(*self._async_generate_attributes(), None)
try:
state, attrs = self._async_generate_attributes()
validate_state(state)
except Exception as err: # pylint: disable=broad-exception-caught
self._preview_callback(None, None, str(err))
else:
self._preview_callback(state, attrs, None)
@callback
def _async_template_startup(self, *_: Any) -> None:

View File

@ -174,6 +174,16 @@ def valid_entity_id(entity_id: str) -> bool:
return VALID_ENTITY_ID.match(entity_id) is not None
def validate_state(state: str) -> str:
"""Validate a state, raise if it not valid."""
if len(state) > MAX_LENGTH_STATE_STATE:
raise InvalidStateError(
f"Invalid state with length {len(state)}. "
"State max length is 255 characters."
)
return state
def callback(func: _CallableT) -> _CallableT:
"""Annotation to mark method as safe to call from within the event loop."""
setattr(func, "_hass_callback", True)
@ -1255,11 +1265,7 @@ class State:
"Format should be <domain>.<object_id>"
)
if len(state) > MAX_LENGTH_STATE_STATE:
raise InvalidStateError(
f"Invalid state encountered for entity ID: {entity_id}. "
"State max length is 255 characters."
)
validate_state(state)
self.entity_id = entity_id
self.state = state

View File

@ -2465,3 +2465,10 @@ async def test_cancellable_hassjob(hass: HomeAssistant) -> None:
# Cleanup
timer2.cancel()
async def test_validate_state(hass: HomeAssistant) -> None:
"""Test validate_state."""
assert ha.validate_state("test") == "test"
with pytest.raises(InvalidStateError):
ha.validate_state("t" * 256)