Add temperature_kelvin, min_kelvin and max_kelvin to template light (#193273)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Erik Montnemery <erik@montnemery.com>
This commit is contained in:
Petro31
2026-11-25 08:15:10 +01:00
committed by GitHub
co-authored by Claude Opus 5.5 Erik Montnemery
parent 71172ad2b6
commit 39cffdb8f8
13 changed files with 1407 additions and 140 deletions
+16 -5
View File
@@ -1,6 +1,6 @@
"""Template config validator."""
from collections.abc import Callable, Collection
from collections.abc import Callable, Collection, Iterable
from contextlib import suppress
import itertools
import logging
@@ -82,9 +82,10 @@ from . import (
)
from .const import (
CONF_TRIGGER_VARIABLES,
DEPRECATED_TEMPLATE_OPTIONS,
DOMAIN,
PLATFORMS,
WEATHER_DEPRECATED_TEMPLATE_OPTIONS,
DeprecatedTemplateOptions,
TemplateConfig,
TemplateConfigSections,
)
@@ -428,10 +429,20 @@ async def _async_validate_triggers_and_conditions(
raise
def _merge_deprecated_options(
deprecations: Iterable[DeprecatedTemplateOptions],
) -> dict[str, Collection[str]]:
"""Return the deprecated options of every deprecation, merged per platform."""
merged: dict[str, set[str]] = {}
for deprecation in deprecations:
merged.setdefault(deprecation.platform, set()).update(deprecation.options)
return dict(merged)
# Deprecated options per platform whose file and line are kept for repairs
DEPRECATED_OPTIONS_WITH_LOCATIONS: dict[str, Collection[str]] = {
WEATHER_DOMAIN: WEATHER_DEPRECATED_TEMPLATE_OPTIONS,
}
DEPRECATED_OPTIONS_WITH_LOCATIONS = _merge_deprecated_options(
DEPRECATED_TEMPLATE_OPTIONS
)
def _get_option_locations(
@@ -139,6 +139,7 @@ from .light import (
CONF_LEVEL_ACTION,
CONF_TEMPERATURE,
CONF_TEMPERATURE_ACTION,
CONF_TEMPERATURE_KELVIN,
async_create_preview_light,
)
from .lock import CONF_LOCK, CONF_OPEN, CONF_UNLOCK, async_create_preview_lock
@@ -211,7 +212,9 @@ _CONFIG_DEVICE_CLASS_DOMAINS = (
)
def generate_schema(domain: str, flow_type: str) -> probatio.Schema:
def generate_schema(
domain: str, flow_type: str, options: Mapping[str, Any] | None = None
) -> probatio.Schema:
"""Generate schema."""
schema: dict[probatio.Marker, Any] = {}
additional_options: dict[probatio.Marker, Any] = {}
@@ -358,7 +361,16 @@ def generate_schema(domain: str, flow_type: str) -> probatio.Schema:
probatio.Optional(CONF_LEVEL_ACTION): selector.ActionSelector(),
probatio.Optional(CONF_HS): selector.TemplateSelector(),
probatio.Optional(CONF_HS_ACTION): selector.ActionSelector(),
probatio.Optional(CONF_TEMPERATURE): selector.TemplateSelector(),
probatio.Optional(CONF_TEMPERATURE_KELVIN): selector.TemplateSelector(),
}
# The deprecated temperature option is only shown to existing helpers
if options and CONF_TEMPERATURE in options:
schema |= {
probatio.Optional(CONF_TEMPERATURE): selector.TemplateSelector(
selector.TemplateSelectorConfig(read_only=True)
),
}
schema |= {
probatio.Optional(CONF_TEMPERATURE_ACTION): selector.ActionSelector(),
}
@@ -584,6 +596,11 @@ options_schema = partial(generate_schema, flow_type="options")
config_schema = partial(generate_schema, flow_type="config")
async def _light_options_schema(handler: SchemaCommonFlowHandler) -> probatio.Schema:
"""Return the light options schema for the options of the config entry."""
return options_schema(Platform.LIGHT, options=handler.options)
async def _get_forecast_description_place_holders(
handler: SchemaCommonFlowHandler,
) -> dict[str, str]:
@@ -663,7 +680,7 @@ def validate_user_input(
"""
async def _validate_user_input(
_: SchemaCommonFlowHandler,
handler: SchemaCommonFlowHandler,
user_input: dict[str, Any],
) -> dict[str, Any]:
"""Add template type to user input."""
@@ -674,6 +691,14 @@ def validate_user_input(
tcv.requires_option(CONF_TARGET_TEMPERATURE, SET_TEMPERATURE_ACTION)(
user_input
)
if template_type == Platform.LIGHT and (
CONF_TEMPERATURE_KELVIN in user_input
or CONF_TEMPERATURE_ACTION not in user_input
):
# The deprecated temperature is read only, it is removed by replacing it
# with temperature_kelvin or by removing the color temperature action
handler.options.pop(CONF_TEMPERATURE, None)
user_input.pop(CONF_TEMPERATURE, None)
if template_type == Platform.MEDIA_PLAYER:
for option, required_option, error in _MEDIA_PLAYER_REQUIRED_OPTIONS:
if option in user_input and required_option not in user_input:
@@ -871,7 +896,7 @@ OPTIONS_FLOW = {
validate_user_input=validate_user_input(Platform.IMAGE),
),
Platform.LIGHT: SchemaFlowFormStep(
options_schema(Platform.LIGHT),
_light_options_schema,
preview="template",
validate_user_input=validate_user_input(Platform.LIGHT),
),
@@ -1037,7 +1062,7 @@ def ws_start_preview(
raise HomeAssistantError
template_type = config_entry.options["template_type"]
name = config_entry.options["name"]
schema = cast(probatio.Schema, OPTIONS_FLOW[template_type].schema)
schema = options_schema(template_type, options=config_entry.options)
entity_registry = er.async_get(hass)
entries = er.async_entries_for_config_entry(
entity_registry, flow_status["handler"]
@@ -1,5 +1,7 @@
"""Constants for the Template Platform Components."""
from collections.abc import Mapping
from dataclasses import dataclass
from enum import StrEnum
from homeassistant.const import Platform
@@ -92,6 +94,45 @@ WEATHER_DEPRECATED_TEMPLATE_OPTIONS = {
"wind_speed_template": "wind_speed",
}
# Light option in mireds to its replacement in kelvin, deprecated in 2026.12
LIGHT_DEPRECATED_MIREDS_OPTIONS = {
"temperature": "temperature_kelvin",
"max_mireds": "min_kelvin",
"min_mireds": "max_kelvin",
}
@dataclass(frozen=True, kw_only=True)
class DeprecatedTemplateOptions:
"""Deprecated YAML options of a template platform that create repairs."""
platform: Platform
# Deprecated option to the option that replaces it
options: Mapping[str, str]
# Also the prefix of the issue ids
translation_key: str
blueprint_translation_key: str
breaks_in_ha_version: str
WEATHER_DEPRECATED_OPTIONS = DeprecatedTemplateOptions(
platform=Platform.WEATHER,
options=WEATHER_DEPRECATED_TEMPLATE_OPTIONS,
translation_key="deprecated_weather_template_options",
blueprint_translation_key="deprecated_weather_template_options_blueprint",
breaks_in_ha_version="2027.6.0",
)
LIGHT_DEPRECATED_OPTIONS = DeprecatedTemplateOptions(
platform=Platform.LIGHT,
options=LIGHT_DEPRECATED_MIREDS_OPTIONS,
translation_key="deprecated_light_mireds_options",
blueprint_translation_key="deprecated_light_mireds_options_blueprint",
breaks_in_ha_version="2027.6.0",
)
DEPRECATED_TEMPLATE_OPTIONS = (WEATHER_DEPRECATED_OPTIONS, LIGHT_DEPRECATED_OPTIONS)
class TemplateConfig(dict):
"""Dummy class to allow adding attributes."""
+231 -57
View File
@@ -3,6 +3,7 @@
from collections.abc import Callable
import contextlib
from dataclasses import dataclass
from functools import partial
import logging
from typing import TYPE_CHECKING, Any, Self, override
@@ -40,17 +41,18 @@ from homeassistant.const import (
Platform,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.exceptions import TemplateError
from homeassistant.helpers import config_validation as cv, issue_registry as ir
from homeassistant.helpers.entity_platform import (
AddConfigEntryEntitiesCallback,
AddEntitiesCallback,
)
from homeassistant.helpers.restore_state import ExtraStoredData, RestoreEntity
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from homeassistant.helpers.typing import UNDEFINED, ConfigType, DiscoveryInfoType
from homeassistant.util import color as color_util
from . import validators as tcv
from .const import DEFAULT_NAMES, DOMAIN
from .const import DEFAULT_NAMES, DOMAIN, LIGHT_DEPRECATED_OPTIONS
from .coordinator import TriggerUpdateCoordinator
from .entity import AbstractTemplateEntity
from .helpers import (
@@ -81,17 +83,23 @@ CONF_EFFECT_ACTION = "set_effect"
CONF_EFFECT_LIST = "effect_list"
CONF_LEVEL = "level"
CONF_LEVEL_ACTION = "set_level"
CONF_MAX_KELVIN = "max_kelvin"
CONF_MAX_MIREDS = "max_mireds"
CONF_MIN_KELVIN = "min_kelvin"
CONF_MIN_MIREDS = "min_mireds"
CONF_OFF_ACTION = "turn_off"
CONF_ON_ACTION = "turn_on"
CONF_SUPPORTS_TRANSITION = "supports_transition"
CONF_TEMPERATURE_ACTION = "set_temperature"
CONF_TEMPERATURE = "temperature"
CONF_TEMPERATURE_KELVIN = "temperature_kelvin"
CONF_XY_ACTION = "set_xy"
DEFAULT_MIN_MIREDS = 153
DEFAULT_MAX_MIREDS = 500
DEPRECATED_TEMPERATURE_ISSUE_ID = "deprecated_light_temperature"
# Above this, the mireds convert to 0 kelvin
MAX_MIREDS = 1_000_000
DEFAULT_NAME = DEFAULT_NAMES[Platform.LIGHT]
@@ -117,7 +125,9 @@ LIGHT_COMMON_SCHEMA = probatio.Schema(
probatio.Optional(CONF_HS): cv.template,
probatio.Optional(CONF_LEVEL_ACTION): cv.SCRIPT_SCHEMA,
probatio.Optional(CONF_LEVEL): cv.template,
probatio.Optional(CONF_MAX_KELVIN): cv.template,
probatio.Optional(CONF_MAX_MIREDS): cv.template,
probatio.Optional(CONF_MIN_KELVIN): cv.template,
probatio.Optional(CONF_MIN_MIREDS): cv.template,
probatio.Required(CONF_OFF_ACTION): cv.SCRIPT_SCHEMA,
probatio.Required(CONF_ON_ACTION): cv.SCRIPT_SCHEMA,
@@ -131,13 +141,28 @@ LIGHT_COMMON_SCHEMA = probatio.Schema(
probatio.Optional(CONF_SUPPORTS_TRANSITION): cv.template,
probatio.Optional(CONF_TEMPERATURE_ACTION): cv.SCRIPT_SCHEMA,
probatio.Optional(CONF_TEMPERATURE): cv.template,
probatio.Optional(CONF_TEMPERATURE_KELVIN): cv.template,
probatio.Optional(CONF_XY): cv.template,
probatio.Optional(CONF_XY_ACTION): cv.SCRIPT_SCHEMA,
}
)
def _validate_color_temp_range(config: dict[str, Any]) -> dict[str, Any]:
"""Validate that the color temperature range is not set in mireds and kelvin."""
if any(option in config for option in (CONF_MIN_MIREDS, CONF_MAX_MIREDS)) and any(
option in config for option in (CONF_MIN_KELVIN, CONF_MAX_KELVIN)
):
raise probatio.Invalid(
f"'{CONF_MIN_KELVIN}' and '{CONF_MAX_KELVIN}' cannot be used together with"
f" '{CONF_MIN_MIREDS}' or '{CONF_MAX_MIREDS}'"
)
return config
_LIGHT_VALIDATION = (
tcv.inclusive_group("effect", CONF_EFFECT, CONF_EFFECT_LIST, CONF_EFFECT_ACTION),
_validate_color_temp_range,
)
_BLOCKED_ATTRIBUTES = tcv.BlockedTemplateAttributes(
@@ -184,6 +209,25 @@ async def async_setup_entry(
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Initialize config entry."""
issue_id = f"{DEPRECATED_TEMPERATURE_ISSUE_ID}_{config_entry.entry_id}"
if CONF_TEMPERATURE in config_entry.options:
ir.async_create_issue(
hass,
DOMAIN,
issue_id,
breaks_in_ha_version=LIGHT_DEPRECATED_OPTIONS.breaks_in_ha_version,
config_entry_id=config_entry.entry_id,
is_fixable=False,
severity=ir.IssueSeverity.WARNING,
translation_key=DEPRECATED_TEMPERATURE_ISSUE_ID,
translation_placeholders={
"name": config_entry.title,
"breaks_in_ha_version": LIGHT_DEPRECATED_OPTIONS.breaks_in_ha_version,
},
)
else:
ir.async_delete_issue(hass, DOMAIN, issue_id)
await async_setup_template_entry(
hass,
config_entry,
@@ -408,15 +452,61 @@ class AbstractTemplateLight(AbstractTemplateEntity, LightEntity, RestoreEntity):
)
self.add_assumed_attribute("_attr_brightness", CONF_LEVEL, CONF_LEVEL_ACTION)
# Setup Color temperature
# Min/Max temperature templates, set up first to validate the temperature
self.setup_template(
CONF_TEMPERATURE,
CONF_MAX_MIREDS,
"_attr_min_color_temp_kelvin",
tcv.number(self, CONF_MAX_MIREDS, 1, MAX_MIREDS),
partial(
self._update_min_kelvin,
convert=color_util.color_temperature_mired_to_kelvin,
),
none_on_template_error=False,
)
self.setup_template(
CONF_MIN_MIREDS,
"_attr_max_color_temp_kelvin",
tcv.number(self, CONF_MIN_MIREDS, 1, MAX_MIREDS),
partial(
self._update_max_kelvin,
convert=color_util.color_temperature_mired_to_kelvin,
),
none_on_template_error=False,
)
self.setup_template(
CONF_MIN_KELVIN,
"_attr_min_color_temp_kelvin",
tcv.number(self, CONF_MIN_KELVIN, 1, None, int),
self._update_min_kelvin,
none_on_template_error=False,
)
self.setup_template(
CONF_MAX_KELVIN,
"_attr_max_color_temp_kelvin",
tcv.number(self, CONF_MAX_KELVIN, 1, None, int),
self._update_max_kelvin,
none_on_template_error=False,
)
# Setup Color temperature, temperature_kelvin takes precedence over the
# deprecated temperature option
self._temperature_option = CONF_TEMPERATURE_KELVIN
self._temperature_validator = self._validate_temperature_kelvin
if CONF_TEMPERATURE in config and CONF_TEMPERATURE_KELVIN not in config:
self._temperature_option = CONF_TEMPERATURE
self._temperature_validator = self._validate_temperature
# The raw result is cached to revalidate it when the min/max range changes
self._rendered_temperature: Any = UNDEFINED
self.setup_template(
self._temperature_option,
"_attr_color_temp_kelvin",
self._validate_temperature,
self._update_color("_attr_color_temp_kelvin", ColorMode.COLOR_TEMP),
on_update=self._update_temperature,
none_on_template_error=False,
)
self.add_assumed_attribute(
"_attr_color_temp_kelvin", CONF_TEMPERATURE, CONF_TEMPERATURE_ACTION
"_attr_color_temp_kelvin",
self._temperature_option,
CONF_TEMPERATURE_ACTION,
)
# Setup Hue Saturation
@@ -474,20 +564,6 @@ class AbstractTemplateLight(AbstractTemplateEntity, LightEntity, RestoreEntity):
)
self.add_assumed_attribute("_attr_effect", CONF_EFFECT, CONF_EFFECT_ACTION)
# Min/Max temperature templates
self.setup_template(
CONF_MAX_MIREDS,
"_attr_max_color_temp_kelvin",
tcv.number(self, CONF_MAX_MIREDS),
self._update_max_mireds,
)
self.setup_template(
CONF_MIN_MIREDS,
"_attr_min_color_temp_kelvin",
tcv.number(self, CONF_MIN_MIREDS),
self._update_min_mireds,
)
# Transition
self.setup_template(
CONF_SUPPORTS_TRANSITION,
@@ -498,6 +574,7 @@ class AbstractTemplateLight(AbstractTemplateEntity, LightEntity, RestoreEntity):
# Stored values for template attributes
self._supports_transition = False
self._inverted_color_temp_range = False
color_modes = {ColorMode.ONOFF}
for action_id, color_mode in (
@@ -575,9 +652,14 @@ class AbstractTemplateLight(AbstractTemplateEntity, LightEntity, RestoreEntity):
optimistic_set = True
for option, attr, color_mode, validator in (
(CONF_TEMPERATURE, ATTR_COLOR_TEMP_KELVIN, ColorMode.COLOR_TEMP, None),
(
CONF_TEMPERATURE,
self._temperature_option,
ATTR_COLOR_TEMP_KELVIN,
ColorMode.COLOR_TEMP,
None,
),
(
self._temperature_option,
ATTR_COLOR_TEMP,
ColorMode.COLOR_TEMP,
color_util.color_temperature_mired_to_kelvin,
@@ -617,7 +699,7 @@ class AbstractTemplateLight(AbstractTemplateEntity, LightEntity, RestoreEntity):
self._attr_color_mode = color_mode
for _option in (
CONF_TEMPERATURE,
self._temperature_option,
CONF_HS,
CONF_RGB,
CONF_RGBW,
@@ -771,21 +853,85 @@ class AbstractTemplateLight(AbstractTemplateEntity, LightEntity, RestoreEntity):
return update
@callback
def _update_temperature(self, result: Any) -> None:
"""Store the rendered temperature and validate it against the range."""
if isinstance(result, TemplateError):
result = None
self._rendered_temperature = result
self._update_color("_attr_color_temp_kelvin", ColorMode.COLOR_TEMP)(
self._temperature_validator(result)
)
@callback
def _revalidate_temperature(self) -> None:
"""Revalidate the rendered temperature after the range changed."""
if self._rendered_temperature is UNDEFINED:
return
self._attr_color_temp_kelvin = self._temperature_validator(
self._rendered_temperature
)
# Another color mode stays active, only an unset mode switches over
if self._attr_color_temp_kelvin is not None and self._attr_color_mode in (
None,
ColorMode.UNKNOWN,
):
self._attr_color_mode = ColorMode.COLOR_TEMP
@property
def _color_temp_range(self) -> tuple[int, int]:
"""Return the color temperature range, the default range when inverted."""
min_kelvin = self._attr_min_color_temp_kelvin
max_kelvin = self._attr_max_color_temp_kelvin
if min_kelvin is None or max_kelvin is None or min_kelvin > max_kelvin:
return DEFAULT_MIN_KELVIN, DEFAULT_MAX_KELVIN
return min_kelvin, max_kelvin
@property
@override
def min_color_temp_kelvin(self) -> int:
"""Return the warmest color temperature this light supports."""
return self._color_temp_range[0]
@property
@override
def max_color_temp_kelvin(self) -> int:
"""Return the coldest color temperature this light supports."""
return self._color_temp_range[1]
@property
@override
def capability_attributes(self) -> dict[str, Any]:
"""Return capability attributes, warning once about an inverted range."""
# Checked on write, the bounds can be inverted between their updates
inverted = (
self._attr_min_color_temp_kelvin is not None
and self._attr_max_color_temp_kelvin is not None
and self._attr_min_color_temp_kelvin > self._attr_max_color_temp_kelvin
)
if inverted and not self._inverted_color_temp_range:
_LOGGER.warning(
"The color temperature range of %s is inverted, min %s K is above "
"max %s K, using the default range %s-%s K",
self.entity_id,
self._attr_min_color_temp_kelvin,
self._attr_max_color_temp_kelvin,
DEFAULT_MIN_KELVIN,
DEFAULT_MAX_KELVIN,
)
self._inverted_color_temp_range = inverted
return super().capability_attributes
@callback
def _validate_temperature(self, result: Any) -> int | None:
"""Validate the temperature from the template."""
if tcv.check_result_for_none(result):
return None
if (min_kelvin := self._attr_min_color_temp_kelvin) is not None:
max_mireds = color_util.color_temperature_kelvin_to_mired(min_kelvin)
else:
max_mireds = DEFAULT_MAX_MIREDS
if (max_kelvin := self._attr_max_color_temp_kelvin) is not None:
min_mireds = color_util.color_temperature_kelvin_to_mired(max_kelvin)
else:
min_mireds = DEFAULT_MIN_MIREDS
min_kelvin, max_kelvin = self._color_temp_range
max_mireds = color_util.color_temperature_kelvin_to_mired(min_kelvin)
min_mireds = color_util.color_temperature_kelvin_to_mired(max_kelvin)
if isinstance(result, (int, float)) and min_mireds <= result <= max_mireds:
return color_util.color_temperature_mired_to_kelvin(result)
@@ -799,40 +945,68 @@ class AbstractTemplateLight(AbstractTemplateEntity, LightEntity, RestoreEntity):
return None
@callback
def _update_max_mireds(self, render):
"""Update the max mireds from the template."""
if render is None:
self._attr_min_color_temp_kelvin = DEFAULT_MIN_KELVIN
return
def _validate_temperature_kelvin(self, result: Any) -> int | None:
"""Validate the temperature in kelvin from the template."""
if tcv.check_result_for_none(result):
return None
try:
self._attr_min_color_temp_kelvin = (
color_util.color_temperature_mired_to_kelvin(int(render))
)
except ValueError:
_LOGGER.exception(
"Template must supply an integer temperature within the range for"
" this light, or 'None'"
)
self._attr_min_color_temp_kelvin = DEFAULT_MIN_KELVIN
min_kelvin, max_kelvin = self._color_temp_range
if (
isinstance(result, (int, float))
and not isinstance(result, bool)
and min_kelvin <= result <= max_kelvin
):
return round(result)
tcv.log_validation_result_error(
self,
CONF_TEMPERATURE_KELVIN,
result,
f"expected a number between {min_kelvin} and {max_kelvin}",
)
return None
@callback
def _update_min_mireds(self, render):
"""Update the min mireds from the template."""
if render is None:
self._attr_max_color_temp_kelvin = DEFAULT_MAX_KELVIN
def _update_min_kelvin(
self, render: Any, convert: Callable[[int], int] | None = None
) -> None:
"""Update the min kelvin from the template."""
if render is None or isinstance(render, TemplateError):
self._attr_min_color_temp_kelvin = DEFAULT_MIN_KELVIN
self._revalidate_temperature()
return
try:
self._attr_max_color_temp_kelvin = (
color_util.color_temperature_mired_to_kelvin(int(render))
value = int(render)
self._attr_min_color_temp_kelvin = convert(value) if convert else value
except ValueError:
_LOGGER.exception(
"Template must supply an integer temperature within the range for"
" this light, or 'None'"
)
self._attr_min_color_temp_kelvin = DEFAULT_MIN_KELVIN
self._revalidate_temperature()
@callback
def _update_max_kelvin(
self, render: Any, convert: Callable[[int], int] | None = None
) -> None:
"""Update the max kelvin from the template."""
if render is None or isinstance(render, TemplateError):
self._attr_max_color_temp_kelvin = DEFAULT_MAX_KELVIN
self._revalidate_temperature()
return
try:
value = int(render)
self._attr_max_color_temp_kelvin = convert(value) if convert else value
except ValueError:
_LOGGER.exception(
"Template must supply an integer temperature within the range for"
" this light, or 'None'"
)
self._attr_max_color_temp_kelvin = DEFAULT_MAX_KELVIN
self._revalidate_temperature()
@callback
def _update_supports_transition(self, render):
+33 -30
View File
@@ -12,25 +12,20 @@ from homeassistant.components.repairs import (
RepairsFlowResult,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_DEVICE_ID, CONF_PATH, CONF_UNIQUE_ID, Platform
from homeassistant.const import CONF_DEVICE_ID, CONF_PATH, CONF_UNIQUE_ID
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import device_registry as dr, issue_registry as ir
from homeassistant.helpers.selector import DeviceSelector
from . import validators as tcv
from .const import (
DEPRECATED_TEMPLATE_OPTIONS,
DOMAIN,
WEATHER_DEPRECATED_TEMPLATE_OPTIONS,
DeprecatedTemplateOptions,
TemplateConfig,
TemplateConfigSections,
)
DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID = "deprecated_weather_template_options"
DEPRECATED_TEMPLATE_OPTIONS_BLUEPRINT_TRANSLATION_KEY = (
"deprecated_weather_template_options_blueprint"
)
DEPRECATED_TEMPLATE_OPTIONS_BREAKS_IN = "2027.6.0"
class CompositeDeviceIdRepairFlow(RepairsFlow):
"""Handler to select a device again after the linked device was split."""
@@ -97,13 +92,14 @@ class CompositeDeviceIdRepairFlow(RepairsFlow):
def _format_deprecated_options(
hass: HomeAssistant,
deprecation: DeprecatedTemplateOptions,
deprecated: list[str],
locations: dict[str, tuple[str, int]],
) -> str:
"""Return the deprecated options and their replacements as a markdown list."""
changes: list[str] = []
for key in deprecated:
change = f"`{key}` → `{WEATHER_DEPRECATED_TEMPLATE_OPTIONS[key]}`"
change = f"`{key}` → `{deprecation.options[key]}`"
if (location := locations.get(key)) is not None:
path = os.path.relpath(location[0], hass.config.config_dir)
change = f"`{path}:{location[1]}`: {change}"
@@ -115,7 +111,19 @@ def _format_deprecated_options(
def async_update_deprecated_template_options_issues(
hass: HomeAssistant, config_sections: list[TemplateConfig] | None
) -> None:
"""Create an issue per weather entity or blueprint using *_template options."""
"""Create the repairs of every platform with deprecated options."""
for deprecation in DEPRECATED_TEMPLATE_OPTIONS:
_async_update_deprecated_options_issues(hass, deprecation, config_sections)
@callback
def _async_update_deprecated_options_issues(
hass: HomeAssistant,
deprecation: DeprecatedTemplateOptions,
config_sections: list[TemplateConfig] | None,
) -> None:
"""Create an issue per entity or blueprint of a platform using deprecated options."""
platform = deprecation.platform
# Fingerprint to translation key, label placeholder and options of each entity
issues: dict[str, tuple[str, dict[str, str], list[str]]] = {}
for section in config_sections or []:
@@ -123,12 +131,8 @@ def async_update_deprecated_template_options_issues(
if section.raw_blueprint_inputs is not None:
blueprint_path = section.raw_blueprint_inputs[CONF_USE_BLUEPRINT][CONF_PATH]
for index, weather_config in enumerate(section.get(Platform.WEATHER, [])):
deprecated = [
key
for key in weather_config
if key in WEATHER_DEPRECATED_TEMPLATE_OPTIONS
]
for index, entity_config in enumerate(section.get(platform, [])):
deprecated = [key for key in entity_config if key in deprecation.options]
if not deprecated:
continue
@@ -142,56 +146,55 @@ def async_update_deprecated_template_options_issues(
)
if fingerprint in issues:
continue
translation_key = DEPRECATED_TEMPLATE_OPTIONS_BLUEPRINT_TRANSLATION_KEY
translation_key = deprecation.blueprint_translation_key
label = {"blueprint": blueprint_path}
else:
fingerprint = "\n".join(
[
tcv.entity_config_repair_identifier(
Platform.WEATHER,
weather_config,
section.get(CONF_UNIQUE_ID),
platform, entity_config, section.get(CONF_UNIQUE_ID)
),
*(
f"{key}="
f"{getattr(weather_config[key], 'template', weather_config[key])}"
f"{getattr(entity_config[key], 'template', entity_config[key])}"
for key in sorted(deprecated)
),
]
)
translation_key = DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID
translation_key = deprecation.translation_key
label = {
"identifier": tcv.entity_config_identifier(
Platform.WEATHER, weather_config
)
"identifier": tcv.entity_config_identifier(platform, entity_config)
}
# Identical entities share a fingerprint, one issue lists all of them
issues.setdefault(fingerprint, (translation_key, label, []))[2].append(
_format_deprecated_options(
hass,
deprecation,
deprecated,
section.option_locations[Platform.WEATHER][index]
section.option_locations[platform][index]
if section.option_locations
else {},
)
)
with ir.async_refresh_issues(
hass, DOMAIN, issue_id_pattern=f"{DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID}_"
hass, DOMAIN, issue_id_pattern=f"{deprecation.translation_key}_"
) as refresh:
for fingerprint, (translation_key, label, options) in issues.items():
ir.async_create_issue(
hass,
DOMAIN,
f"{DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID}_"
f"{deprecation.translation_key}_"
f"{hashlib.sha256(fingerprint.encode()).hexdigest()[:16]}",
breaks_in_ha_version=DEPRECATED_TEMPLATE_OPTIONS_BREAKS_IN,
breaks_in_ha_version=deprecation.breaks_in_ha_version,
is_fixable=False,
severity=ir.IssueSeverity.WARNING,
translation_key=translation_key,
translation_placeholders={**label, "options": "\n".join(options)},
learn_more_url="https://www.home-assistant.io/integrations/template/#weather",
learn_more_url=(
f"https://www.home-assistant.io/integrations/template/#{platform}"
),
)
# Repairs of entities in invalid sections can't be told apart from stale
+18 -6
View File
@@ -136,7 +136,6 @@
"target_temperature": "Defines a template for the target temperature.",
"temperature_unit": "[%key:component::template::common::temperature_unit_description%]"
},
"sections": {
"additional_options": {
"data": {
@@ -310,7 +309,7 @@
"set_level": "Actions on set level",
"set_temperature": "Actions on set color temperature",
"state": "[%key:component::template::common::state%]",
"temperature": "Color temperature",
"temperature_kelvin": "Color temperature",
"turn_off": "[%key:component::template::common::turn_off%]",
"turn_on": "[%key:component::template::common::turn_on%]"
},
@@ -322,7 +321,7 @@
"set_level": "Defines actions to run when the light is given a brightness command. The script will only be called if the `turn_on` call only has `brightness`, and optionally `transition`. Receives variables `brightness` and, optionally, `transition`.",
"set_temperature": "Defines actions to run when the light is given a color temperature command. Receives variable `color_temp_kelvin`. May also receive variables `brightness` and/or `transition`.",
"state": "The light is `on` if the template evaluates as `True`, `yes`, `on`, `enable` or a positive number. Any other value will render it as `off`.",
"temperature": "Defines a template to get the color temperature of the light.",
"temperature_kelvin": "Defines a template to get the color temperature of the light in kelvin.",
"turn_off": "Defines actions to run when the light is turned off.",
"turn_on": "Defines actions to run when the light is turned on."
},
@@ -769,6 +768,18 @@
"description": "A trigger template configuration needs a trigger and at least one domain when defining an entity. This will be a configuration validation error in Home Assistant Core 2026.5.\n\nPlease remove the orphaned trigger from the configuration.\n\n```\n{config}\n```",
"title": "Incomplete template configuration"
},
"deprecated_light_mireds_options": {
"description": "The template light entity with `{identifier}` uses options in mireds. These options are deprecated and will be removed in a future version of Home Assistant.\n\nUpdate your YAML configuration by replacing the following options and change their templates to render kelvin instead of mireds:\n\n{options}\n\nThe lowest mireds value is the highest kelvin value, so `min_mireds` is replaced by `max_kelvin` and `max_mireds` by `min_kelvin`.\n\nAfter updating the configuration, reload the template entities or restart Home Assistant to fix this issue.",
"title": "Template light entity uses deprecated options in mireds ({identifier})"
},
"deprecated_light_mireds_options_blueprint": {
"description": "The template light blueprint `{blueprint}` uses options in mireds. These options are deprecated and will be removed in a future version of Home Assistant.\n\nUpdate the blueprint by replacing the following options and change their templates to render kelvin instead of mireds:\n\n{options}\n\nThe lowest mireds value is the highest kelvin value, so `min_mireds` is replaced by `max_kelvin` and `max_mireds` by `min_kelvin`.\n\nIf the blueprint was imported, re-import it once its author has updated it instead. Then reload the template entities or restart Home Assistant to fix this issue.",
"title": "Template light blueprint uses deprecated options in mireds ({blueprint})"
},
"deprecated_light_temperature": {
"description": "The template light helper {name} defines its color temperature in mireds. This is deprecated and will stop working in Home Assistant Core {breaks_in_ha_version}.\n\nTo fix this issue, open the options of the template light helper and define the color temperature in kelvin, or remove the actions on set color temperature if the light should not support a color temperature.",
"title": "Template light helper {name} uses a color temperature in mireds"
},
"deprecated_weather_template_options": {
"description": "The template weather entity with `{identifier}` uses options ending in `_template`. These options are deprecated and will be removed in a future version of Home Assistant.\n\nUpdate your YAML configuration by renaming the following options:\n\n{options}\n\nAfter updating the configuration, reload the template entities or restart Home Assistant to fix this issue.",
"title": "Template weather entity uses deprecated options ({identifier})"
@@ -897,7 +908,6 @@
"target_temperature": "[%key:component::template::config::step::climate::data_description::target_temperature%]",
"temperature_unit": "[%key:component::template::common::temperature_unit_description%]"
},
"sections": {
"additional_options": {
"data": {
@@ -1064,7 +1074,8 @@
"set_level": "[%key:component::template::config::step::light::data::set_level%]",
"set_temperature": "[%key:component::template::config::step::light::data::set_temperature%]",
"state": "[%key:component::template::common::state%]",
"temperature": "[%key:component::template::config::step::light::data::temperature%]",
"temperature": "Color temperature in mireds (deprecated)",
"temperature_kelvin": "[%key:component::template::config::step::light::data::temperature_kelvin%]",
"turn_off": "[%key:component::template::common::turn_off%]",
"turn_on": "[%key:component::template::common::turn_on%]"
},
@@ -1076,7 +1087,8 @@
"set_level": "[%key:component::template::config::step::light::data_description::set_level%]",
"set_temperature": "[%key:component::template::config::step::light::data_description::set_temperature%]",
"state": "[%key:component::template::config::step::light::data_description::state%]",
"temperature": "[%key:component::template::config::step::light::data_description::temperature%]",
"temperature": "The color temperature template in mireds is deprecated and can no longer be changed. Define the color temperature in kelvin instead, or remove the actions on set color temperature, which removes this template.",
"temperature_kelvin": "[%key:component::template::config::step::light::data_description::temperature_kelvin%]",
"turn_off": "[%key:component::template::config::step::light::data_description::turn_off%]",
"turn_on": "[%key:component::template::config::step::light::data_description::turn_on%]"
},
@@ -4,6 +4,7 @@ from collections.abc import Callable
from enum import StrEnum
from itertools import chain
import logging
import math
from typing import Any
import probatio
@@ -321,25 +322,29 @@ def number(
if check_result_for_none(result, **kwargs):
return None
if (result_type := type(result)) is bool:
if type(result) is bool:
log_validation_result_error(entity, attribute, result, message)
return None
if isinstance(result, (float, int)):
value = result
if return_type is int and result_type is float:
value = int(value)
elif return_type is float and result_type is int:
value = float(value)
else:
try:
value = probatio.Coerce(float)(result)
if return_type is int:
value = int(value)
except probatio.Invalid:
log_validation_result_error(entity, attribute, result, message)
return None
# int() raises on NaN and infinity
if isinstance(value, float) and not math.isfinite(value):
log_validation_result_error(entity, attribute, result, message)
return None
if return_type is int and isinstance(value, float):
value = int(value)
elif return_type is float and isinstance(value, int):
value = float(value)
if minimum is None and maximum is None:
return value
+60 -24
View File
@@ -15,12 +15,15 @@ from homeassistant import config as hass_config
from homeassistant.components.template import DOMAIN
from homeassistant.components.template.config import (
CONFIG_SECTION_SCHEMA,
_merge_deprecated_options,
async_validate_config,
async_validate_config_section,
)
from homeassistant.components.template.const import PLATFORMS, TemplateService
from homeassistant.components.template.repairs import (
DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID,
from homeassistant.components.template.const import (
PLATFORMS,
WEATHER_DEPRECATED_OPTIONS,
DeprecatedTemplateOptions,
TemplateService,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import (
@@ -1514,7 +1517,7 @@ async def test_deprecated_template_options_issue_file_and_line(
await async_setup_yaml_config(hass, yaml_config_dir, WEATHER_LEGACY_YAML)
issues = get_issues_with_prefix(
issue_registry, DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID
issue_registry, WEATHER_DEPRECATED_OPTIONS.translation_key
)
assert [issue.translation_placeholders for issue in issues] == [
{"identifier": "name: Test", "options": legacy_options(4)},
@@ -1527,7 +1530,9 @@ async def test_deprecated_template_options_issue_file_and_line(
)
assert (
get_issues_with_prefix(issue_registry, DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID)
get_issues_with_prefix(
issue_registry, WEATHER_DEPRECATED_OPTIONS.translation_key
)
== []
)
@@ -1550,7 +1555,7 @@ async def test_deprecated_template_options_issue_per_entity(
)
issues = get_issues_with_prefix(
issue_registry, DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID
issue_registry, WEATHER_DEPRECATED_OPTIONS.translation_key
)
assert [issue.translation_placeholders for issue in issues] == [
{"identifier": "name: Test", "options": legacy_options(4)},
@@ -1566,7 +1571,7 @@ async def test_deprecated_template_options_issue_one_entity_fixed(
hass, yaml_config_dir, WEATHER_LEGACY_YAML + WEATHER_SECOND_LEGACY_YAML
)
issues = get_issues_with_prefix(
issue_registry, DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID
issue_registry, WEATHER_DEPRECATED_OPTIONS.translation_key
)
assert [issue.translation_placeholders for issue in issues] == [
{"identifier": "name: Test", "options": legacy_options(4)},
@@ -1583,7 +1588,7 @@ async def test_deprecated_template_options_issue_one_entity_fixed(
)
assert get_issues_with_prefix(
issue_registry, DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID
issue_registry, WEATHER_DEPRECATED_OPTIONS.translation_key
) == [second_issue]
@@ -1606,7 +1611,7 @@ template:
)
issues = get_issues_with_prefix(
issue_registry, DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID
issue_registry, WEATHER_DEPRECATED_OPTIONS.translation_key
)
assert [issue.translation_placeholders for issue in issues] == [
{"identifier": "unique_id: kitchen", "options": legacy_options(5)},
@@ -1637,7 +1642,7 @@ template:
)
issues = get_issues_with_prefix(
issue_registry, DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID
issue_registry, WEATHER_DEPRECATED_OPTIONS.translation_key
)
assert [issue.translation_placeholders for issue in issues] == [
{"identifier": "name: Test", "options": legacy_options(5)},
@@ -1666,7 +1671,7 @@ template:
)
assert get_issues_with_prefix(
issue_registry, DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID
issue_registry, WEATHER_DEPRECATED_OPTIONS.translation_key
) == [second_issue]
@@ -1676,7 +1681,7 @@ async def test_deprecated_template_options_issue_dismissed(
"""Test a dismissed repair stays dismissed until the configuration changes."""
await async_setup_yaml_config(hass, yaml_config_dir, WEATHER_LEGACY_YAML)
issues = get_issues_with_prefix(
issue_registry, DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID
issue_registry, WEATHER_DEPRECATED_OPTIONS.translation_key
)
assert len(issues) == 1
dismissed_issue_id = issues[0].issue_id
@@ -1686,7 +1691,7 @@ async def test_deprecated_template_options_issue_dismissed(
await async_reload_yaml_config(hass, yaml_config_dir, "\n" + WEATHER_LEGACY_YAML)
issues = get_issues_with_prefix(
issue_registry, DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID
issue_registry, WEATHER_DEPRECATED_OPTIONS.translation_key
)
assert len(issues) == 1
assert issues[0].issue_id == dismissed_issue_id
@@ -1697,7 +1702,7 @@ async def test_deprecated_template_options_issue_dismissed(
)
issues = get_issues_with_prefix(
issue_registry, DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID
issue_registry, WEATHER_DEPRECATED_OPTIONS.translation_key
)
assert len(issues) == 1
assert issues[0].issue_id != dismissed_issue_id
@@ -1710,7 +1715,7 @@ async def test_deprecated_template_options_issue_not_changed_by_config_check(
"""Test validating the configuration without reloading keeps the repair."""
await async_setup_yaml_config(hass, yaml_config_dir, WEATHER_LEGACY_YAML)
issues = get_issues_with_prefix(
issue_registry, DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID
issue_registry, WEATHER_DEPRECATED_OPTIONS.translation_key
)
assert len(issues) == 1
@@ -1723,7 +1728,9 @@ async def test_deprecated_template_options_issue_not_changed_by_config_check(
await async_validate_config(hass, fixed_config)
assert (
get_issues_with_prefix(issue_registry, DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID)
get_issues_with_prefix(
issue_registry, WEATHER_DEPRECATED_OPTIONS.translation_key
)
== issues
)
@@ -1755,7 +1762,7 @@ async def test_deprecated_template_options_issue_kept_with_invalid_section(
"""Test an invalid section doesn't delete repairs or their ignore flag."""
await async_setup_yaml_config(hass, yaml_config_dir, WEATHER_LEGACY_YAML)
issues = get_issues_with_prefix(
issue_registry, DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID
issue_registry, WEATHER_DEPRECATED_OPTIONS.translation_key
)
assert len(issues) == 1
issue_registry.async_ignore(DOMAIN, issues[0].issue_id, True)
@@ -1764,13 +1771,13 @@ async def test_deprecated_template_options_issue_kept_with_invalid_section(
await async_reload_yaml_config(hass, yaml_config_dir, invalid_yaml)
assert get_issues_with_prefix(
issue_registry, DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID
issue_registry, WEATHER_DEPRECATED_OPTIONS.translation_key
) == [issue]
await async_reload_yaml_config(hass, yaml_config_dir, WEATHER_LEGACY_YAML)
assert get_issues_with_prefix(
issue_registry, DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID
issue_registry, WEATHER_DEPRECATED_OPTIONS.translation_key
) == [issue]
@@ -1779,12 +1786,16 @@ async def test_deprecated_template_options_issue_removed_without_template_config
) -> None:
"""Test the repair is removed when the template configuration is removed."""
await async_setup_yaml_config(hass, yaml_config_dir, WEATHER_LEGACY_YAML)
assert get_issues_with_prefix(issue_registry, DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID)
assert get_issues_with_prefix(
issue_registry, WEATHER_DEPRECATED_OPTIONS.translation_key
)
await async_reload_yaml_config(hass, yaml_config_dir, "homeassistant:\n")
assert (
get_issues_with_prefix(issue_registry, DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID)
get_issues_with_prefix(
issue_registry, WEATHER_DEPRECATED_OPTIONS.translation_key
)
== []
)
@@ -1811,7 +1822,7 @@ template:
)
issues = get_issues_with_prefix(
issue_registry, DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID
issue_registry, WEATHER_DEPRECATED_OPTIONS.translation_key
)
assert [issue.translation_placeholders for issue in issues] == [
{
@@ -1841,7 +1852,7 @@ template:
)
remaining = get_issues_with_prefix(
issue_registry, DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID
issue_registry, WEATHER_DEPRECATED_OPTIONS.translation_key
)
assert [
(issue.issue_id, issue.dismissed_version, issue.translation_placeholders)
@@ -1882,11 +1893,36 @@ async def test_deprecated_template_options_issue_blueprint(
await hass.async_block_till_done()
assert (
get_issues_with_prefix(issue_registry, DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID)
get_issues_with_prefix(
issue_registry, WEATHER_DEPRECATED_OPTIONS.translation_key
)
== snapshot
)
def test_merge_deprecated_options_per_platform() -> None:
"""Test deprecations of the same platform all keep their option locations."""
deprecations = [
DeprecatedTemplateOptions(
platform=platform,
options=options,
translation_key=key,
blueprint_translation_key=f"{key}_blueprint",
breaks_in_ha_version="2027.6.0",
)
for platform, options, key in (
(Platform.LIGHT, {"temperature": "temperature_kelvin"}, "first"),
(Platform.LIGHT, {"level": "set_level"}, "second"),
(Platform.COVER, {"position": "set_cover_position"}, "third"),
)
]
assert _merge_deprecated_options(deprecations) == {
Platform.LIGHT: {"temperature", "level"},
Platform.COVER: {"position"},
}
async def test_option_locations_only_deprecated_options(
hass: HomeAssistant, yaml_config_dir: Path
) -> None:
@@ -1335,6 +1335,121 @@ async def test_options_remove_device_class(
assert "device_class" not in config_entry.options
LIGHT_OPTIONS = {
"name": "My template",
"template_type": "light",
"turn_on": [],
"turn_off": [],
"set_temperature": [],
}
def _get_schema_key(data_schema: probatio.Schema, key: str) -> probatio.Marker | None:
"""Return the marker of a key in a schema."""
return next((marker for marker in data_schema.schema if marker == key), None)
async def test_config_flow_light_temperature_kelvin(hass: HomeAssistant) -> None:
"""Test the light config flow only offers the color temperature in kelvin."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"next_step_id": "light"}
)
assert result["type"] is FlowResultType.FORM
assert _get_schema_key(result["data_schema"], "temperature_kelvin") is not None
assert _get_schema_key(result["data_schema"], "temperature") is None
async def test_options_light_without_temperature(hass: HomeAssistant) -> None:
"""Test the light options flow hides the temperature when it is not configured."""
config_entry = MockConfigEntry(
data={}, domain=DOMAIN, options=LIGHT_OPTIONS, title="My template"
)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
result = await hass.config_entries.options.async_init(config_entry.entry_id)
assert result["type"] is FlowResultType.FORM
assert _get_schema_key(result["data_schema"], "temperature_kelvin") is not None
assert _get_schema_key(result["data_schema"], "temperature") is None
@pytest.mark.parametrize(
("user_input", "expected_options"),
[
pytest.param(
{"set_temperature": []},
{"set_temperature": [], "temperature": "{{ 500 }}"},
id="keep_temperature",
),
pytest.param(
{"set_temperature": [], "temperature": "{{ 500 }}"},
{"set_temperature": [], "temperature": "{{ 500 }}"},
id="keep_submitted_temperature",
),
pytest.param(
{"set_temperature": [], "temperature_kelvin": "{{ 2000 }}"},
{"set_temperature": [], "temperature_kelvin": "{{ 2000 }}"},
id="replace_temperature",
),
pytest.param(
{
"set_temperature": [],
"temperature": "{{ 500 }}",
"temperature_kelvin": "{{ 2000 }}",
},
{"set_temperature": [], "temperature_kelvin": "{{ 2000 }}"},
id="replace_submitted_temperature",
),
pytest.param({}, {}, id="remove_temperature_action"),
pytest.param(
{"temperature": "{{ 500 }}"}, {}, id="remove_temperature_action_submitted"
),
],
)
async def test_options_light_deprecated_temperature(
hass: HomeAssistant,
user_input: dict[str, Any],
expected_options: dict[str, Any],
) -> None:
"""Test the deprecated light temperature is read only in the options flow."""
config_entry = MockConfigEntry(
data={},
domain=DOMAIN,
options={**LIGHT_OPTIONS, "temperature": "{{ 500 }}"},
title="My template",
)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
result = await hass.config_entries.options.async_init(config_entry.entry_id)
assert result["type"] is FlowResultType.FORM
data_schema = result["data_schema"]
temperature_key = _get_schema_key(data_schema, "temperature")
assert temperature_key is not None
assert data_schema.schema[temperature_key].config["read_only"] is True
assert get_schema_suggested_value(data_schema.schema, "temperature") == (
"{{ 500 }}"
)
result = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input={"turn_on": [], "turn_off": [], **user_input},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert config_entry.options == {
"name": "My template",
"template_type": "light",
"turn_on": [],
"turn_off": [],
**expected_options,
}
def _assert_number_unit_of_measurement_context(data_schema: probatio.Schema) -> None:
"""Assert the unit of measurement selector is filtered by the device class."""
# Serialize the form the way it is sent to the frontend
@@ -2161,6 +2276,46 @@ async def test_option_flow_preview(
assert len(hass.states.async_all()) == 3
async def test_option_flow_preview_light_deprecated_temperature(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test the options flow preview of a light helper with a temperature in mireds."""
client = await hass_ws_client(hass)
config_entry = MockConfigEntry(
data={},
domain=DOMAIN,
options={**LIGHT_OPTIONS, "temperature": "{{ 500 }}"},
title="My template",
)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
result = await hass.config_entries.options.async_init(config_entry.entry_id)
assert result["preview"] == "template"
await client.send_json_auto_id(
{
"type": "template/start_preview",
"flow_id": result["flow_id"],
"flow_type": "options_flow",
"user_input": {
"state": "{{ true }}",
"turn_on": [],
"turn_off": [],
"set_temperature": [],
"temperature": "{{ 500 }}",
},
}
)
msg = await client.receive_json()
assert msg["success"]
msg = await client.receive_json()
assert msg["event"]["state"] == "on"
assert msg["event"]["attributes"]["color_temp_kelvin"] == 2000
async def test_option_flow_sensor_preview_config_entry_removed(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
+770 -2
View File
@@ -2,7 +2,9 @@
from enum import StrEnum
from itertools import chain
from pathlib import Path
from typing import Any
from unittest.mock import patch
import pytest
from pytest_homeassistant.common import (
@@ -12,6 +14,7 @@ from pytest_homeassistant.common import (
from pytest_homeassistant.typing import WebSocketGenerator
from syrupy.assertion import SnapshotAssertion
from homeassistant import config as hass_config
from homeassistant.components import light, template
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
@@ -29,7 +32,17 @@ from homeassistant.components.light import (
LightEntityFeature,
LightEntityStateAttribute,
)
from homeassistant.components.template.light import DEFAULT_NAME
from homeassistant.components.template.config import async_validate_config
from homeassistant.components.template.const import (
LIGHT_DEPRECATED_OPTIONS,
WEATHER_DEPRECATED_OPTIONS,
DeprecatedTemplateOptions,
TemplateService,
)
from homeassistant.components.template.light import (
DEFAULT_NAME,
DEPRECATED_TEMPERATURE_ISSUE_ID,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
@@ -40,9 +53,11 @@ from homeassistant.const import (
STATE_UNKNOWN,
)
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers import entity_registry as er, issue_registry as ir
from homeassistant.helpers.restore_state import STORAGE_KEY as RESTORE_STATE_KEY
from homeassistant.helpers.typing import ConfigType
from homeassistant.setup import async_setup_component
from homeassistant.util.yaml import load_yaml_dict
from .conftest import (
ConfigurationStyle,
@@ -55,6 +70,7 @@ from .conftest import (
assert_state_and_attributes,
async_get_flow_preview_state,
async_trigger,
get_issues_with_prefix,
make_test_action,
make_test_trigger,
setup_and_test_nested_unique_id,
@@ -353,6 +369,30 @@ async def setup_light_with_mireds(
)
@pytest.fixture
async def setup_light_with_kelvin(
hass: HomeAssistant,
count: int,
style: ConfigurationStyle,
attribute: str,
attribute_template: str,
) -> None:
"""Do setup of light that uses kelvin."""
await setup_entity(
hass,
TEST_LIGHT,
style,
count,
{
attribute: attribute_template,
"temperature_kelvin": "{{ 3000 }}",
**COLOR_TEMP_ACTION,
},
"{{ 1==1 }}",
ON_OFF_ACTIONS,
)
@pytest.fixture
async def setup_light_with_transition_template(
hass: HomeAssistant,
@@ -748,6 +788,7 @@ async def test_level_action_no_template(
(255, "{{255}}", ColorMode.BRIGHTNESS),
(None, "{{256}}", ColorMode.BRIGHTNESS),
(None, "{{x - 12}}", ColorMode.BRIGHTNESS),
(None, "{{ '1' * 400 }}", ColorMode.BRIGHTNESS),
(None, "{{ none }}", ColorMode.BRIGHTNESS),
(None, "", ColorMode.BRIGHTNESS),
(
@@ -811,6 +852,363 @@ async def test_temperature_template(
assert state.attributes["supported_features"] == 0
@pytest.mark.parametrize(("count", "extra_config"), [(1, ON_OFF_COLOR_TEMP_ACTIONS)])
@pytest.mark.parametrize(
("style", "attribute"),
[
(ConfigurationStyle.MODERN, "temperature_kelvin"),
(ConfigurationStyle.TRIGGER, "temperature_kelvin"),
],
)
@pytest.mark.parametrize(
("expected_temp", "attribute_template"),
[
(2000, "{{ 2000 }}"),
(6535, "{{ 6535 }}"),
(3000, "{{ 3000.4 }}"),
(2701, "{{ 2700.9 }}"),
(None, "{{ 1999 }}"),
(None, "{{ 6536 }}"),
(None, "{{ true }}"),
(None, "{{ x - 12 }}"),
(None, "None"),
(None, "{{ none }}"),
(None, ""),
(None, "{{ 'one' }}"),
],
)
@pytest.mark.usefixtures("setup_single_attribute_light")
async def test_temperature_kelvin_template(
hass: HomeAssistant, expected_temp: int | None
) -> None:
"""Test the template for the temperature in kelvin."""
await async_trigger(hass, TEST_STATE_ENTITY_ID, STATE_ON)
state = hass.states.get(TEST_LIGHT.entity_id)
assert state.attributes.get("color_temp_kelvin") == expected_temp
assert state.state == STATE_ON
assert state.attributes.get("color_mode") == ColorMode.COLOR_TEMP
assert state.attributes["supported_color_modes"] == [ColorMode.COLOR_TEMP]
@pytest.mark.parametrize("count", [1])
@pytest.mark.parametrize(
"style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER]
)
@pytest.mark.parametrize(
("config", "expected_temp"),
[
pytest.param(
{"temperature_kelvin": "{{ 1600 }}", "min_kelvin": "{{ 1500 }}"},
1600,
id="below_default_min",
),
pytest.param(
{"temperature_kelvin": "{{ 9000 }}", "max_kelvin": "{{ 10000 }}"},
9000,
id="above_default_max",
),
pytest.param(
{"temperature_kelvin": "{{ 2500 }}", "min_kelvin": "{{ 3000 }}"},
None,
id="below_min",
),
pytest.param(
{"temperature": "{{ 500 }}", "temperature_kelvin": "{{ 3000 }}"},
3000,
id="kelvin_over_mireds",
),
],
)
async def test_temperature_kelvin_range(
hass: HomeAssistant,
count: int,
style: ConfigurationStyle,
config: ConfigType,
expected_temp: int | None,
) -> None:
"""Test the temperature in kelvin against the configured range."""
await setup_entity(
hass, TEST_LIGHT, style, count, config, "{{ 1==1 }}", ON_OFF_COLOR_TEMP_ACTIONS
)
await async_trigger(hass, TEST_STATE_ENTITY_ID, STATE_ON)
state = hass.states.get(TEST_LIGHT.entity_id)
assert state.attributes.get("color_temp_kelvin") == expected_temp
@pytest.mark.parametrize("count", [0])
@pytest.mark.parametrize(
"style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER]
)
@pytest.mark.parametrize(
"config",
[
{"min_mireds": "{{ 153 }}", "min_kelvin": "{{ 2000 }}"},
{"min_mireds": "{{ 153 }}", "max_kelvin": "{{ 6500 }}"},
{"max_mireds": "{{ 500 }}", "min_kelvin": "{{ 2000 }}"},
{"max_mireds": "{{ 500 }}", "max_kelvin": "{{ 6500 }}"},
],
)
async def test_mireds_and_kelvin_range_invalid(
hass: HomeAssistant,
count: int,
style: ConfigurationStyle,
config: ConfigType,
) -> None:
"""Test the color temperature range can not mix mireds and kelvin."""
await setup_entity(
hass, TEST_LIGHT, style, count, config, "{{ 1==1 }}", ON_OFF_COLOR_TEMP_ACTIONS
)
assert hass.states.get(TEST_LIGHT.entity_id) is None
def get_deprecated_mireds_options_issues(
issue_registry: ir.IssueRegistry,
) -> list[ir.IssueEntry]:
"""Return the deprecated light mireds options issues."""
return get_issues_with_prefix(
issue_registry, LIGHT_DEPRECATED_OPTIONS.translation_key
)
@pytest.mark.parametrize("count", [1])
@pytest.mark.parametrize(
"style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER]
)
@pytest.mark.parametrize(
("config", "options"),
[
pytest.param(
{"temperature": "{{ 500 }}"},
"- `temperature` → `temperature_kelvin`",
id="temperature",
),
pytest.param(
{"temperature": "{{ 500 }}", "temperature_kelvin": "{{ 2000 }}"},
"- `temperature` → `temperature_kelvin`",
id="temperature_and_kelvin",
),
pytest.param(
{"min_mireds": "{{ 153 }}", "max_mireds": "{{ 500 }}"},
"- `min_mireds` → `max_kelvin`\n- `max_mireds` → `min_kelvin`",
id="mireds_range",
),
],
)
async def test_deprecated_mireds_options_issue(
hass: HomeAssistant,
issue_registry: ir.IssueRegistry,
count: int,
style: ConfigurationStyle,
config: ConfigType,
options: str,
) -> None:
"""Test a repair issue is created for options in mireds."""
await setup_entity(
hass, TEST_LIGHT, style, count, config, "{{ 1==1 }}", ON_OFF_COLOR_TEMP_ACTIONS
)
issues = get_deprecated_mireds_options_issues(issue_registry)
assert len(issues) == 1
assert issues[0].breaks_in_ha_version == "2027.6.0"
assert issues[0].is_fixable is False
assert issues[0].severity == ir.IssueSeverity.WARNING
assert issues[0].learn_more_url == (
"https://www.home-assistant.io/integrations/template/#light"
)
assert issues[0].translation_key == LIGHT_DEPRECATED_OPTIONS.translation_key
assert issues[0].translation_placeholders == {
"identifier": f"name: {TEST_LIGHT.object_id}",
"options": options,
}
@pytest.mark.parametrize("count", [1])
@pytest.mark.parametrize(
"style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER]
)
@pytest.mark.parametrize(
"config",
[
{
"temperature_kelvin": "{{ 3000 }}",
"min_kelvin": "{{ 2000 }}",
"max_kelvin": "{{ 6500 }}",
}
],
)
async def test_no_deprecated_mireds_options_issue(
hass: HomeAssistant,
issue_registry: ir.IssueRegistry,
count: int,
style: ConfigurationStyle,
config: ConfigType,
) -> None:
"""Test no repair issue is created for options in kelvin."""
await setup_entity(
hass, TEST_LIGHT, style, count, config, "{{ 1==1 }}", ON_OFF_COLOR_TEMP_ACTIONS
)
assert get_deprecated_mireds_options_issues(issue_registry) == []
MIREDS_YAML = """\
template:
- light:
- name: Test
turn_on: []
turn_off: []
set_temperature: []
temperature: "{{ 500 }}"
max_mireds: "{{ 500 }}"
"""
KELVIN_YAML = """\
template:
- light:
- name: Test
turn_on: []
turn_off: []
set_temperature: []
temperature_kelvin: "{{ 2000 }}"
min_kelvin: "{{ 2000 }}"
"""
WEATHER_LEGACY_YAML = """\
- weather:
- name: Weather
condition_template: sunny
temperature_template: "{{ 20 }}"
humidity_template: "{{ 25 }}"
"""
async def _async_setup_yaml(hass: HomeAssistant, yaml_path: Path, yaml: str) -> None:
"""Write configuration.yaml and set up the template integration from it."""
await hass.async_add_executor_job(yaml_path.write_text, yaml)
config = await hass.async_add_executor_job(load_yaml_dict, yaml_path)
assert await async_setup_component(hass, template.DOMAIN, config)
await hass.async_block_till_done()
async def _async_reload_yaml(hass: HomeAssistant, yaml_path: Path, yaml: str) -> None:
"""Write configuration.yaml and reload the template entities from it."""
await hass.async_add_executor_job(yaml_path.write_text, yaml)
with patch.object(hass_config, "YAML_CONFIG_FILE", str(yaml_path)):
await hass.services.async_call(
template.DOMAIN, TemplateService.RELOAD, blocking=True
)
await hass.async_block_till_done()
async def test_deprecated_mireds_options_issue_file_and_line(
hass: HomeAssistant, issue_registry: ir.IssueRegistry, tmp_path: Path
) -> None:
"""Test the repair lists file and line, and is removed after a fix."""
hass.config.config_dir = str(tmp_path)
yaml_path = tmp_path / "configuration.yaml"
await _async_setup_yaml(hass, yaml_path, MIREDS_YAML)
issues = get_deprecated_mireds_options_issues(issue_registry)
assert len(issues) == 1
assert issues[0].translation_placeholders == {
"identifier": "name: Test",
"options": (
"- `configuration.yaml:7`: `temperature` → `temperature_kelvin`\n"
"- `configuration.yaml:8`: `max_mireds` → `min_kelvin`"
),
}
await _async_reload_yaml(hass, yaml_path, KELVIN_YAML)
assert get_deprecated_mireds_options_issues(issue_registry) == []
async def test_deprecated_mireds_options_issue_not_changed_by_config_check(
hass: HomeAssistant, issue_registry: ir.IssueRegistry, tmp_path: Path
) -> None:
"""Test validating the configuration alone does not create or remove repairs."""
hass.config.config_dir = str(tmp_path)
yaml_path = tmp_path / "configuration.yaml"
await _async_setup_yaml(hass, yaml_path, MIREDS_YAML)
issues = get_deprecated_mireds_options_issues(issue_registry)
assert len(issues) == 1
await hass.async_add_executor_job(yaml_path.write_text, KELVIN_YAML)
config = await hass.async_add_executor_job(load_yaml_dict, yaml_path)
await async_validate_config(hass, config)
assert get_deprecated_mireds_options_issues(issue_registry) == issues
async def test_deprecated_options_issues_per_platform(
hass: HomeAssistant, issue_registry: ir.IssueRegistry, tmp_path: Path
) -> None:
"""Test fixing the light options keeps the weather repair, and the reverse."""
hass.config.config_dir = str(tmp_path)
yaml_path = tmp_path / "configuration.yaml"
def issue_ids(deprecation: DeprecatedTemplateOptions) -> list[str]:
return [
issue.issue_id
for issue in get_issues_with_prefix(
issue_registry, deprecation.translation_key
)
]
await _async_setup_yaml(hass, yaml_path, MIREDS_YAML + WEATHER_LEGACY_YAML)
light_issue_ids = issue_ids(LIGHT_DEPRECATED_OPTIONS)
weather_issue_ids = issue_ids(WEATHER_DEPRECATED_OPTIONS)
assert len(light_issue_ids) == 1
assert len(weather_issue_ids) == 1
await _async_reload_yaml(hass, yaml_path, KELVIN_YAML + WEATHER_LEGACY_YAML)
assert issue_ids(LIGHT_DEPRECATED_OPTIONS) == []
assert issue_ids(WEATHER_DEPRECATED_OPTIONS) == weather_issue_ids
await _async_reload_yaml(hass, yaml_path, MIREDS_YAML)
assert issue_ids(LIGHT_DEPRECATED_OPTIONS) == light_issue_ids
assert issue_ids(WEATHER_DEPRECATED_OPTIONS) == []
async def test_deprecated_mireds_options_issue_blueprint(
hass: HomeAssistant, issue_registry: ir.IssueRegistry
) -> None:
"""Test all instances of a light blueprint share one repair."""
assert await async_setup_component(
hass,
template.DOMAIN,
{
template.DOMAIN: [
{
"use_blueprint": {
"path": "test_light_with_mireds.yaml",
"input": {"sensor": sensor},
},
"name": name,
}
for sensor, name in (
("sensor.first", "First"),
("sensor.second", "Second"),
)
]
},
)
await hass.async_block_till_done()
issues = get_deprecated_mireds_options_issues(issue_registry)
assert len(issues) == 1
assert (
issues[0].translation_key == LIGHT_DEPRECATED_OPTIONS.blueprint_translation_key
)
assert issues[0].translation_placeholders == {
"blueprint": "test_light_with_mireds.yaml",
"options": (
"- `blueprints/template/test_light_with_mireds.yaml:19`: "
"`temperature` → `temperature_kelvin`\n"
"- `blueprints/template/test_light_with_mireds.yaml:20`: "
"`max_mireds` → `min_kelvin`"
),
}
@pytest.mark.parametrize(("count", "extra_config"), [(1, ON_OFF_COLOR_TEMP_ACTIONS)])
@pytest.mark.parametrize(
"style",
@@ -1486,6 +1884,11 @@ async def test_effect_template(
("expected_max_kelvin", "attribute_template"),
[
(8474, "{{118}}"),
(6535, "{{ 1000001 }}"),
(6535, "{{ 0 }}"),
(6535, "{{ -5 }}"),
(6535, "{{ 'nan' | float }}"),
(6535, "{{ 'inf' | float }}"),
(6535, "{{x - 12}}"),
(6535, "None"),
(6535, "{{ none }}"),
@@ -1516,6 +1919,12 @@ async def test_min_mireds_template(
("expected_min_kelvin", "attribute_template"),
[
(2049, "{{488}}"),
(1, "{{ 1000000 }}"),
(2000, "{{ 1000001 }}"),
(2000, "{{ 0 }}"),
(2000, "{{ -5 }}"),
(2000, "{{ 'nan' | float }}"),
(2000, "{{ 'inf' | float }}"),
(2000, "{{x - 12}}"),
(2000, "None"),
(2000, "{{ none }}"),
@@ -1535,6 +1944,284 @@ async def test_max_mireds_template(
assert state.attributes.get("min_color_temp_kelvin") == expected_min_kelvin
@pytest.mark.parametrize("count", [1])
@pytest.mark.parametrize(
("style", "attribute"),
[
(ConfigurationStyle.MODERN, "min_kelvin"),
(ConfigurationStyle.TRIGGER, "min_kelvin"),
],
)
@pytest.mark.parametrize(
("expected_min_kelvin", "attribute_template"),
[
(2500, "{{ 2500 }}"),
(2000, "{{ 0 }}"),
(2000, "{{ -5 }}"),
(2000, "{{ 'nan' | float }}"),
(2000, "{{ 'inf' | float }}"),
(2000, "{{ x - 12 }}"),
(2000, "None"),
(2000, "{{ none }}"),
(2000, ""),
(2000, "{{ 'a' }}"),
],
)
@pytest.mark.usefixtures("setup_light_with_kelvin")
async def test_min_kelvin_template(
hass: HomeAssistant, expected_min_kelvin: int
) -> None:
"""Test the template for the min kelvin."""
await async_trigger(hass, TEST_STATE_ENTITY_ID, STATE_ON)
state = hass.states.get(TEST_LIGHT.entity_id)
assert state is not None
assert state.attributes.get("min_color_temp_kelvin") == expected_min_kelvin
@pytest.mark.parametrize("count", [1])
@pytest.mark.parametrize(
("style", "attribute"),
[
(ConfigurationStyle.MODERN, "max_kelvin"),
(ConfigurationStyle.TRIGGER, "max_kelvin"),
],
)
@pytest.mark.parametrize(
("expected_max_kelvin", "attribute_template"),
[
(5000, "{{ 5000 }}"),
(6535, "{{ 0 }}"),
(6535, "{{ -5 }}"),
(6535, "{{ 'nan' | float }}"),
(6535, "{{ 'inf' | float }}"),
(6535, "{{ x - 12 }}"),
(6535, "None"),
(6535, "{{ none }}"),
(6535, ""),
(6535, "{{ 'a' }}"),
],
)
@pytest.mark.usefixtures("setup_light_with_kelvin")
async def test_max_kelvin_template(
hass: HomeAssistant, expected_max_kelvin: int
) -> None:
"""Test the template for the max kelvin."""
await async_trigger(hass, TEST_STATE_ENTITY_ID, STATE_ON)
state = hass.states.get(TEST_LIGHT.entity_id)
assert state is not None
assert state.attributes.get("max_color_temp_kelvin") == expected_max_kelvin
@pytest.mark.parametrize("count", [1])
@pytest.mark.parametrize(
"style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER]
)
@pytest.mark.parametrize(
"option", ["min_mireds", "max_mireds", "min_kelvin", "max_kelvin"]
)
@pytest.mark.parametrize(
"value",
[
pytest.param("{{ x - 12 }}", id="template_error"),
pytest.param("{{ 0 }}", id="zero"),
pytest.param("{{ 'inf' | float }}", id="infinity"),
],
)
async def test_color_temp_range_template_error_rgbww(
hass: HomeAssistant,
count: int,
style: ConfigurationStyle,
option: str,
value: str,
) -> None:
"""Test an invalid range keeps the light working in RGBWW mode."""
await setup_entity(
hass,
TEST_LIGHT,
style,
count,
{
option: value,
"rgbww": "{{ (255, 0, 0, 10, 10) }}",
**RGBWW_ACTION,
**COLOR_TEMP_ACTION,
},
"{{ 1==1 }}",
ON_OFF_ACTIONS,
)
await async_trigger(hass, TEST_STATE_ENTITY_ID, STATE_ON)
state = hass.states.get(TEST_LIGHT.entity_id)
assert state is not None
assert state.state == STATE_ON
assert state.attributes["color_mode"] == ColorMode.RGBWW
assert state.attributes["min_color_temp_kelvin"] == 2000
assert state.attributes["max_color_temp_kelvin"] == 6535
@pytest.mark.parametrize("count", [1])
@pytest.mark.parametrize(
"style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER]
)
@pytest.mark.parametrize(
("config", "first_bound", "second_bound"),
[
pytest.param(
{
"temperature_kelvin": "{{ 2500 }}",
"min_kelvin": "{{ states('sensor.bound') | int }}",
},
3000,
2000,
id="kelvin",
),
pytest.param(
{
"temperature": "{{ 400 }}",
"max_mireds": "{{ states('sensor.bound') | int }}",
},
333,
500,
id="mireds",
),
],
)
async def test_temperature_revalidated_when_range_changes(
hass: HomeAssistant,
count: int,
style: ConfigurationStyle,
config: ConfigType,
first_bound: int,
second_bound: int,
) -> None:
"""Test the temperature is revalidated when the range widens and narrows."""
hass.states.async_set("sensor.bound", str(first_bound))
await setup_entity(
hass, TEST_LIGHT, style, count, config, "{{ 1==1 }}", ON_OFF_COLOR_TEMP_ACTIONS
)
await async_trigger(hass, TEST_STATE_ENTITY_ID, STATE_ON)
state = hass.states.get(TEST_LIGHT.entity_id)
assert state.attributes["color_temp_kelvin"] is None
# The unchanged temperature becomes valid when the range widens
hass.states.async_set("sensor.bound", str(second_bound))
await async_trigger(hass, TEST_STATE_ENTITY_ID, STATE_OFF)
state = hass.states.get(TEST_LIGHT.entity_id)
assert state.attributes["color_temp_kelvin"] == 2500
# And invalid again when the range narrows
hass.states.async_set("sensor.bound", str(first_bound))
await async_trigger(hass, TEST_STATE_ENTITY_ID, STATE_ON)
state = hass.states.get(TEST_LIGHT.entity_id)
assert state.attributes["color_temp_kelvin"] is None
@pytest.mark.parametrize(
"style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER]
)
async def test_inverted_color_temp_range(
hass: HomeAssistant, style: ConfigurationStyle, caplog: pytest.LogCaptureFixture
) -> None:
"""Test an inverted range falls back to the default range and warns once."""
await setup_entity(
hass,
TEST_LIGHT,
style,
1,
{
"temperature_kelvin": "{{ 4000 }}",
"min_kelvin": "{{ 6000 }}",
"max_kelvin": "{{ 3000 }}",
},
"{{ 1==1 }}",
ON_OFF_COLOR_TEMP_ACTIONS,
)
await async_trigger(hass, TEST_STATE_ENTITY_ID, STATE_ON)
await async_trigger(hass, TEST_STATE_ENTITY_ID, STATE_OFF)
state = hass.states.get(TEST_LIGHT.entity_id)
assert state.attributes["min_color_temp_kelvin"] == 2000
assert state.attributes["max_color_temp_kelvin"] == 6535
assert state.attributes["color_temp_kelvin"] == 4000
assert caplog.text.count("color temperature range of light.test_light") == 1
async def test_color_temp_range_moved_past_old_range(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test moving the whole range does not warn while one bound is updated."""
hass.states.async_set("sensor.bound", "2000")
await setup_entity(
hass,
TEST_LIGHT,
ConfigurationStyle.MODERN,
1,
{
"temperature_kelvin": "{{ 4500 }}",
"min_kelvin": "{{ states('sensor.bound') | int }}",
"max_kelvin": "{{ states('sensor.bound') | int + 1000 }}",
},
"{{ 1==1 }}",
ON_OFF_COLOR_TEMP_ACTIONS,
)
await async_trigger(hass, TEST_STATE_ENTITY_ID, STATE_ON)
assert hass.states.get(TEST_LIGHT.entity_id).attributes["color_temp_kelvin"] is None
hass.states.async_set("sensor.bound", "4000")
await hass.async_block_till_done()
state = hass.states.get(TEST_LIGHT.entity_id)
assert state.attributes["min_color_temp_kelvin"] == 4000
assert state.attributes["max_color_temp_kelvin"] == 5000
assert state.attributes["color_temp_kelvin"] == 4500
assert "color temperature range" not in caplog.text
@pytest.mark.parametrize(
("hs_template", "first_mode", "expected_mode", "expected_temp"),
[
pytest.param(
"{{ none }}", ColorMode.UNKNOWN, ColorMode.COLOR_TEMP, 2500, id="unknown"
),
pytest.param(
"{{ (360, 100) }}", ColorMode.HS, ColorMode.HS, None, id="keep_hs"
),
],
)
async def test_temperature_revalidated_color_mode(
hass: HomeAssistant,
hs_template: str,
first_mode: ColorMode,
expected_mode: ColorMode,
expected_temp: int | None,
) -> None:
"""Test the color mode when the range widens on a multi color mode light."""
hass.states.async_set("sensor.bound", "3000")
await setup_entity(
hass,
TEST_LIGHT,
ConfigurationStyle.MODERN,
1,
{
"temperature_kelvin": "{{ 2500 }}",
"min_kelvin": "{{ states('sensor.bound') | int }}",
"hs": hs_template,
**HS_ACTION,
},
"{{ 1==1 }}",
ON_OFF_COLOR_TEMP_ACTIONS,
)
await async_trigger(hass, TEST_STATE_ENTITY_ID, STATE_ON)
state = hass.states.get(TEST_LIGHT.entity_id)
assert state.attributes["color_mode"] == first_mode
assert state.attributes.get("color_temp_kelvin") is None
hass.states.async_set("sensor.bound", "2000")
await hass.async_block_till_done()
state = hass.states.get(TEST_LIGHT.entity_id)
assert state.attributes["color_mode"] == expected_mode
assert state.attributes.get("color_temp_kelvin") == expected_temp
@pytest.mark.parametrize(("count", "extra_config"), [(1, ON_OFF_COLOR_TEMP_ACTIONS)])
@pytest.mark.parametrize(
("style", "attribute"),
@@ -1891,6 +2578,87 @@ async def test_setup_config_entry(
assert state == snapshot
async def _async_setup_light_config_entry(
hass: HomeAssistant, options: dict[str, Any]
) -> MockConfigEntry:
"""Set up a template light config entry."""
config_entry = MockConfigEntry(
data={},
domain=template.DOMAIN,
options={
"name": "My template",
"turn_on": [],
"turn_off": [],
"set_temperature": [],
"template_type": light.DOMAIN,
**options,
},
title="My template",
)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
return config_entry
async def test_deprecated_temperature_config_entry_issue(
hass: HomeAssistant, issue_registry: ir.IssueRegistry
) -> None:
"""Test a repair issue is tied to a helper that uses the temperature option."""
config_entry = await _async_setup_light_config_entry(
hass, {"temperature": "{{ 500 }}"}
)
issue_id = f"{DEPRECATED_TEMPERATURE_ISSUE_ID}_{config_entry.entry_id}"
issue = issue_registry.async_get_issue(template.DOMAIN, issue_id)
assert issue is not None
assert issue.breaks_in_ha_version == "2027.6.0"
assert issue.config_entry_id == config_entry.entry_id
assert issue.translation_key == DEPRECATED_TEMPERATURE_ISSUE_ID
assert issue.translation_placeholders == {
"name": "My template",
"breaks_in_ha_version": "2027.6.0",
}
# Replacing the option with temperature_kelvin removes the issue
options = {**config_entry.options, "temperature_kelvin": "{{ 2000 }}"}
options.pop("temperature")
hass.config_entries.async_update_entry(config_entry, options=options)
assert await hass.config_entries.async_reload(config_entry.entry_id)
await hass.async_block_till_done()
assert issue_registry.async_get_issue(template.DOMAIN, issue_id) is None
async def test_deprecated_temperature_config_entry_removed(
hass: HomeAssistant, issue_registry: ir.IssueRegistry
) -> None:
"""Test the repair issue is removed with the helper."""
config_entry = await _async_setup_light_config_entry(
hass, {"temperature": "{{ 500 }}"}
)
issue_id = f"{DEPRECATED_TEMPERATURE_ISSUE_ID}_{config_entry.entry_id}"
assert issue_registry.async_get_issue(template.DOMAIN, issue_id) is not None
assert await hass.config_entries.async_remove(config_entry.entry_id)
await hass.async_block_till_done()
assert issue_registry.async_get_issue(template.DOMAIN, issue_id) is None
async def test_no_deprecated_temperature_config_entry_issue(
hass: HomeAssistant, issue_registry: ir.IssueRegistry
) -> None:
"""Test no repair issue is created for a helper using kelvin."""
config_entry = await _async_setup_light_config_entry(
hass, {"temperature_kelvin": "{{ 3000 }}"}
)
assert (
issue_registry.async_get_issue(
template.DOMAIN,
f"{DEPRECATED_TEMPERATURE_ISSUE_ID}_{config_entry.entry_id}",
)
is None
)
async def test_flow_preview(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
@@ -1,5 +1,6 @@
"""Test template validators."""
import math
from typing import Any
import pytest
@@ -563,6 +564,12 @@ async def test_boolean_as_false(
{"junk"},
[],
["stuff"],
"nan",
"inf",
"-inf",
math.nan,
math.inf,
-math.inf,
),
],
)
@@ -606,6 +613,7 @@ async def test_number_as_float(
(0.0, 0),
(-324.4564, -324),
(1, 1),
pytest.param(10**400, 10**400, id="huge_int"),
*expect_none(
None,
"al;dfj",
@@ -619,6 +627,12 @@ async def test_number_as_float(
{"junk"},
[],
["stuff"],
"nan",
"inf",
"-inf",
math.nan,
math.inf,
-math.inf,
),
],
)
+7 -4
View File
@@ -14,9 +14,10 @@ from pytest_homeassistant.typing import WebSocketGenerator
from syrupy.assertion import SnapshotAssertion
from homeassistant.components import template
from homeassistant.components.template.const import CONF_PICTURE, DOMAIN
from homeassistant.components.template.repairs import (
DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID,
from homeassistant.components.template.const import (
CONF_PICTURE,
DOMAIN,
WEATHER_DEPRECATED_OPTIONS,
)
from homeassistant.components.template.weather import DEFAULT_NAME
from homeassistant.components.weather import (
@@ -1143,6 +1144,8 @@ async def test_deprecated_template_options_issue(
) -> None:
"""Test a repair issue is created only for deprecated *_template options."""
assert (
get_issues_with_prefix(issue_registry, DEPRECATED_TEMPLATE_OPTIONS_ISSUE_ID)
get_issues_with_prefix(
issue_registry, WEATHER_DEPRECATED_OPTIONS.translation_key
)
== snapshot
)
@@ -0,0 +1,20 @@
blueprint:
name: Test light with mireds
description: Creates a light with a color temperature in mireds
domain: template
input:
sensor:
name: Sensor Entity
description: The sensor entity
selector:
entity:
domain: sensor
variables:
sensor: !input sensor
light:
state: "{{ is_state(sensor, 'on') }}"
turn_on: []
turn_off: []
set_temperature: []
temperature: "{{ 300 }}"
max_mireds: "{{ 500 }}"