Add unique ID support to Trend integration YAML configuration (#147346)

This commit is contained in:
Franck Nijhof 2025-06-23 14:44:58 +02:00 committed by GitHub
parent 2e155831e6
commit 87ecf552dc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 41 additions and 0 deletions

View File

@ -27,6 +27,7 @@ from homeassistant.const import (
CONF_ENTITY_ID,
CONF_FRIENDLY_NAME,
CONF_SENSORS,
CONF_UNIQUE_ID,
STATE_ON,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
@ -89,6 +90,7 @@ SENSOR_SCHEMA = vol.All(
vol.Optional(CONF_MIN_GRADIENT, default=0.0): vol.Coerce(float),
vol.Optional(CONF_SAMPLE_DURATION, default=0): cv.positive_int,
vol.Optional(CONF_MIN_SAMPLES, default=2): cv.positive_int,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
),
_validate_min_max,
@ -121,6 +123,7 @@ async def async_setup_platform(
min_samples=sensor_config[CONF_MIN_SAMPLES],
max_samples=sensor_config[CONF_MAX_SAMPLES],
device_class=sensor_config.get(CONF_DEVICE_CLASS),
unique_id=sensor_config.get(CONF_UNIQUE_ID),
sensor_entity_id=generate_entity_id(
ENTITY_ID_FORMAT, sensor_name, hass=hass
),

View File

@ -48,6 +48,7 @@ async def _setup_legacy_component(hass: HomeAssistant, params: dict[str, Any]) -
)
async def test_basic_trend_setup_from_yaml(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
states: list[str],
inverted: bool,
expected_state: str,
@ -72,6 +73,43 @@ async def test_basic_trend_setup_from_yaml(
assert (sensor_state := hass.states.get("binary_sensor.test_trend_sensor"))
assert sensor_state.state == expected_state
# Verify that entity without unique_id in YAML is not in the registry
entity_entry = entity_registry.async_get("binary_sensor.test_trend_sensor")
assert entity_entry is None
async def test_trend_setup_from_yaml_with_unique_id(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
) -> None:
"""Test trend setup from YAML with unique_id."""
await _setup_legacy_component(
hass,
{
"friendly_name": "Test state with ID",
"entity_id": "sensor.cpu_temp",
"unique_id": "my_unique_trend_sensor",
"max_samples": 2.0,
"min_gradient": 0.0,
"sample_duration": 0.0,
},
)
# Set some states to ensure the sensor works
hass.states.async_set("sensor.cpu_temp", "1")
await hass.async_block_till_done()
hass.states.async_set("sensor.cpu_temp", "2")
await hass.async_block_till_done()
# Check that the sensor exists and has the correct state
assert (sensor_state := hass.states.get("binary_sensor.test_trend_sensor"))
assert sensor_state.state == STATE_ON
# Check that the entity is registered with the correct unique_id
entity_entry = entity_registry.async_get("binary_sensor.test_trend_sensor")
assert entity_entry is not None
assert entity_entry.unique_id == "my_unique_trend_sensor"
@pytest.mark.parametrize(
("states", "inverted", "expected_state"),