Raise on incorrect suggested unit for sensor (#120180)

This commit is contained in:
G Johansson 2024-06-22 22:05:45 +02:00 committed by GitHub
parent 08fae5d419
commit b59e7ede9a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 8 additions and 27 deletions

View File

@ -383,15 +383,9 @@ class SensorEntity(Entity, cached_properties=CACHED_PROPERTIES_WITH_ATTR_):
): ):
if not self._invalid_suggested_unit_of_measurement_reported: if not self._invalid_suggested_unit_of_measurement_reported:
self._invalid_suggested_unit_of_measurement_reported = True self._invalid_suggested_unit_of_measurement_reported = True
report_issue = self._suggest_report_issue() raise ValueError(
# This should raise in Home Assistant Core 2024.5 f"Entity {type(self)} suggest an incorrect "
_LOGGER.warning( f"unit of measurement: {suggested_unit_of_measurement}."
(
"%s sets an invalid suggested_unit_of_measurement. Please %s. "
"This warning will become an error in Home Assistant Core 2024.5"
),
type(self),
report_issue,
) )
return False return False

View File

@ -4,7 +4,6 @@ from __future__ import annotations
from datetime import UTC, date, datetime from datetime import UTC, date, datetime
from decimal import Decimal from decimal import Decimal
import logging
from types import ModuleType from types import ModuleType
from typing import Any from typing import Any
@ -2634,25 +2633,13 @@ async def test_suggested_unit_guard_invalid_unit(
assert await async_setup_component(hass, "sensor", {"sensor": {"platform": "test"}}) assert await async_setup_component(hass, "sensor", {"sensor": {"platform": "test"}})
await hass.async_block_till_done() await hass.async_block_till_done()
# Unit of measurement should be native one assert not hass.states.get("sensor.invalid")
state = hass.states.get(entity.entity_id) assert not entity_registry.async_get("sensor.invalid")
assert int(state.state) == state_value
assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == native_unit
# Assert the suggested unit is ignored and not stored in the entity registry
entry = entity_registry.async_get(entity.entity_id)
assert entry.unit_of_measurement == native_unit
assert entry.options == {}
assert ( assert (
"homeassistant.components.sensor", "Entity <class 'tests.components.sensor.common.MockSensor'> suggest an incorrect unit of measurement: invalid_unit"
logging.WARNING, in caplog.text
( )
"<class 'tests.components.sensor.common.MockSensor'> sets an"
" invalid suggested_unit_of_measurement. Please create a bug report at "
"https://github.com/home-assistant/core/issues?q=is%3Aopen+is%3Aissue+label%3A%22integration%3A+test%22."
" This warning will become an error in Home Assistant Core 2024.5"
),
) in caplog.record_tuples
@pytest.mark.parametrize( @pytest.mark.parametrize(