diff --git a/homeassistant/components/sensor/entity.py b/homeassistant/components/sensor/entity.py index 4e34ae8e62bb..b301e6d1ae75 100644 --- a/homeassistant/components/sensor/entity.py +++ b/homeassistant/components/sensor/entity.py @@ -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)) diff --git a/tests/components/sensor/test_init.py b/tests/components/sensor/test_init.py index f3db769372c5..2d3029fec0ac 100644 --- a/tests/components/sensor/test_init.py +++ b/tests/components/sensor/test_init.py @@ -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",