From 865190f0b084ae4b3ee8e5223e1fd080ce173f1b Mon Sep 17 00:00:00 2001 From: Richard Kroegel <42204099+rikroe@users.noreply.github.com> Date: Wed, 10 Jul 2024 17:45:07 +0200 Subject: [PATCH] Get suggested_unit_of_measurement via unit converter's UNIT_CLASS (#119196) Co-authored-by: Richard <rikroe@users.noreply.github.com> Co-authored-by: Erik Montnemery <erik@montnemery.com> --- homeassistant/components/sensor/__init__.py | 11 ++++++++++- tests/components/sensor/test_init.py | 16 +++++++++++++++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/sensor/__init__.py b/homeassistant/components/sensor/__init__.py index 63b853f971e..e7f4b00fd77 100644 --- a/homeassistant/components/sensor/__init__.py +++ b/homeassistant/components/sensor/__init__.py @@ -394,11 +394,20 @@ class SensorEntity(Entity, cached_properties=CACHED_PROPERTIES_WITH_ATTR_): suggested_unit_of_measurement = self.suggested_unit_of_measurement if suggested_unit_of_measurement is None: - # Fallback to suggested by the unit conversion rules + # Fallback to unit suggested by the unit conversion rules from device class suggested_unit_of_measurement = self.hass.config.units.get_converted_unit( self.device_class, self.native_unit_of_measurement ) + if suggested_unit_of_measurement is None and ( + unit_converter := UNIT_CONVERTERS.get(self.device_class) + ): + # If the device class is not known by the unit system but has a unit converter, + # fall back to the unit suggested by the unit converter's unit class. + suggested_unit_of_measurement = self.hass.config.units.get_converted_unit( + unit_converter.UNIT_CLASS, self.native_unit_of_measurement + ) + if suggested_unit_of_measurement is None: return UNDEFINED diff --git a/tests/components/sensor/test_init.py b/tests/components/sensor/test_init.py index 034360c6cd2..2504ea80d84 100644 --- a/tests/components/sensor/test_init.py +++ b/tests/components/sensor/test_init.py @@ -942,7 +942,21 @@ async def test_custom_unit_change( "1000000", "1093613", SensorDeviceClass.DISTANCE, - ) + ), + # Volume Storage (subclass of Volume) + ( + US_CUSTOMARY_SYSTEM, + UnitOfVolume.LITERS, + UnitOfVolume.GALLONS, + UnitOfVolume.GALLONS, + UnitOfVolume.FLUID_OUNCES, + 1000, + "1000", + "264", + "264", + "33814", + SensorDeviceClass.VOLUME_STORAGE, + ), ], ) async def test_unit_conversion_priority( -- GitLab