Ensure it's safe to call Entity.__repr__ on non added entity (#106032)

This commit is contained in:
Erik Montnemery 2023-12-31 18:54:34 +01:00 committed by Franck Nijhof
parent c54af00ce9
commit f9150b78b3
No known key found for this signature in database
GPG key ID: D62583BA8AB11CA3
3 changed files with 19 additions and 14 deletions

View file

@ -734,17 +734,6 @@ class SensorEntity(Entity, cached_properties=CACHED_PROPERTIES_WITH_ATTR_):
return value
def __repr__(self) -> str:
"""Return the representation.
Entity.__repr__ includes the state in the generated string, this fails if we're
called before self.hass is set.
"""
if not self.hass:
return f"<Entity {self.name}>"
return super().__repr__()
def _suggested_precision_or_none(self) -> int | None:
"""Return suggested display precision, or None if not set."""
assert self.registry_entry

View file

@ -1476,7 +1476,12 @@ class Entity(
self.async_on_remove(self._async_unsubscribe_device_updates)
def __repr__(self) -> str:
"""Return the representation."""
"""Return the representation.
If the entity is not added to a platform it's not safe to call _stringify_state.
"""
if self._platform_state != EntityPlatformState.ADDED:
return f"<entity {self.entity_id}={STATE_UNKNOWN}>"
return f"<entity {self.entity_id}={self._stringify_state(self.available)}>"
async def async_request_call(self, coro: Coroutine[Any, Any, _T]) -> _T:

View file

@ -1392,8 +1392,8 @@ async def test_translation_key(hass: HomeAssistant) -> None:
assert mock_entity2.translation_key == "from_entity_description"
async def test_repr_using_stringify_state() -> None:
"""Test that repr uses stringify state."""
async def test_repr(hass) -> None:
"""Test Entity.__repr__."""
class MyEntity(MockEntity):
"""Mock entity."""
@ -1403,9 +1403,20 @@ async def test_repr_using_stringify_state() -> None:
"""Return the state."""
raise ValueError("Boom")
platform = MockEntityPlatform(hass, domain="hello")
my_entity = MyEntity(entity_id="test.test", available=False)
# Not yet added
assert str(my_entity) == "<entity test.test=unknown>"
# Added
await platform.async_add_entities([my_entity])
assert str(my_entity) == "<entity test.test=unavailable>"
# Removed
await platform.async_remove_entity(my_entity.entity_id)
assert str(my_entity) == "<entity test.test=unknown>"
async def test_warn_using_async_update_ha_state(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture