Fix energy_distance sensor failing on 0 between inverse units (#187657)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Raman Gupta
2026-10-20 23:23:49 -04:00
committed by GitHub
co-authored by Claude Opus 5.5
parent b330c60105
commit 8baa3ec807
2 changed files with 56 additions and 2 deletions
+2 -2
View File
@@ -682,8 +682,8 @@ class SensorEntity(Entity, cached_properties=CACHED_PROPERTIES_WITH_ATTR_):
if native_unit_of_measurement != unit_of_measurement and (
converter := UNIT_CONVERTERS.get(device_class)
):
# Unit conversion needed
value = converter.converter_factory(
# Unit conversion needed, 0 between inverse units converts to None
value = converter.converter_factory_allow_none(
native_unit_of_measurement, unit_of_measurement
)(float(numerical_value))
+54
View File
@@ -979,6 +979,60 @@ async def test_custom_unit(
assert entry.options["sensor"]["suggested_display_precision"] == suggested_precision
@pytest.mark.parametrize(
("native_unit", "custom_unit", "expected_state"),
[
pytest.param(
UnitOfEnergyDistance.KM_PER_KILO_WATT_HOUR,
UnitOfEnergyDistance.KILO_WATT_HOUR_PER_100_KM,
STATE_UNKNOWN,
id="km_per_kwh_to_kwh_per_100km",
),
pytest.param(
UnitOfEnergyDistance.KILO_WATT_HOUR_PER_100_KM,
UnitOfEnergyDistance.MILES_PER_KILO_WATT_HOUR,
STATE_UNKNOWN,
id="kwh_per_100km_to_mi_per_kwh",
),
pytest.param(
UnitOfEnergyDistance.KILO_WATT_HOUR_PER_100_KM,
UnitOfEnergyDistance.WATT_HOUR_PER_KM,
"0.0",
id="kwh_per_100km_to_wh_per_km",
),
],
)
async def test_custom_unit_zero_between_inverse_units(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
native_unit: str,
custom_unit: str,
expected_state: str,
) -> None:
"""Test a zero value converted between inverse units gives an unknown state."""
entry = entity_registry.async_get_or_create("sensor", "test", "very_unique")
entity_registry.async_update_entity_options(
entry.entity_id, "sensor", {"unit_of_measurement": custom_unit}
)
await hass.async_block_till_done()
entity0 = MockSensor(
name="Test",
native_value="0",
native_unit_of_measurement=native_unit,
device_class=SensorDeviceClass.ENERGY_DISTANCE,
unique_id="very_unique",
)
setup_test_component_platform(hass, sensor.DOMAIN, [entity0])
assert await async_setup_component(hass, DOMAIN, {"sensor": {"platform": "test"}})
await hass.async_block_till_done()
state = hass.states.get(entity0.entity_id)
assert state.state == expected_state
assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == custom_unit
@pytest.mark.parametrize(
(
"native_unit",