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 GitHub
parent 353b573707
commit 4c99fe9ae5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
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}`" 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 # Only allow `options` to be set for `enum` sensors
# to limit the possible sensor values # to limit the possible sensor values
if (options := config.get(CONF_OPTIONS)) is not None: 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, "device_class": None,
"unit_of_measurement": 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() await mqtt_mock_entry()
state = hass.states.get("sensor.test_1") state = hass.states.get("sensor.test_1")
assert state is not None
assert state.attributes["device_class"] == "temperature" assert state.attributes["device_class"] == "temperature"
state = hass.states.get("sensor.test_2") state = hass.states.get("sensor.test_2")
assert state is not None
assert "device_class" not in state.attributes assert "device_class" not in state.attributes
state = hass.states.get("sensor.test_3") 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 assert "device_class" not in state.attributes