From 1e35971e8a79604b9bf20dff321808014d5fc8ca Mon Sep 17 00:00:00 2001 From: G Johansson Date: Mon, 2 Nov 2026 09:05:29 +0100 Subject: [PATCH] Add config flow to compensation helper (#147928) Co-authored-by: Claude Opus 5.5 --- .../components/compensation/__init__.py | 161 +++++++++---- .../components/compensation/config_flow.py | 213 +++++++++++++++++ .../components/compensation/const.py | 12 +- .../components/compensation/manifest.json | 2 + .../components/compensation/sensor.py | 21 ++ .../components/compensation/strings.json | 122 ++++++++++ homeassistant/generated/config_flows.py | 1 + homeassistant/generated/integrations.json | 18 +- tests/components/compensation/conftest.py | 59 +++++ .../compensation/test_config_flow.py | 225 ++++++++++++++++++ tests/components/compensation/test_init.py | 83 +++++++ tests/components/compensation/test_sensor.py | 15 ++ 12 files changed, 874 insertions(+), 58 deletions(-) create mode 100644 homeassistant/components/compensation/config_flow.py create mode 100644 homeassistant/components/compensation/strings.json create mode 100644 tests/components/compensation/conftest.py create mode 100644 tests/components/compensation/test_config_flow.py create mode 100644 tests/components/compensation/test_init.py diff --git a/homeassistant/components/compensation/__init__.py b/homeassistant/components/compensation/__init__.py index 509515e4cd89..8ef9780d42b4 100644 --- a/homeassistant/components/compensation/__init__.py +++ b/homeassistant/components/compensation/__init__.py @@ -12,9 +12,11 @@ from homeassistant.components.sensor import ( DOMAIN as SENSOR_DOMAIN, STATE_CLASSES_SCHEMA as SENSOR_STATE_CLASSES_SCHEMA, ) +from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONF_ATTRIBUTE, CONF_DEVICE_CLASS, + CONF_ENTITY_ID, CONF_MAXIMUM, CONF_MINIMUM, CONF_NAME, @@ -23,22 +25,29 @@ from homeassistant.const import ( CONF_UNIT_OF_MEASUREMENT, ) from homeassistant.core import HomeAssistant +from homeassistant.exceptions import ConfigEntryError from homeassistant.helpers import config_validation as cv +from homeassistant.helpers.device import async_entity_id_to_device_id from homeassistant.helpers.discovery import async_load_platform +from homeassistant.helpers.helper_integration import async_handle_source_entity_changes from homeassistant.helpers.typing import ConfigType from .const import ( + CONF_COMPENSATED_VALUE, CONF_COMPENSATION, CONF_DATAPOINTS, CONF_DEGREE, CONF_LOWER_LIMIT, CONF_POLYNOMIAL, + CONF_POLYNOMIAL_CONFIG, CONF_PRECISION, + CONF_UNCOMPENSATED_VALUE, CONF_UPPER_LIMIT, DATA_COMPENSATION, DEFAULT_DEGREE, DEFAULT_PRECISION, DOMAIN, + PLATFORMS, ) _LOGGER = logging.getLogger(__name__) @@ -87,6 +96,42 @@ CONFIG_SCHEMA = probatio.Schema( ) +async def create_compensation_data( + hass: HomeAssistant, compensation: str, conf: ConfigType +) -> None: + """Create compensation data. + + Raises FloatingPointError if no polynomial can be fitted to the data points. + """ + _LOGGER.debug("Setup %s.%s", DOMAIN, compensation) + + degree = conf[CONF_DEGREE] + + initial_coefficients: list[tuple[float, float]] = conf[CONF_DATAPOINTS] + sorted_coefficients = sorted(initial_coefficients, key=itemgetter(0)) + + # get x values and y values from the x,y point pairs + x_values, y_values = zip(*initial_coefficients, strict=False) + + with np.errstate(all="raise"): + coefficients = np.polyfit(x_values, y_values, degree) + + data = {k: v for k, v in conf.items() if k not in [CONF_DEGREE, CONF_DATAPOINTS]} + data[CONF_POLYNOMIAL] = np.poly1d(coefficients) + + if data[CONF_LOWER_LIMIT]: + data[CONF_MINIMUM] = sorted_coefficients[0] + else: + data[CONF_MINIMUM] = None + + if data[CONF_UPPER_LIMIT]: + data[CONF_MAXIMUM] = sorted_coefficients[-1] + else: + data[CONF_MAXIMUM] = None + + hass.data[DATA_COMPENSATION][compensation] = data + + async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the Compensation sensor.""" hass.data[DATA_COMPENSATION] = {} @@ -97,54 +142,74 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: return True for compensation, conf in config[DOMAIN].items(): - _LOGGER.debug("Setup %s.%s", DOMAIN, compensation) - - degree = conf[CONF_DEGREE] - - initial_coefficients: list[tuple[float, float]] = conf[CONF_DATAPOINTS] - sorted_coefficients = sorted(initial_coefficients, key=itemgetter(0)) - - # get x values and y values from the x,y point pairs - x_values, y_values = zip(*initial_coefficients, strict=False) - - # try to get valid coefficients for a polynomial - coefficients = None - with np.errstate(all="raise"): - try: - coefficients = np.polyfit(x_values, y_values, degree) - except FloatingPointError as error: - _LOGGER.error( - "Setup of %s encountered an error, %s", - compensation, - error, - ) - - if coefficients is not None: - data = { - k: v for k, v in conf.items() if k not in [CONF_DEGREE, CONF_DATAPOINTS] - } - data[CONF_POLYNOMIAL] = np.poly1d(coefficients) - - if data[CONF_LOWER_LIMIT]: - data[CONF_MINIMUM] = sorted_coefficients[0] - else: - data[CONF_MINIMUM] = None - - if data[CONF_UPPER_LIMIT]: - data[CONF_MAXIMUM] = sorted_coefficients[-1] - else: - data[CONF_MAXIMUM] = None - - hass.data[DATA_COMPENSATION][compensation] = data - - hass.async_create_task( - async_load_platform( - hass, - SENSOR_DOMAIN, - DOMAIN, - {CONF_COMPENSATION: compensation}, - config, - ) + try: + await create_compensation_data(hass, compensation, conf) + except FloatingPointError as error: + _LOGGER.error( + "Setup of %s encountered an error, %s", + compensation, + error, ) + continue + + hass.async_create_task( + async_load_platform( + hass, + SENSOR_DOMAIN, + DOMAIN, + {CONF_COMPENSATION: compensation}, + config, + ) + ) return True + + +async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: + """Set up Compensation from a config entry.""" + + def set_source_entity_id_or_uuid(source_entity_id: str) -> None: + hass.config_entries.async_update_entry( + entry, + options={**entry.options, CONF_ENTITY_ID: source_entity_id}, + ) + hass.config_entries.async_schedule_reload(entry.entry_id) + + entry.async_on_unload( + async_handle_source_entity_changes( + hass, + helper_config_entry_id=entry.entry_id, + set_source_entity_id_or_uuid=set_source_entity_id_or_uuid, + source_device_id=async_entity_id_to_device_id( + hass, entry.options[CONF_ENTITY_ID] + ), + source_entity_id_or_uuid=entry.options[CONF_ENTITY_ID], + ) + ) + + config = dict(entry.options) + data_points: list[dict[str, float]] = config[CONF_POLYNOMIAL_CONFIG][ + CONF_DATAPOINTS + ] + new_data_points = [ + [data_point[CONF_UNCOMPENSATED_VALUE], data_point[CONF_COMPENSATED_VALUE]] + for data_point in data_points + ] + config[CONF_DEGREE] = config[CONF_POLYNOMIAL_CONFIG][CONF_DEGREE] + config[CONF_DATAPOINTS] = new_data_points + + try: + await create_compensation_data(hass, entry.entry_id, config) + except FloatingPointError as error: + raise ConfigEntryError( + translation_domain=DOMAIN, + translation_key="setup_error", + translation_placeholders={"title": entry.title, "error": str(error)}, + ) from error + await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) + + +async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: + """Unload Compensation config entry.""" + await hass.config_entries.async_unload_platforms_or_raise(entry, PLATFORMS) + hass.data[DATA_COMPENSATION].pop(entry.entry_id, None) diff --git a/homeassistant/components/compensation/config_flow.py b/homeassistant/components/compensation/config_flow.py new file mode 100644 index 000000000000..0bda6b7feb97 --- /dev/null +++ b/homeassistant/components/compensation/config_flow.py @@ -0,0 +1,213 @@ +"""Config flow for Compensation integration.""" + +from collections.abc import Mapping +from typing import Any, cast, override + +import numpy as np +import probatio + +from homeassistant.components.sensor import CONF_STATE_CLASS +from homeassistant.const import ( + CONF_ATTRIBUTE, + CONF_DEVICE_CLASS, + CONF_ENTITY_ID, + CONF_NAME, + CONF_UNIT_OF_MEASUREMENT, + Platform, +) +from homeassistant.data_entry_flow import SectionConfig, section +from homeassistant.helpers import entity_registry as er +from homeassistant.helpers.schema_config_entry_flow import ( + SchemaCommonFlowHandler, + SchemaConfigFlowHandler, + SchemaFlowError, + SchemaFlowFormStep, +) +from homeassistant.helpers.selector import ( + AttributeSelector, + AttributeSelectorConfig, + BooleanSelector, + DeviceClassSelector, + DeviceClassSelectorConfig, + EntitySelector, + NumberSelector, + NumberSelectorConfig, + NumberSelectorMode, + ObjectSelector, + ObjectSelectorConfig, + ObjectSelectorField, + StateClassSelector, + TextSelector, + UnitOfMeasurementSelector, + UnitOfMeasurementSelectorConfig, +) + +from .const import ( + CONF_COMPENSATED_VALUE, + CONF_DATAPOINTS, + CONF_DEGREE, + CONF_LOWER_LIMIT, + CONF_POLYNOMIAL_CONFIG, + CONF_PRECISION, + CONF_UNCOMPENSATED_VALUE, + CONF_UPPER_LIMIT, + DEFAULT_DEGREE, + DEFAULT_NAME, + DEFAULT_PRECISION, + DOMAIN, +) + + +async def get_options_schema(handler: SchemaCommonFlowHandler) -> probatio.Schema: + """Get options schema.""" + entity_id = handler.options[CONF_ENTITY_ID] + + return probatio.Schema( + { + probatio.Required(CONF_POLYNOMIAL_CONFIG): section( + probatio.Schema( + { + probatio.Optional(CONF_DATAPOINTS): ObjectSelector( + ObjectSelectorConfig( + label_field="uncompensated_value", + description_field="compensated_value", + multiple=True, + translation_key=CONF_DATAPOINTS, + fields={ + CONF_UNCOMPENSATED_VALUE: ObjectSelectorField( + required=True, + selector=NumberSelector( + NumberSelectorConfig( + mode=NumberSelectorMode.BOX + ) + ), + ), + CONF_COMPENSATED_VALUE: ObjectSelectorField( + required=True, + selector=NumberSelector( + NumberSelectorConfig( + mode=NumberSelectorMode.BOX + ) + ), + ), + }, + ) + ), + probatio.Optional( + CONF_DEGREE, default=DEFAULT_DEGREE + ): NumberSelector( + NumberSelectorConfig( + min=1, max=7, step=1, mode=NumberSelectorMode.BOX + ) + ), + }, + ), + SectionConfig(collapsed=False), + ), + probatio.Optional(CONF_ATTRIBUTE): AttributeSelector( + AttributeSelectorConfig(entity_id=entity_id) + ), + probatio.Optional(CONF_UPPER_LIMIT, default=False): BooleanSelector(), + probatio.Optional(CONF_LOWER_LIMIT, default=False): BooleanSelector(), + probatio.Optional( + CONF_PRECISION, default=DEFAULT_PRECISION + ): NumberSelector( + NumberSelectorConfig(min=0, step=1, mode=NumberSelectorMode.BOX) + ), + probatio.Optional(CONF_DEVICE_CLASS): DeviceClassSelector( + DeviceClassSelectorConfig(domain=Platform.SENSOR) + ), + probatio.Optional(CONF_STATE_CLASS): StateClassSelector(), + probatio.Optional(CONF_UNIT_OF_MEASUREMENT): UnitOfMeasurementSelector( + UnitOfMeasurementSelectorConfig( + context={ + "filter_device_class": CONF_DEVICE_CLASS, + "filter_state_class": CONF_STATE_CLASS, + } + ) + ), + } + ) + + +async def validate_options( + handler: SchemaCommonFlowHandler, user_input: dict[str, Any] +) -> dict[str, Any]: + """Validate options selected.""" + + if not user_input[CONF_POLYNOMIAL_CONFIG].get(CONF_DATAPOINTS): + raise SchemaFlowError("not_enough_datapoints") + + user_input[CONF_PRECISION] = int(user_input[CONF_PRECISION]) + user_input[CONF_POLYNOMIAL_CONFIG][CONF_DEGREE] = int( + user_input[CONF_POLYNOMIAL_CONFIG][CONF_DEGREE] + ) + + data_points = user_input[CONF_POLYNOMIAL_CONFIG][CONF_DATAPOINTS] + degree = user_input[CONF_POLYNOMIAL_CONFIG][CONF_DEGREE] + if len(data_points) <= degree: + raise SchemaFlowError("not_enough_datapoints") + + with np.errstate(all="raise"): + try: + np.polyfit( + [data_point[CONF_UNCOMPENSATED_VALUE] for data_point in data_points], + [data_point[CONF_COMPENSATED_VALUE] for data_point in data_points], + degree, + ) + except FloatingPointError as error: + raise SchemaFlowError("invalid_datapoints") from error + + handler.parent_handler._async_abort_entries_match({**handler.options, **user_input}) # noqa: SLF001 + + return user_input + + +async def validate_setup( + handler: SchemaCommonFlowHandler, user_input: dict[str, Any] +) -> dict[str, Any]: + """Validate setup input.""" + # The attribute selector in the options step needs an entity ID, not a UUID + user_input[CONF_ENTITY_ID] = er.async_validate_entity_id( + er.async_get(handler.parent_handler.hass), user_input[CONF_ENTITY_ID] + ) + return user_input + + +DATA_SCHEMA_SETUP = probatio.Schema( + { + probatio.Required(CONF_NAME, default=DEFAULT_NAME): TextSelector(), + probatio.Required(CONF_ENTITY_ID): EntitySelector(), + } +) + +CONFIG_FLOW = { + "user": SchemaFlowFormStep( + schema=DATA_SCHEMA_SETUP, + validate_user_input=validate_setup, + next_step="options", + ), + "options": SchemaFlowFormStep( + schema=get_options_schema, + validate_user_input=validate_options, + ), +} +OPTIONS_FLOW = { + "init": SchemaFlowFormStep( + get_options_schema, + validate_user_input=validate_options, + ), +} + + +class CompensationConfigFlowHandler(SchemaConfigFlowHandler, domain=DOMAIN): + """Handle a config flow for Compensation.""" + + config_flow = CONFIG_FLOW + options_flow = OPTIONS_FLOW + options_flow_reloads = True + + @override + def async_config_entry_title(self, options: Mapping[str, Any]) -> str: + """Return config entry title.""" + return cast(str, options[CONF_NAME]) diff --git a/homeassistant/components/compensation/const.py b/homeassistant/components/compensation/const.py index ce9594697006..dbb40a3ce12e 100644 --- a/homeassistant/components/compensation/const.py +++ b/homeassistant/components/compensation/const.py @@ -1,6 +1,12 @@ """Compensation constants.""" +from typing import Any + +from homeassistant.const import Platform +from homeassistant.util.hass_dict import HassKey + DOMAIN = "compensation" +PLATFORMS = [Platform.SENSOR] SENSOR = "compensation" @@ -11,8 +17,12 @@ CONF_DATAPOINTS = "data_points" CONF_DEGREE = "degree" CONF_PRECISION = "precision" CONF_POLYNOMIAL = "polynomial" +CONF_POLYNOMIAL_CONFIG = "polynomial_config" +CONF_COMPENSATED_VALUE = "compensated_value" +CONF_UNCOMPENSATED_VALUE = "uncompensated_value" -DATA_COMPENSATION = "compensation_data" + +DATA_COMPENSATION: HassKey[dict[str, Any]] = HassKey("compensation_data") DEFAULT_DEGREE = 1 DEFAULT_NAME = "Compensation" diff --git a/homeassistant/components/compensation/manifest.json b/homeassistant/components/compensation/manifest.json index b2873de83995..6b2887251ce4 100644 --- a/homeassistant/components/compensation/manifest.json +++ b/homeassistant/components/compensation/manifest.json @@ -3,7 +3,9 @@ "name": "Compensation", "categories": ["helpers.calculate_value"], "codeowners": ["@Petro31"], + "config_flow": true, "documentation": "https://www.home-assistant.io/integrations/compensation", + "integration_type": "helper", "iot_class": "calculated", "quality_scale": "legacy", "requirements": ["numpy==2.3.2"] diff --git a/homeassistant/components/compensation/sensor.py b/homeassistant/components/compensation/sensor.py index f00e892b9589..ced0fbb856dc 100644 --- a/homeassistant/components/compensation/sensor.py +++ b/homeassistant/components/compensation/sensor.py @@ -11,9 +11,11 @@ from homeassistant.components.sensor import ( SensorEntity, SensorEntityCapabilityAttribute, ) +from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONF_ATTRIBUTE, CONF_DEVICE_CLASS, + CONF_ENTITY_ID, CONF_MAXIMUM, CONF_MINIMUM, CONF_NAME, @@ -32,6 +34,7 @@ from homeassistant.core import ( callback, ) from homeassistant.helpers.entity_platform import ( + AddConfigEntryEntitiesCallback, AddEntitiesCallback, async_create_platform_config_not_supported_issue, ) @@ -87,6 +90,24 @@ async def async_setup_platform( ) +async def async_setup_entry( + hass: HomeAssistant, + entry: ConfigEntry, + async_add_entities: AddConfigEntryEntitiesCallback, +) -> None: + """Set up the Compensation sensor entry.""" + compensation = entry.entry_id + conf: dict[str, Any] = hass.data[DATA_COMPENSATION][compensation] + + source: str = conf[CONF_ENTITY_ID] + attribute: str | None = conf.get(CONF_ATTRIBUTE) + name = entry.title + + async_add_entities( + [CompensationSensor(entry.entry_id, name, source, attribute, conf)] + ) + + class CompensationSensor(SensorEntity): """Representation of a Compensation sensor.""" diff --git a/homeassistant/components/compensation/strings.json b/homeassistant/components/compensation/strings.json new file mode 100644 index 000000000000..48f01a5d70a6 --- /dev/null +++ b/homeassistant/components/compensation/strings.json @@ -0,0 +1,122 @@ +{ + "config": { + "abort": { + "already_configured": "[%key:common::config_flow::abort::already_configured_account%]" + }, + "error": { + "invalid_datapoints": "Unable to calculate a polynomial from the data points. Make sure the uncompensated values are distinct.", + "not_enough_datapoints": "The number of datapoints needs to be more than the configured degree." + }, + "step": { + "options": { + "data": { + "attribute": "Attribute", + "device_class": "Device class", + "lower_limit": "Lower limit", + "precision": "Precision", + "state_class": "State class", + "unit_of_measurement": "Unit of measurement", + "upper_limit": "Upper limit" + }, + "data_description": { + "attribute": "Attribute from the source to monitor/compensate.", + "device_class": "The device class of the compensation sensor. If not set, the device class of the source entity is used.", + "lower_limit": "Enables a lower limit for the sensor. The lower limit is defined by the data point with the lowest uncompensated value.", + "precision": "Defines the precision of the calculated values, through the argument of round().", + "state_class": "The state class of the compensation sensor. If not set, the state class of the source entity is used.", + "unit_of_measurement": "The unit of measurement of the compensation sensor, if any.", + "upper_limit": "Enables an upper limit for the sensor. The upper limit is defined by the data point with the highest uncompensated value." + }, + "description": "Refer to the documentation for further details on how to configure the compensation sensor using these options.", + "sections": { + "polynomial_config": { + "data": { + "data_points": "Data points", + "degree": "Degree" + }, + "data_description": { + "degree": "The degree of the polynomial." + }, + "description": "Configure the polynomial used for compensation.", + "name": "Polynomial configuration" + } + } + }, + "user": { + "data": { + "entity_id": "Source entity", + "name": "[%key:common::config_flow::data::name%]" + }, + "data_description": { + "entity_id": "Entity to use as source.", + "name": "Name of the compensation sensor." + }, + "description": "Create a compensation sensor that enhances the accuracy of a source sensor's value. This is done by calculating a new state using an nth degree polynomial with the source sensor's value." + } + } + }, + "exceptions": { + "setup_error": { + "message": "Setup of {title} could not be completed due to {error}" + } + }, + "options": { + "abort": { + "already_configured": "[%key:common::config_flow::abort::already_configured_account%]" + }, + "error": { + "invalid_datapoints": "[%key:component::compensation::config::error::invalid_datapoints%]", + "not_enough_datapoints": "[%key:component::compensation::config::error::not_enough_datapoints%]" + }, + "step": { + "init": { + "data": { + "attribute": "[%key:component::compensation::config::step::options::data::attribute%]", + "device_class": "[%key:component::compensation::config::step::options::data::device_class%]", + "lower_limit": "[%key:component::compensation::config::step::options::data::lower_limit%]", + "precision": "[%key:component::compensation::config::step::options::data::precision%]", + "state_class": "[%key:component::compensation::config::step::options::data::state_class%]", + "unit_of_measurement": "[%key:component::compensation::config::step::options::data::unit_of_measurement%]", + "upper_limit": "[%key:component::compensation::config::step::options::data::upper_limit%]" + }, + "data_description": { + "attribute": "[%key:component::compensation::config::step::options::data_description::attribute%]", + "device_class": "[%key:component::compensation::config::step::options::data_description::device_class%]", + "lower_limit": "[%key:component::compensation::config::step::options::data_description::lower_limit%]", + "precision": "[%key:component::compensation::config::step::options::data_description::precision%]", + "state_class": "[%key:component::compensation::config::step::options::data_description::state_class%]", + "unit_of_measurement": "[%key:component::compensation::config::step::options::data_description::unit_of_measurement%]", + "upper_limit": "[%key:component::compensation::config::step::options::data_description::upper_limit%]" + }, + "description": "[%key:component::compensation::config::step::options::description%]", + "sections": { + "polynomial_config": { + "data": { + "data_points": "[%key:component::compensation::config::step::options::sections::polynomial_config::data::data_points%]", + "degree": "[%key:component::compensation::config::step::options::sections::polynomial_config::data::degree%]" + }, + "data_description": { + "degree": "[%key:component::compensation::config::step::options::sections::polynomial_config::data_description::degree%]" + }, + "description": "[%key:component::compensation::config::step::options::sections::polynomial_config::description%]", + "name": "[%key:component::compensation::config::step::options::sections::polynomial_config::name%]" + } + } + } + } + }, + "selector": { + "data_points": { + "fields": { + "compensated_value": { + "name": "Compensated value", + "overview_label": "Compensated value: {value}" + }, + "uncompensated_value": { + "name": "Uncompensated value", + "overview_label": "Uncompensated value: {value}" + } + } + } + } +} diff --git a/homeassistant/generated/config_flows.py b/homeassistant/generated/config_flows.py index 5db1ce6d5169..ba7418dcc111 100644 --- a/homeassistant/generated/config_flows.py +++ b/homeassistant/generated/config_flows.py @@ -5,6 +5,7 @@ To update, run python3 -m script.hassfest FLOWS = { "helper": [ + "compensation", "derivative", "filter", "generic_hygrostat", diff --git a/homeassistant/generated/integrations.json b/homeassistant/generated/integrations.json index 84a46e954881..d6122f198d28 100644 --- a/homeassistant/generated/integrations.json +++ b/homeassistant/generated/integrations.json @@ -2488,15 +2488,6 @@ "config_flow": false, "iot_class": "local_polling" }, - "compensation": { - "name": "Compensation", - "integration_type": "hub", - "categories": [ - "helpers.calculate_value" - ], - "config_flow": false, - "iot_class": "calculated" - }, "compit": { "name": "Compit", "integration_type": "hub", @@ -17274,6 +17265,15 @@ } }, "helper": { + "compensation": { + "name": "Compensation", + "integration_type": "helper", + "categories": [ + "helpers.calculate_value" + ], + "config_flow": true, + "iot_class": "calculated" + }, "counter": { "integration_type": "helper", "categories": [ diff --git a/tests/components/compensation/conftest.py b/tests/components/compensation/conftest.py new file mode 100644 index 000000000000..4e9cb463ae31 --- /dev/null +++ b/tests/components/compensation/conftest.py @@ -0,0 +1,59 @@ +"""Compensation fixtures.""" + +from collections.abc import Generator +from unittest.mock import AsyncMock, patch + +import pytest +from pytest_homeassistant.common import MockConfigEntry + +from homeassistant.components.compensation.const import ( + CONF_COMPENSATED_VALUE, + CONF_DATAPOINTS, + CONF_DEGREE, + CONF_LOWER_LIMIT, + CONF_POLYNOMIAL_CONFIG, + CONF_PRECISION, + CONF_UNCOMPENSATED_VALUE, + CONF_UPPER_LIMIT, + DOMAIN, +) +from homeassistant.const import CONF_ENTITY_ID, CONF_NAME + + +@pytest.fixture +def mock_setup_entry() -> Generator[AsyncMock]: + """Override async_setup_entry.""" + with patch( + "homeassistant.components.compensation.async_setup_entry", + return_value=True, + ) as mock_setup_entry: + yield mock_setup_entry + + +@pytest.fixture +def data_points() -> list[dict[str, float]]: + """Return the data points for the config entry.""" + return [ + {CONF_UNCOMPENSATED_VALUE: 1.0, CONF_COMPENSATED_VALUE: 2.0}, + {CONF_UNCOMPENSATED_VALUE: 2.0, CONF_COMPENSATED_VALUE: 3.0}, + ] + + +@pytest.fixture +def mock_config_entry(data_points: list[dict[str, float]]) -> MockConfigEntry: + """Return a compensation config entry.""" + return MockConfigEntry( + domain=DOMAIN, + title="My compensation", + options={ + CONF_NAME: "My compensation", + CONF_ENTITY_ID: "sensor.uncompensated", + CONF_POLYNOMIAL_CONFIG: { + CONF_DATAPOINTS: data_points, + CONF_DEGREE: 1, + }, + CONF_LOWER_LIMIT: False, + CONF_UPPER_LIMIT: False, + CONF_PRECISION: 2, + }, + ) diff --git a/tests/components/compensation/test_config_flow.py b/tests/components/compensation/test_config_flow.py new file mode 100644 index 000000000000..e31b3aa7a283 --- /dev/null +++ b/tests/components/compensation/test_config_flow.py @@ -0,0 +1,225 @@ +"""Test for compensation config flow.""" + +from collections.abc import Callable +from typing import Any +from unittest.mock import AsyncMock + +import pytest +from pytest_homeassistant.common import MockConfigEntry + +from homeassistant.components.compensation.const import ( + CONF_COMPENSATED_VALUE, + CONF_DATAPOINTS, + CONF_DEGREE, + CONF_LOWER_LIMIT, + CONF_POLYNOMIAL_CONFIG, + CONF_PRECISION, + CONF_UNCOMPENSATED_VALUE, + CONF_UPPER_LIMIT, + DEFAULT_NAME, + DOMAIN, +) +from homeassistant.components.sensor import ( + ATTR_STATE_CLASS, + CONF_STATE_CLASS, + SensorDeviceClass, + SensorStateClass, +) +from homeassistant.config_entries import SOURCE_USER +from homeassistant.const import ( + ATTR_DEVICE_CLASS, + ATTR_UNIT_OF_MEASUREMENT, + CONF_DEVICE_CLASS, + CONF_ENTITY_ID, + CONF_NAME, + CONF_UNIT_OF_MEASUREMENT, + UnitOfTemperature, +) +from homeassistant.core import HomeAssistant +from homeassistant.data_entry_flow import FlowResultType +from homeassistant.helpers import entity_registry as er + + +@pytest.mark.parametrize( + "source", + [ + pytest.param(lambda entry: entry.entity_id, id="entity_id"), + pytest.param(lambda entry: entry.id, id="uuid"), + ], +) +async def test_user_flow( + hass: HomeAssistant, + mock_setup_entry: AsyncMock, + entity_registry: er.EntityRegistry, + source: Callable[[er.RegistryEntry], str], +) -> None: + """Test full flow.""" + source_entry = entity_registry.async_get_or_create( + "sensor", "test", "unique", suggested_object_id="test_sensor" + ) + + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": SOURCE_USER}, + ) + await hass.async_block_till_done() + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_NAME: DEFAULT_NAME, CONF_ENTITY_ID: source(source_entry)}, + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "options" + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + { + CONF_LOWER_LIMIT: False, + CONF_POLYNOMIAL_CONFIG: { + CONF_DATAPOINTS: [ + {CONF_COMPENSATED_VALUE: 6, CONF_UNCOMPENSATED_VALUE: 5}, + {CONF_COMPENSATED_VALUE: 8, CONF_UNCOMPENSATED_VALUE: 7}, + ], + CONF_DEGREE: 1, + }, + CONF_PRECISION: 2, + CONF_UPPER_LIMIT: False, + }, + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == DEFAULT_NAME + assert result["data"] == {} + assert result["options"] == { + CONF_ENTITY_ID: "sensor.test_sensor", + CONF_LOWER_LIMIT: False, + CONF_NAME: "Compensation", + CONF_POLYNOMIAL_CONFIG: { + CONF_DATAPOINTS: [ + {CONF_COMPENSATED_VALUE: 6, CONF_UNCOMPENSATED_VALUE: 5}, + {CONF_COMPENSATED_VALUE: 8, CONF_UNCOMPENSATED_VALUE: 7}, + ], + CONF_DEGREE: 1, + }, + CONF_PRECISION: 2, + CONF_UPPER_LIMIT: False, + } + + +@pytest.mark.parametrize( + ("data_points", "error"), + [ + pytest.param([], "not_enough_datapoints", id="no_datapoints"), + pytest.param( + [{CONF_COMPENSATED_VALUE: 6, CONF_UNCOMPENSATED_VALUE: 5}], + "not_enough_datapoints", + id="not_enough_datapoints", + ), + pytest.param( + [ + {CONF_COMPENSATED_VALUE: 1, CONF_UNCOMPENSATED_VALUE: 0}, + {CONF_COMPENSATED_VALUE: 1, CONF_UNCOMPENSATED_VALUE: 0}, + ], + "invalid_datapoints", + id="invalid_datapoints", + ), + ], +) +@pytest.mark.usefixtures("mock_setup_entry") +async def test_user_flow_errors( + hass: HomeAssistant, data_points: list[dict[str, Any]], error: str +) -> None: + """Test the flow shows an error for invalid data points and can recover.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_NAME: DEFAULT_NAME, CONF_ENTITY_ID: "sensor.test_sensor"}, + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + { + CONF_POLYNOMIAL_CONFIG: {CONF_DATAPOINTS: data_points, CONF_DEGREE: 1}, + CONF_PRECISION: 2, + }, + ) + + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {"base": error} + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + { + CONF_POLYNOMIAL_CONFIG: { + CONF_DATAPOINTS: [ + {CONF_COMPENSATED_VALUE: 6, CONF_UNCOMPENSATED_VALUE: 5}, + {CONF_COMPENSATED_VALUE: 8, CONF_UNCOMPENSATED_VALUE: 7}, + ], + CONF_DEGREE: 1, + }, + CONF_PRECISION: 2, + }, + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + + +async def test_options_flow( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Test the options flow updates the entry and reloads it.""" + hass.states.async_set("sensor.uncompensated", "5") + mock_config_entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + assert hass.states.get("sensor.my_compensation").state == "6.0" + + result = await hass.config_entries.options.async_init(mock_config_entry.entry_id) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "init" + + result = await hass.config_entries.options.async_configure( + result["flow_id"], + { + CONF_POLYNOMIAL_CONFIG: { + CONF_DATAPOINTS: [ + {CONF_COMPENSATED_VALUE: 2, CONF_UNCOMPENSATED_VALUE: 1}, + {CONF_COMPENSATED_VALUE: 4, CONF_UNCOMPENSATED_VALUE: 2}, + ], + CONF_DEGREE: 1, + }, + CONF_PRECISION: 1, + CONF_DEVICE_CLASS: SensorDeviceClass.TEMPERATURE, + CONF_STATE_CLASS: SensorStateClass.MEASUREMENT, + CONF_UNIT_OF_MEASUREMENT: UnitOfTemperature.CELSIUS, + }, + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert mock_config_entry.options == { + CONF_ENTITY_ID: "sensor.uncompensated", + CONF_LOWER_LIMIT: False, + CONF_NAME: "My compensation", + CONF_POLYNOMIAL_CONFIG: { + CONF_DATAPOINTS: [ + {CONF_COMPENSATED_VALUE: 2, CONF_UNCOMPENSATED_VALUE: 1}, + {CONF_COMPENSATED_VALUE: 4, CONF_UNCOMPENSATED_VALUE: 2}, + ], + CONF_DEGREE: 1, + }, + CONF_PRECISION: 1, + CONF_DEVICE_CLASS: SensorDeviceClass.TEMPERATURE, + CONF_STATE_CLASS: SensorStateClass.MEASUREMENT, + CONF_UNIT_OF_MEASUREMENT: UnitOfTemperature.CELSIUS, + CONF_UPPER_LIMIT: False, + } + + # The reloaded sensor picks up the existing source state without a new change + state = hass.states.get("sensor.my_compensation") + assert state.state == "10.0" + assert state.attributes[ATTR_DEVICE_CLASS] == SensorDeviceClass.TEMPERATURE + assert state.attributes[ATTR_STATE_CLASS] == SensorStateClass.MEASUREMENT + assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == UnitOfTemperature.CELSIUS diff --git a/tests/components/compensation/test_init.py b/tests/components/compensation/test_init.py new file mode 100644 index 000000000000..d6b31635e92e --- /dev/null +++ b/tests/components/compensation/test_init.py @@ -0,0 +1,83 @@ +"""Test the Compensation integration setup.""" + +import pytest +from pytest_homeassistant.common import MockConfigEntry + +from homeassistant.components.compensation.const import ( + CONF_COMPENSATED_VALUE, + CONF_UNCOMPENSATED_VALUE, +) +from homeassistant.config_entries import ConfigEntryState +from homeassistant.const import CONF_ENTITY_ID +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er + +ENTITY_ID = "sensor.my_compensation" + + +async def test_setup_and_unload_entry( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Test setting up and unloading a config entry.""" + mock_config_entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.LOADED + + hass.states.async_set("sensor.uncompensated", "5") + await hass.async_block_till_done() + assert hass.states.get(ENTITY_ID).state == "6.0" + + assert await hass.config_entries.async_unload(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.NOT_LOADED + + +@pytest.mark.parametrize( + "data_points", + [ + [ + {CONF_UNCOMPENSATED_VALUE: 0.0, CONF_COMPENSATED_VALUE: 1.0}, + {CONF_UNCOMPENSATED_VALUE: 0.0, CONF_COMPENSATED_VALUE: 1.0}, + ] + ], +) +async def test_setup_entry_polyfit_error( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Test setup fails when no polynomial can be fitted to the data points.""" + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR + assert mock_config_entry.error_reason_translation_key == "setup_error" + assert hass.states.get(ENTITY_ID) is None + + +async def test_source_entity_new_entity_id( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + mock_config_entry: MockConfigEntry, +) -> None: + """Test the config entry follows a renamed source entity.""" + source_entry = entity_registry.async_get_or_create( + "sensor", "test", "unique", suggested_object_id="uncompensated" + ) + mock_config_entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + entity_registry.async_update_entity( + source_entry.entity_id, new_entity_id="sensor.new_entity_id" + ) + await hass.async_block_till_done() + + assert mock_config_entry.options[CONF_ENTITY_ID] == "sensor.new_entity_id" + assert mock_config_entry.state is ConfigEntryState.LOADED + + hass.states.async_set("sensor.new_entity_id", "5") + await hass.async_block_till_done() + assert hass.states.get(ENTITY_ID).state == "6.0" diff --git a/tests/components/compensation/test_sensor.py b/tests/components/compensation/test_sensor.py index e39b6a0f7a73..9de70d3e92bc 100644 --- a/tests/components/compensation/test_sensor.py +++ b/tests/components/compensation/test_sensor.py @@ -5,6 +5,7 @@ from unittest.mock import patch import pytest from pytest_homeassistant.common import ( + MockConfigEntry, assert_platform_setup_creates_issue, assert_setup_component, get_fixture_path, @@ -149,6 +150,20 @@ async def test_initial_state_from_existing_source(hass: HomeAssistant) -> None: assert state.state == "5.0" +async def test_config_entry_initial_state_from_existing_source( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Test the config entry sensor uses the source state that exists before setup.""" + hass.states.async_set(TEST_SOURCE, "5") + mock_config_entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + state = hass.states.get("sensor.my_compensation") + assert state is not None + assert state.state == "6.0" + + @pytest.mark.parametrize("config", [{"name": TEST_OBJECT_ID, **TEST_BASE_CONFIG}]) @pytest.mark.usefixtures("setup_compensation") async def test_attributes_come_from_source(hass: HomeAssistant) -> None: