Ignore MQTT sensor unit of measurement if it is an empty string (#149006)

This commit is contained in:
Jan Bouwhuis 2025-07-18 18:57:03 +02:00 committed by Franck Nijhof
parent d57c5ffa8f
commit c6bb26be89
No known key found for this signature in database
GPG Key ID: AB33ADACE7101952
2 changed files with 45 additions and 0 deletions

View File

@ -98,6 +98,12 @@ def validate_sensor_state_and_device_class_config(config: ConfigType) -> ConfigT
f"together with state class `{state_class}`"
)
unit_of_measurement: str | None
if (
unit_of_measurement := config.get(CONF_UNIT_OF_MEASUREMENT)
) is not None and not unit_of_measurement.strip():
config.pop(CONF_UNIT_OF_MEASUREMENT)
# Only allow `options` to be set for `enum` sensors
# to limit the possible sensor values
if (options := config.get(CONF_OPTIONS)) is not None:

View File

@ -924,6 +924,30 @@ async def test_invalid_unit_of_measurement(
"device_class": None,
"unit_of_measurement": None,
},
{
"name": "Test 4",
"state_topic": "test-topic",
"device_class": "ph",
"unit_of_measurement": "",
},
{
"name": "Test 5",
"state_topic": "test-topic",
"device_class": "ph",
"unit_of_measurement": " ",
},
{
"name": "Test 6",
"state_topic": "test-topic",
"device_class": None,
"unit_of_measurement": "",
},
{
"name": "Test 7",
"state_topic": "test-topic",
"device_class": None,
"unit_of_measurement": " ",
},
]
}
}
@ -936,10 +960,25 @@ async def test_valid_device_class_and_uom(
await mqtt_mock_entry()
state = hass.states.get("sensor.test_1")
assert state is not None
assert state.attributes["device_class"] == "temperature"
state = hass.states.get("sensor.test_2")
assert state is not None
assert "device_class" not in state.attributes
state = hass.states.get("sensor.test_3")
assert state is not None
assert "device_class" not in state.attributes
state = hass.states.get("sensor.test_4")
assert state is not None
assert state.attributes["device_class"] == "ph"
state = hass.states.get("sensor.test_5")
assert state is not None
assert state.attributes["device_class"] == "ph"
state = hass.states.get("sensor.test_6")
assert state is not None
assert "device_class" not in state.attributes
state = hass.states.get("sensor.test_7")
assert state is not None
assert "device_class" not in state.attributes