Warn for unneeded use of async_update_ha_state (#91372)

pull/91381/head
Franck Nijhof 2023-04-13 19:49:56 +02:00 committed by GitHub
parent f2997ce4cc
commit 22a1a6846d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 35 additions and 0 deletions

View File

@ -249,6 +249,10 @@ class Entity(ABC):
# If we reported this entity is updated while disabled
_disabled_reported = False
# If we reported this entity is using async_update_ha_state, while
# it should be using async_write_ha_state.
_async_update_ha_state_reported = False
# Protect for multiple updates
_update_staged = False
@ -552,6 +556,20 @@ class Entity(ABC):
_LOGGER.exception("Update for %s fails", self.entity_id)
return
if not self._async_update_ha_state_reported:
report_issue = self._suggest_report_issue()
_LOGGER.warning(
(
"Entity %s (%s) is using self.async_update_ha_state(), without"
" enabling force_update. Instead it should use"
" self.async_write_ha_state(), please %s"
),
self.entity_id,
type(self),
report_issue,
)
self._async_update_ha_state_reported = True
self._async_write_ha_state()
@callback

View File

@ -986,3 +986,20 @@ async def test_repr_using_stringify_state() -> None:
entity = MyEntity(entity_id="test.test", available=False)
assert str(entity) == "<entity test.test=unavailable>"
async def test_warn_using_async_update_ha_state(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test we warn once when using async_update_ha_state without force_update."""
ent = entity.Entity()
ent.hass = hass
ent.entity_id = "hello.world"
caplog.clear()
await ent.async_update_ha_state()
assert "is using self.async_update_ha_state()" in caplog.text
caplog.clear()
await ent.async_update_ha_state()
assert "is using self.async_update_ha_state()" not in caplog.text