mirror of
https://github.com/home-assistant/core.git
synced 2025-07-22 20:57:21 +00:00
Check if the unit of measurement is valid before creating the entity (#139932)
This commit is contained in:
parent
4ff2309a90
commit
99e1a7a676
@ -11,6 +11,7 @@ import voluptuous as vol
|
|||||||
from homeassistant.components import sensor
|
from homeassistant.components import sensor
|
||||||
from homeassistant.components.sensor import (
|
from homeassistant.components.sensor import (
|
||||||
CONF_STATE_CLASS,
|
CONF_STATE_CLASS,
|
||||||
|
DEVICE_CLASS_UNITS,
|
||||||
DEVICE_CLASSES_SCHEMA,
|
DEVICE_CLASSES_SCHEMA,
|
||||||
ENTITY_ID_FORMAT,
|
ENTITY_ID_FORMAT,
|
||||||
STATE_CLASSES_SCHEMA,
|
STATE_CLASSES_SCHEMA,
|
||||||
@ -107,6 +108,20 @@ def validate_sensor_state_and_device_class_config(config: ConfigType) -> ConfigT
|
|||||||
f"got `{CONF_DEVICE_CLASS}` '{device_class}'"
|
f"got `{CONF_DEVICE_CLASS}` '{device_class}'"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if (device_class := config.get(CONF_DEVICE_CLASS)) is None or (
|
||||||
|
unit_of_measurement := config.get(CONF_UNIT_OF_MEASUREMENT)
|
||||||
|
) is None:
|
||||||
|
return config
|
||||||
|
|
||||||
|
if (
|
||||||
|
device_class in DEVICE_CLASS_UNITS
|
||||||
|
and unit_of_measurement not in DEVICE_CLASS_UNITS[device_class]
|
||||||
|
):
|
||||||
|
raise vol.Invalid(
|
||||||
|
f"The unit of measurement `{unit_of_measurement}` is not valid "
|
||||||
|
f"together with device class `{device_class}`"
|
||||||
|
)
|
||||||
|
|
||||||
return config
|
return config
|
||||||
|
|
||||||
|
|
||||||
|
@ -870,6 +870,32 @@ async def test_invalid_device_class(
|
|||||||
assert "expected SensorDeviceClass or one of" in caplog.text
|
assert "expected SensorDeviceClass or one of" in caplog.text
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"hass_config",
|
||||||
|
[
|
||||||
|
{
|
||||||
|
mqtt.DOMAIN: {
|
||||||
|
sensor.DOMAIN: {
|
||||||
|
"name": "test",
|
||||||
|
"state_topic": "test-topic",
|
||||||
|
"device_class": "energy",
|
||||||
|
"unit_of_measurement": "ppm",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
)
|
||||||
|
async def test_invalid_unit_of_measurement(
|
||||||
|
mqtt_mock_entry: MqttMockHAClientGenerator, caplog: pytest.LogCaptureFixture
|
||||||
|
) -> None:
|
||||||
|
"""Test device_class with invalid unit of measurement."""
|
||||||
|
assert await mqtt_mock_entry()
|
||||||
|
assert (
|
||||||
|
"The unit of measurement `ppm` is not valid together with device class `energy`"
|
||||||
|
in caplog.text
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
"hass_config",
|
"hass_config",
|
||||||
[
|
[
|
||||||
|
Loading…
x
Reference in New Issue
Block a user