Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion homeassistant/util/unit_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,11 @@ def converter_factory_allow_none(
return lambda value: value
from_ratio, to_ratio = cls._get_from_to_ratio(from_unit, to_unit)
if cls._are_unit_inverses(from_unit, to_unit):
return lambda val: None if val is None else to_ratio / (val / from_ratio)
return (
lambda val: None
if val is None or val == 0
else to_ratio / (val / from_ratio)
)
return lambda val: None if val is None else (val / from_ratio) * to_ratio

@classmethod
Expand Down
52 changes: 52 additions & 0 deletions tests/util/test_unit_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -1264,6 +1264,58 @@ def test_unit_conversion_factory_allow_none_with_none() -> None:
)(None)
is None
)
assert (
EnergyDistanceConverter.converter_factory_allow_none(
UnitOfEnergyDistance.MILES_PER_KILO_WATT_HOUR,
UnitOfEnergyDistance.KILO_WATT_HOUR_PER_100_KM,
)(0)
is None
)
assert (
EnergyDistanceConverter.converter_factory_allow_none(
UnitOfEnergyDistance.KILO_WATT_HOUR_PER_100_KM,
UnitOfEnergyDistance.WATT_HOUR_PER_KM,
)(0)
== 0
)
assert (
EnergyDistanceConverter.converter_factory_allow_none(
UnitOfEnergyDistance.KM_PER_KILO_WATT_HOUR,
UnitOfEnergyDistance.MILES_PER_KILO_WATT_HOUR,
)(0.0)
== 0.0
)
assert (
EnergyDistanceConverter.converter_factory_allow_none(
UnitOfEnergyDistance.MILES_PER_KILO_WATT_HOUR,
UnitOfEnergyDistance.KM_PER_KILO_WATT_HOUR,
)(0)
== 0.0
)


def test_unit_conversion_factory_allow_none_with_zero_for_inverse_units() -> None:
"""Test converter_factory_allow_none returns None for zero with inverse units."""
# Test EnergyDistanceConverter with inverse units (kWh/100km <-> km/kWh)
assert (
EnergyDistanceConverter.converter_factory_allow_none(
UnitOfEnergyDistance.KILO_WATT_HOUR_PER_100_KM,
UnitOfEnergyDistance.KM_PER_KILO_WATT_HOUR,
)(0)
is None
)
assert (
EnergyDistanceConverter.converter_factory_allow_none(
UnitOfEnergyDistance.KM_PER_KILO_WATT_HOUR,
UnitOfEnergyDistance.KILO_WATT_HOUR_PER_100_KM,
)(0)
is None
)
# Test with non-zero value to ensure normal conversion still works
assert EnergyDistanceConverter.converter_factory_allow_none(
UnitOfEnergyDistance.KILO_WATT_HOUR_PER_100_KM,
UnitOfEnergyDistance.KM_PER_KILO_WATT_HOUR,
)(25) == pytest.approx(4)


@pytest.mark.parametrize(
Expand Down
Loading