Skip to content

Commit 4c99fe9

Browse files
authored
Ignore MQTT sensor unit of measurement if it is an empty string (home-assistant#149006)
1 parent 353b573 commit 4c99fe9

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

homeassistant/components/mqtt/sensor.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,12 @@ def validate_sensor_state_and_device_class_config(config: ConfigType) -> ConfigT
9898
f"together with state class `{state_class}`"
9999
)
100100

101+
unit_of_measurement: str | None
102+
if (
103+
unit_of_measurement := config.get(CONF_UNIT_OF_MEASUREMENT)
104+
) is not None and not unit_of_measurement.strip():
105+
config.pop(CONF_UNIT_OF_MEASUREMENT)
106+
101107
# Only allow `options` to be set for `enum` sensors
102108
# to limit the possible sensor values
103109
if (options := config.get(CONF_OPTIONS)) is not None:

tests/components/mqtt/test_sensor.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -924,6 +924,30 @@ async def test_invalid_unit_of_measurement(
924924
"device_class": None,
925925
"unit_of_measurement": None,
926926
},
927+
{
928+
"name": "Test 4",
929+
"state_topic": "test-topic",
930+
"device_class": "ph",
931+
"unit_of_measurement": "",
932+
},
933+
{
934+
"name": "Test 5",
935+
"state_topic": "test-topic",
936+
"device_class": "ph",
937+
"unit_of_measurement": " ",
938+
},
939+
{
940+
"name": "Test 6",
941+
"state_topic": "test-topic",
942+
"device_class": None,
943+
"unit_of_measurement": "",
944+
},
945+
{
946+
"name": "Test 7",
947+
"state_topic": "test-topic",
948+
"device_class": None,
949+
"unit_of_measurement": " ",
950+
},
927951
]
928952
}
929953
}
@@ -936,10 +960,25 @@ async def test_valid_device_class_and_uom(
936960
await mqtt_mock_entry()
937961

938962
state = hass.states.get("sensor.test_1")
963+
assert state is not None
939964
assert state.attributes["device_class"] == "temperature"
940965
state = hass.states.get("sensor.test_2")
966+
assert state is not None
941967
assert "device_class" not in state.attributes
942968
state = hass.states.get("sensor.test_3")
969+
assert state is not None
970+
assert "device_class" not in state.attributes
971+
state = hass.states.get("sensor.test_4")
972+
assert state is not None
973+
assert state.attributes["device_class"] == "ph"
974+
state = hass.states.get("sensor.test_5")
975+
assert state is not None
976+
assert state.attributes["device_class"] == "ph"
977+
state = hass.states.get("sensor.test_6")
978+
assert state is not None
979+
assert "device_class" not in state.attributes
980+
state = hass.states.get("sensor.test_7")
981+
assert state is not None
943982
assert "device_class" not in state.attributes
944983

945984

0 commit comments

Comments
 (0)