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:
self._invalid_suggested_unit_of_measurement_reported = True
report_issue = self._suggest_report_issue()
# This should raise in Home Assistant Core 2024.5
_LOGGER.warning(
(
"%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,
raise ValueError(
f"Entity {type(self)} suggest an incorrect "
f"unit of measurement: {suggested_unit_of_measurement}."
)
return False

View file

@ -4,7 +4,6 @@ from __future__ import annotations
from datetime import UTC, date, datetime
from decimal import Decimal
import logging
from types import ModuleType
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"}})
await hass.async_block_till_done()
# Unit of measurement should be native one
state = hass.states.get(entity.entity_id)
assert int(state.state) == state_value
assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == native_unit
assert not hass.states.get("sensor.invalid")
assert not entity_registry.async_get("sensor.invalid")
# 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 (
"homeassistant.components.sensor",
logging.WARNING,
(
"<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
"Entity <class 'tests.components.sensor.common.MockSensor'> suggest an incorrect unit of measurement: invalid_unit"
in caplog.text
)
@pytest.mark.parametrize(