Raise error if sensor has translated and hardcoded unit (#131657)
parent
3485ce9c71
commit
e4e9d76b45
|
@ -547,6 +547,12 @@ class SensorEntity(Entity, cached_properties=CACHED_PROPERTIES_WITH_ATTR_):
|
|||
unit_of_measurement
|
||||
:= self.platform.default_language_platform_translations.get(translation_key)
|
||||
):
|
||||
if native_unit_of_measurement is not None:
|
||||
raise ValueError(
|
||||
f"Sensor {type(self)} from integration '{self.platform.platform_name}' "
|
||||
f"has a translation key for unit_of_measurement '{unit_of_measurement}', "
|
||||
f"but also has a native_unit_of_measurement '{native_unit_of_measurement}'"
|
||||
)
|
||||
return unit_of_measurement
|
||||
|
||||
# Lowest priority: Native unit
|
||||
|
|
|
@ -504,7 +504,6 @@ async def test_translated_unit(
|
|||
entity0.entity_description = SensorEntityDescription(
|
||||
"test",
|
||||
translation_key="test_translation_key",
|
||||
native_unit_of_measurement="ignored_unit",
|
||||
)
|
||||
setup_test_component_platform(hass, sensor.DOMAIN, [entity0])
|
||||
|
||||
|
@ -518,6 +517,37 @@ async def test_translated_unit(
|
|||
assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == "Tests"
|
||||
|
||||
|
||||
async def test_translated_unit_with_native_unit_raises(
|
||||
hass: HomeAssistant,
|
||||
) -> None:
|
||||
"""Test that translated unit."""
|
||||
|
||||
with patch(
|
||||
"homeassistant.helpers.service.translation.async_get_translations",
|
||||
return_value={
|
||||
"component.test.entity.sensor.test_translation_key.unit_of_measurement": "Tests"
|
||||
},
|
||||
):
|
||||
entity0 = MockSensor(
|
||||
name="Test",
|
||||
native_value="123",
|
||||
unique_id="very_unique",
|
||||
)
|
||||
entity0.entity_description = SensorEntityDescription(
|
||||
"test",
|
||||
translation_key="test_translation_key",
|
||||
native_unit_of_measurement="bad_unit",
|
||||
)
|
||||
setup_test_component_platform(hass, sensor.DOMAIN, [entity0])
|
||||
|
||||
assert await async_setup_component(
|
||||
hass, "sensor", {"sensor": {"platform": "test"}}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
# Setup fails so entity_id is None
|
||||
assert entity0.entity_id is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
(
|
||||
"device_class",
|
||||
|
|
Loading…
Reference in New Issue