Fix TemplateError definition (#82570)

This commit is contained in:
epenet 2022-11-23 20:30:32 +01:00 committed by GitHub
parent 6b85d17e7c
commit f91e250e90
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 26 additions and 5 deletions

View File

@ -25,9 +25,12 @@ class NoEntitySpecifiedError(HomeAssistantError):
class TemplateError(HomeAssistantError):
"""Error during template rendering."""
def __init__(self, exception: Exception) -> None:
def __init__(self, exception: Exception | str) -> None:
"""Init the error."""
super().__init__(f"{exception.__class__.__name__}: {exception}")
if isinstance(exception, str):
super().__init__(exception)
else:
super().__init__(f"{exception.__class__.__name__}: {exception}")
@attr.s

View File

@ -918,7 +918,7 @@ def _state_generator(
def _get_state_if_valid(hass: HomeAssistant, entity_id: str) -> TemplateState | None:
state = hass.states.get(entity_id)
if state is None and not valid_entity_id(entity_id):
raise TemplateError(f"Invalid entity ID '{entity_id}'") # type: ignore[arg-type]
raise TemplateError(f"Invalid entity ID '{entity_id}'")
return _get_template_state_from_state(hass, entity_id, state)

View File

@ -194,7 +194,7 @@ async def test_non_allowed_templates(hass, calls, caplog):
)
assert (
"Got error 'TemplateError: str: Use of 'states' is not supported in limited templates' when setting up triggers"
"Got error 'TemplateError: Use of 'states' is not supported in limited templates' when setting up triggers"
in caplog.text
)

View File

@ -1,12 +1,17 @@
"""Test to verify that Home Assistant exceptions work."""
from __future__ import annotations
import pytest
from homeassistant.exceptions import (
ConditionErrorContainer,
ConditionErrorIndex,
ConditionErrorMessage,
TemplateError,
)
def test_conditionerror_format():
def test_conditionerror_format() -> None:
"""Test ConditionError stringifiers."""
error1 = ConditionErrorMessage("test", "A test error")
assert str(error1) == "In 'test' condition: A test error"
@ -43,3 +48,16 @@ In 'box' (item 2 of 2):
== """In 'box':
In 'test' condition: A test error"""
)
@pytest.mark.parametrize(
"arg, expected",
[
("message", "message"),
(Exception("message"), "Exception: message"),
],
)
def test_template_message(arg: str | Exception, expected: str) -> None:
"""Ensure we can create TemplateError."""
template_error = TemplateError(arg)
assert str(template_error) == expected