Allow is_state_attr to check attributes for None (#132879)

This commit is contained in:
Petro31 2025-01-17 02:41:10 -05:00 committed by GitHub
parent f3683f0b5e
commit 566f514a75
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 23 additions and 3 deletions

View File

@ -1879,8 +1879,12 @@ def is_state(hass: HomeAssistant, entity_id: str, state: str | list[str]) -> boo
def is_state_attr(hass: HomeAssistant, entity_id: str, name: str, value: Any) -> bool:
"""Test if a state's attribute is a specific value."""
attr = state_attr(hass, entity_id, name)
return attr is not None and attr == value
if (state_obj := _get_state(hass, entity_id)) is not None:
attr = state_obj.attributes.get(name, _SENTINEL)
if attr is _SENTINEL:
return False
return bool(attr == value)
return False
def state_attr(hass: HomeAssistant, entity_id: str, name: str) -> Any:

View File

@ -1970,7 +1970,7 @@ def test_is_state(hass: HomeAssistant) -> None:
def test_is_state_attr(hass: HomeAssistant) -> None:
"""Test is_state_attr method."""
hass.states.async_set("test.object", "available", {"mode": "on"})
hass.states.async_set("test.object", "available", {"mode": "on", "exists": None})
tpl = template.Template(
"""
{% if is_state_attr("test.object", "mode", "on") %}yes{% else %}no{% endif %}
@ -2003,6 +2003,22 @@ def test_is_state_attr(hass: HomeAssistant) -> None:
)
assert tpl.async_render() == "test.object"
tpl = template.Template(
"""
{% if is_state_attr("test.object", "exists", None) %}yes{% else %}no{% endif %}
""",
hass,
)
assert tpl.async_render() == "yes"
tpl = template.Template(
"""
{% if is_state_attr("test.object", "noexist", None) %}yes{% else %}no{% endif %}
""",
hass,
)
assert tpl.async_render() == "no"
def test_state_attr(hass: HomeAssistant) -> None:
"""Test state_attr method."""