From c7cf9585aedcd9daca06e8334f9aa9d9c9c7889f Mon Sep 17 00:00:00 2001 From: Petro31 <35082313+Petro31@users.noreply.github.com> Date: Thu, 15 May 2025 02:18:37 -0400 Subject: [PATCH] Add modern style configuration for template fan (#144751) * add modern template fan * address comments and add tests for coverage --- homeassistant/components/template/config.py | 9 +- homeassistant/components/template/fan.py | 153 +- tests/components/template/test_fan.py | 1886 +++++++++++-------- 3 files changed, 1218 insertions(+), 830 deletions(-) diff --git a/homeassistant/components/template/config.py b/homeassistant/components/template/config.py index ca643653cec..5e7425f13d7 100644 --- a/homeassistant/components/template/config.py +++ b/homeassistant/components/template/config.py @@ -14,6 +14,7 @@ from homeassistant.components.blueprint import ( ) from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN from homeassistant.components.cover import DOMAIN as COVER_DOMAIN +from homeassistant.components.fan import DOMAIN as FAN_DOMAIN from homeassistant.components.image import DOMAIN as IMAGE_DOMAIN from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN from homeassistant.components.number import DOMAIN as NUMBER_DOMAIN @@ -46,6 +47,7 @@ from . import ( binary_sensor as binary_sensor_platform, button as button_platform, cover as cover_platform, + fan as fan_platform, image as image_platform, light as light_platform, number as number_platform, @@ -131,9 +133,14 @@ CONFIG_SECTION_SCHEMA = vol.All( vol.Optional(COVER_DOMAIN): vol.All( cv.ensure_list, [cover_platform.COVER_SCHEMA] ), + vol.Optional(FAN_DOMAIN): vol.All( + cv.ensure_list, [fan_platform.FAN_SCHEMA] + ), }, ), - ensure_domains_do_not_have_trigger_or_action(BUTTON_DOMAIN, COVER_DOMAIN), + ensure_domains_do_not_have_trigger_or_action( + BUTTON_DOMAIN, COVER_DOMAIN, FAN_DOMAIN + ), ) TEMPLATE_BLUEPRINT_SCHEMA = vol.All( diff --git a/homeassistant/components/template/fan.py b/homeassistant/components/template/fan.py index 7ec62891784..32e6b06d108 100644 --- a/homeassistant/components/template/fan.py +++ b/homeassistant/components/template/fan.py @@ -21,6 +21,8 @@ from homeassistant.components.fan import ( from homeassistant.const import ( CONF_ENTITY_ID, CONF_FRIENDLY_NAME, + CONF_NAME, + CONF_STATE, CONF_UNIQUE_ID, CONF_VALUE_TEMPLATE, STATE_ON, @@ -29,14 +31,17 @@ from homeassistant.const import ( ) from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import TemplateError -from homeassistant.helpers import config_validation as cv +from homeassistant.helpers import config_validation as cv, template from homeassistant.helpers.entity import async_generate_entity_id from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType -from .const import DOMAIN +from .const import CONF_OBJECT_ID, CONF_PICTURE, DOMAIN from .template_entity import ( + LEGACY_FIELDS as TEMPLATE_ENTITY_LEGACY_FIELDS, + TEMPLATE_ENTITY_AVAILABILITY_SCHEMA, TEMPLATE_ENTITY_AVAILABILITY_SCHEMA_LEGACY, + TEMPLATE_ENTITY_ICON_SCHEMA, TemplateEntity, rewrite_common_legacy_to_modern_conf, ) @@ -59,54 +64,121 @@ CONF_SET_PRESET_MODE_ACTION = "set_preset_mode" _VALID_DIRECTIONS = [DIRECTION_FORWARD, DIRECTION_REVERSE] +CONF_DIRECTION = "direction" +CONF_OSCILLATING = "oscillating" +CONF_PERCENTAGE = "percentage" +CONF_PRESET_MODE = "preset_mode" + +LEGACY_FIELDS = TEMPLATE_ENTITY_LEGACY_FIELDS | { + CONF_DIRECTION_TEMPLATE: CONF_DIRECTION, + CONF_OSCILLATING_TEMPLATE: CONF_OSCILLATING, + CONF_PERCENTAGE_TEMPLATE: CONF_PERCENTAGE, + CONF_PRESET_MODE_TEMPLATE: CONF_PRESET_MODE, + CONF_VALUE_TEMPLATE: CONF_STATE, +} + +DEFAULT_NAME = "Template Fan" + FAN_SCHEMA = vol.All( + vol.Schema( + { + vol.Optional(CONF_DIRECTION): cv.template, + vol.Optional(CONF_NAME): cv.template, + vol.Required(CONF_OFF_ACTION): cv.SCRIPT_SCHEMA, + vol.Required(CONF_ON_ACTION): cv.SCRIPT_SCHEMA, + vol.Optional(CONF_OSCILLATING): cv.template, + vol.Optional(CONF_PERCENTAGE): cv.template, + vol.Optional(CONF_PICTURE): cv.template, + vol.Optional(CONF_PRESET_MODE): cv.template, + vol.Optional(CONF_PRESET_MODES): cv.ensure_list, + vol.Optional(CONF_SET_DIRECTION_ACTION): cv.SCRIPT_SCHEMA, + vol.Optional(CONF_SET_OSCILLATING_ACTION): cv.SCRIPT_SCHEMA, + vol.Optional(CONF_SET_PERCENTAGE_ACTION): cv.SCRIPT_SCHEMA, + vol.Optional(CONF_SET_PRESET_MODE_ACTION): cv.SCRIPT_SCHEMA, + vol.Optional(CONF_SPEED_COUNT): vol.Coerce(int), + vol.Optional(CONF_STATE): cv.template, + vol.Optional(CONF_UNIQUE_ID): cv.string, + } + ) + .extend(TEMPLATE_ENTITY_AVAILABILITY_SCHEMA.schema) + .extend(TEMPLATE_ENTITY_ICON_SCHEMA.schema), +) + +LEGACY_FAN_SCHEMA = vol.All( cv.deprecated(CONF_ENTITY_ID), vol.Schema( { + vol.Optional(CONF_DIRECTION_TEMPLATE): cv.template, + vol.Optional(CONF_ENTITY_ID): cv.entity_ids, vol.Optional(CONF_FRIENDLY_NAME): cv.string, - vol.Optional(CONF_VALUE_TEMPLATE): cv.template, + vol.Required(CONF_OFF_ACTION): cv.SCRIPT_SCHEMA, + vol.Required(CONF_ON_ACTION): cv.SCRIPT_SCHEMA, + vol.Optional(CONF_OSCILLATING_TEMPLATE): cv.template, vol.Optional(CONF_PERCENTAGE_TEMPLATE): cv.template, vol.Optional(CONF_PRESET_MODE_TEMPLATE): cv.template, - vol.Optional(CONF_OSCILLATING_TEMPLATE): cv.template, - vol.Optional(CONF_DIRECTION_TEMPLATE): cv.template, - vol.Required(CONF_ON_ACTION): cv.SCRIPT_SCHEMA, - vol.Required(CONF_OFF_ACTION): cv.SCRIPT_SCHEMA, + vol.Optional(CONF_PRESET_MODES): cv.ensure_list, + vol.Optional(CONF_SET_DIRECTION_ACTION): cv.SCRIPT_SCHEMA, + vol.Optional(CONF_SET_OSCILLATING_ACTION): cv.SCRIPT_SCHEMA, vol.Optional(CONF_SET_PERCENTAGE_ACTION): cv.SCRIPT_SCHEMA, vol.Optional(CONF_SET_PRESET_MODE_ACTION): cv.SCRIPT_SCHEMA, - vol.Optional(CONF_SET_OSCILLATING_ACTION): cv.SCRIPT_SCHEMA, - vol.Optional(CONF_SET_DIRECTION_ACTION): cv.SCRIPT_SCHEMA, vol.Optional(CONF_SPEED_COUNT): vol.Coerce(int), - vol.Optional(CONF_PRESET_MODES): cv.ensure_list, - vol.Optional(CONF_ENTITY_ID): cv.entity_ids, vol.Optional(CONF_UNIQUE_ID): cv.string, + vol.Optional(CONF_VALUE_TEMPLATE): cv.template, } ).extend(TEMPLATE_ENTITY_AVAILABILITY_SCHEMA_LEGACY.schema), ) PLATFORM_SCHEMA = cv.PLATFORM_SCHEMA.extend( - {vol.Required(CONF_FANS): cv.schema_with_slug_keys(FAN_SCHEMA)} + {vol.Required(CONF_FANS): cv.schema_with_slug_keys(LEGACY_FAN_SCHEMA)} ) -async def _async_create_entities(hass: HomeAssistant, config): - """Create the Template Fans.""" +def rewrite_legacy_to_modern_conf( + hass: HomeAssistant, config: dict[str, dict] +) -> list[dict]: + """Rewrite legacy fan configuration definitions to modern ones.""" fans = [] - for object_id, entity_config in config[CONF_FANS].items(): - entity_config = rewrite_common_legacy_to_modern_conf(hass, entity_config) + for object_id, entity_conf in config.items(): + entity_conf = {**entity_conf, CONF_OBJECT_ID: object_id} - unique_id = entity_config.get(CONF_UNIQUE_ID) + entity_conf = rewrite_common_legacy_to_modern_conf( + hass, entity_conf, LEGACY_FIELDS + ) + + if CONF_NAME not in entity_conf: + entity_conf[CONF_NAME] = template.Template(object_id, hass) + + fans.append(entity_conf) + + return fans + + +@callback +def _async_create_template_tracking_entities( + async_add_entities: AddEntitiesCallback, + hass: HomeAssistant, + definitions: list[dict], + unique_id_prefix: str | None, +) -> None: + """Create the template fans.""" + fans = [] + + for entity_conf in definitions: + unique_id = entity_conf.get(CONF_UNIQUE_ID) + + if unique_id and unique_id_prefix: + unique_id = f"{unique_id_prefix}-{unique_id}" fans.append( TemplateFan( hass, - object_id, - entity_config, + entity_conf, unique_id, ) ) - return fans + async_add_entities(fans) async def async_setup_platform( @@ -116,7 +188,21 @@ async def async_setup_platform( discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the template fans.""" - async_add_entities(await _async_create_entities(hass, config)) + if discovery_info is None: + _async_create_template_tracking_entities( + async_add_entities, + hass, + rewrite_legacy_to_modern_conf(hass, config[CONF_FANS]), + None, + ) + return + + _async_create_template_tracking_entities( + async_add_entities, + hass, + discovery_info["entities"], + discovery_info["unique_id"], + ) class TemplateFan(TemplateEntity, FanEntity): @@ -127,27 +213,24 @@ class TemplateFan(TemplateEntity, FanEntity): def __init__( self, hass: HomeAssistant, - object_id, config: dict[str, Any], unique_id, ) -> None: """Initialize the fan.""" - super().__init__( - hass, config=config, fallback_name=object_id, unique_id=unique_id - ) - self.hass = hass - self.entity_id = async_generate_entity_id( - ENTITY_ID_FORMAT, object_id, hass=hass - ) + super().__init__(hass, config=config, fallback_name=None, unique_id=unique_id) + if (object_id := config.get(CONF_OBJECT_ID)) is not None: + self.entity_id = async_generate_entity_id( + ENTITY_ID_FORMAT, object_id, hass=hass + ) name = self._attr_name if TYPE_CHECKING: assert name is not None - self._template = config.get(CONF_VALUE_TEMPLATE) - self._percentage_template = config.get(CONF_PERCENTAGE_TEMPLATE) - self._preset_mode_template = config.get(CONF_PRESET_MODE_TEMPLATE) - self._oscillating_template = config.get(CONF_OSCILLATING_TEMPLATE) - self._direction_template = config.get(CONF_DIRECTION_TEMPLATE) + self._template = config.get(CONF_STATE) + self._percentage_template = config.get(CONF_PERCENTAGE) + self._preset_mode_template = config.get(CONF_PRESET_MODE) + self._oscillating_template = config.get(CONF_OSCILLATING) + self._direction_template = config.get(CONF_DIRECTION) self._attr_supported_features |= ( FanEntityFeature.TURN_OFF | FanEntityFeature.TURN_ON @@ -231,7 +314,7 @@ class TemplateFan(TemplateEntity, FanEntity): if preset_mode is not None: await self.async_set_preset_mode(preset_mode) - elif percentage is not None: + if percentage is not None: await self.async_set_percentage(percentage) if self._template is None: diff --git a/tests/components/template/test_fan.py b/tests/components/template/test_fan.py index dac97931fa7..a061ce86256 100644 --- a/tests/components/template/test_fan.py +++ b/tests/components/template/test_fan.py @@ -5,8 +5,7 @@ from typing import Any import pytest import voluptuous as vol -from homeassistant import setup -from homeassistant.components import fan +from homeassistant.components import fan, template from homeassistant.components.fan import ( ATTR_DIRECTION, ATTR_OSCILLATING, @@ -14,12 +13,12 @@ from homeassistant.components.fan import ( ATTR_PRESET_MODE, DIRECTION_FORWARD, DIRECTION_REVERSE, - DOMAIN as FAN_DOMAIN, FanEntityFeature, NotValidPresetModeError, ) from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNAVAILABLE from homeassistant.core import HomeAssistant, ServiceCall +from homeassistant.helpers import entity_registry as er from homeassistant.setup import async_setup_component from .conftest import ConfigurationStyle @@ -27,23 +26,14 @@ from .conftest import ConfigurationStyle from tests.common import assert_setup_component from tests.components.fan import common -_TEST_OBJECT_ID = "test_fan" -_TEST_FAN = f"fan.{_TEST_OBJECT_ID}" +TEST_OBJECT_ID = "test_fan" +TEST_ENTITY_ID = f"fan.{TEST_OBJECT_ID}" # Represent for fan's state _STATE_INPUT_BOOLEAN = "input_boolean.state" # Represent for fan's state _STATE_AVAILABILITY_BOOLEAN = "availability_boolean.state" -# Represent for fan's preset mode -_PRESET_MODE_INPUT_SELECT = "input_select.preset_mode" -# Represent for fan's speed percentage -_PERCENTAGE_INPUT_NUMBER = "input_number.percentage" -# Represent for fan's oscillating -_OSC_INPUT = "input_select.osc" -# Represent for fan's direction -_DIRECTION_INPUT_SELECT = "input_select.direction" - -OPTIMISTIC_ON_OFF_CONFIG = { +OPTIMISTIC_ON_OFF_ACTIONS = { "turn_on": { "service": "test.automation", "data": { @@ -59,7 +49,10 @@ OPTIMISTIC_ON_OFF_CONFIG = { }, }, } - +NAMED_ON_OFF_ACTIONS = { + **OPTIMISTIC_ON_OFF_ACTIONS, + "name": TEST_OBJECT_ID, +} PERCENTAGE_ACTION = { "set_percentage": { @@ -72,7 +65,7 @@ PERCENTAGE_ACTION = { }, } OPTIMISTIC_PERCENTAGE_CONFIG = { - **OPTIMISTIC_ON_OFF_CONFIG, + **OPTIMISTIC_ON_OFF_ACTIONS, **PERCENTAGE_ACTION, } @@ -87,7 +80,7 @@ PRESET_MODE_ACTION = { }, } OPTIMISTIC_PRESET_MODE_CONFIG = { - **OPTIMISTIC_ON_OFF_CONFIG, + **OPTIMISTIC_ON_OFF_ACTIONS, **PRESET_MODE_ACTION, } OPTIMISTIC_PRESET_MODE_CONFIG2 = { @@ -106,7 +99,7 @@ OSCILLATE_ACTION = { }, } OPTIMISTIC_OSCILLATE_CONFIG = { - **OPTIMISTIC_ON_OFF_CONFIG, + **OPTIMISTIC_ON_OFF_ACTIONS, **OSCILLATE_ACTION, } @@ -121,16 +114,38 @@ DIRECTION_ACTION = { }, } OPTIMISTIC_DIRECTION_CONFIG = { - **OPTIMISTIC_ON_OFF_CONFIG, + **OPTIMISTIC_ON_OFF_ACTIONS, **DIRECTION_ACTION, } +UNIQUE_ID_CONFIG = { + **OPTIMISTIC_ON_OFF_ACTIONS, + "unique_id": "not-so-unique-anymore", +} + + +def _verify( + hass: HomeAssistant, + expected_state: str, + expected_percentage: int | None = None, + expected_oscillating: bool | None = None, + expected_direction: str | None = None, + expected_preset_mode: str | None = None, +) -> None: + """Verify fan's state, speed and osc.""" + state = hass.states.get(TEST_ENTITY_ID) + attributes = state.attributes + assert state.state == str(expected_state) + assert attributes.get(ATTR_PERCENTAGE) == expected_percentage + assert attributes.get(ATTR_OSCILLATING) == expected_oscillating + assert attributes.get(ATTR_DIRECTION) == expected_direction + assert attributes.get(ATTR_PRESET_MODE) == expected_preset_mode async def async_setup_legacy_format( - hass: HomeAssistant, count: int, light_config: dict[str, Any] + hass: HomeAssistant, count: int, fan_config: dict[str, Any] ) -> None: """Do setup of fan integration via legacy format.""" - config = {"fan": {"platform": "template", "fans": light_config}} + config = {"fan": {"platform": "template", "fans": fan_config}} with assert_setup_component(count, fan.DOMAIN): assert await async_setup_component( @@ -144,6 +159,38 @@ async def async_setup_legacy_format( await hass.async_block_till_done() +async def async_setup_modern_format( + hass: HomeAssistant, count: int, fan_config: dict[str, Any] +) -> None: + """Do setup of fan integration via modern format.""" + config = {"template": {"fan": fan_config}} + + with assert_setup_component(count, template.DOMAIN): + assert await async_setup_component( + hass, + template.DOMAIN, + config, + ) + + await hass.async_block_till_done() + await hass.async_start() + await hass.async_block_till_done() + + +async def async_setup_legacy_named_fan( + hass: HomeAssistant, count: int, fan_config: dict[str, Any] +): + """Do setup of a named fan via legacy format.""" + await async_setup_legacy_format(hass, count, {TEST_OBJECT_ID: fan_config}) + + +async def async_setup_modern_named_fan( + hass: HomeAssistant, count: int, fan_config: dict[str, Any] +): + """Do setup of a named fan via legacy format.""" + await async_setup_modern_format(hass, count, {"name": TEST_OBJECT_ID, **fan_config}) + + async def async_setup_legacy_format_with_attribute( hass: HomeAssistant, count: int, @@ -157,7 +204,7 @@ async def async_setup_legacy_format_with_attribute( hass, count, { - _TEST_OBJECT_ID: { + TEST_OBJECT_ID: { **extra_config, "value_template": "{{ 1 == 1 }}", **extra, @@ -166,16 +213,83 @@ async def async_setup_legacy_format_with_attribute( ) +async def async_setup_modern_format_with_attribute( + hass: HomeAssistant, + count: int, + attribute: str, + attribute_template: str, + extra_config: dict, +) -> None: + """Do setup of a modern fan that has a single templated attribute.""" + extra = {attribute: attribute_template} if attribute and attribute_template else {} + await async_setup_modern_format( + hass, + count, + { + "name": TEST_OBJECT_ID, + **extra_config, + "state": "{{ 1 == 1 }}", + **extra, + }, + ) + + @pytest.fixture async def setup_fan( hass: HomeAssistant, count: int, style: ConfigurationStyle, - light_config: dict[str, Any], + fan_config: dict[str, Any], ) -> None: """Do setup of fan integration.""" if style == ConfigurationStyle.LEGACY: - await async_setup_legacy_format(hass, count, light_config) + await async_setup_legacy_format(hass, count, fan_config) + elif style == ConfigurationStyle.MODERN: + await async_setup_modern_format(hass, count, fan_config) + + +@pytest.fixture +async def setup_named_fan( + hass: HomeAssistant, + count: int, + style: ConfigurationStyle, + fan_config: dict[str, Any], +) -> None: + """Do setup of fan integration.""" + if style == ConfigurationStyle.LEGACY: + await async_setup_legacy_named_fan(hass, count, fan_config) + elif style == ConfigurationStyle.MODERN: + await async_setup_modern_named_fan(hass, count, fan_config) + + +@pytest.fixture +async def setup_state_fan( + hass: HomeAssistant, + count: int, + style: ConfigurationStyle, + state_template: str, +): + """Do setup of fan integration using a state template.""" + if style == ConfigurationStyle.LEGACY: + await async_setup_legacy_format( + hass, + count, + { + TEST_OBJECT_ID: { + **OPTIMISTIC_ON_OFF_ACTIONS, + "value_template": state_template, + } + }, + ) + elif style == ConfigurationStyle.MODERN: + await async_setup_modern_format( + hass, + count, + { + **NAMED_ON_OFF_ACTIONS, + "state": state_template, + }, + ) @pytest.fixture @@ -187,9 +301,14 @@ async def setup_test_fan_with_extra_config( extra_config: dict[str, Any], ) -> None: """Do setup of fan integration.""" - config = {_TEST_OBJECT_ID: {**fan_config, **extra_config}} if style == ConfigurationStyle.LEGACY: - await async_setup_legacy_format(hass, count, config) + await async_setup_legacy_format( + hass, count, {TEST_OBJECT_ID: {**fan_config, **extra_config}} + ) + elif style == ConfigurationStyle.MODERN: + await async_setup_modern_format( + hass, count, {"name": TEST_OBJECT_ID, **fan_config, **extra_config} + ) @pytest.fixture @@ -204,344 +323,507 @@ async def setup_optimistic_fan_attribute( await async_setup_legacy_format_with_attribute( hass, count, "", "", extra_config ) + elif style == ConfigurationStyle.MODERN: + await async_setup_modern_format_with_attribute( + hass, count, "", "", extra_config + ) -@pytest.mark.parametrize(("count", "domain"), [(1, FAN_DOMAIN)]) +@pytest.fixture +async def setup_single_attribute_state_fan( + hass: HomeAssistant, + count: int, + style: ConfigurationStyle, + attribute: str, + attribute_template: str, + state_template: str, + extra_config: dict, +) -> None: + """Do setup of fan integration testing a single attribute.""" + extra = {attribute: attribute_template} if attribute and attribute_template else {} + if style == ConfigurationStyle.LEGACY: + await async_setup_legacy_format( + hass, + count, + { + TEST_OBJECT_ID: { + **OPTIMISTIC_ON_OFF_ACTIONS, + "value_template": state_template, + **extra, + **extra_config, + } + }, + ) + elif style == ConfigurationStyle.MODERN: + await async_setup_modern_format( + hass, + count, + { + **NAMED_ON_OFF_ACTIONS, + "state": state_template, + **extra, + **extra_config, + }, + ) + + +@pytest.mark.parametrize(("count", "state_template"), [(1, "{{ 'on' }}")]) @pytest.mark.parametrize( - "config", - [ - { - FAN_DOMAIN: { - "platform": "template", - "fans": { - "test_fan": { - "value_template": "{{ 'on' }}", - "turn_on": {"service": "script.fan_on"}, - "turn_off": {"service": "script.fan_off"}, - } - }, - } - }, - ], + "style", [ConfigurationStyle.LEGACY, ConfigurationStyle.MODERN] ) -@pytest.mark.usefixtures("start_ha") +@pytest.mark.usefixtures("setup_state_fan") async def test_missing_optional_config(hass: HomeAssistant) -> None: """Test: missing optional template is ok.""" _verify(hass, STATE_ON, None, None, None, None) -@pytest.mark.parametrize(("count", "domain"), [(0, FAN_DOMAIN)]) +@pytest.mark.parametrize("count", [0]) @pytest.mark.parametrize( - "config", + "style", [ConfigurationStyle.LEGACY, ConfigurationStyle.MODERN] +) +@pytest.mark.parametrize( + "fan_config", [ { - FAN_DOMAIN: { - "platform": "template", - "fans": { - "platform": "template", - "fans": { - "test_fan": { - "turn_on": {"service": "script.fan_on"}, - "turn_off": {"service": "script.fan_off"}, - } - }, - }, - } + "value_template": "{{ 'on' }}", + "turn_off": {"service": "script.fan_off"}, }, { - FAN_DOMAIN: { - "platform": "template", - "fans": { - "platform": "template", - "fans": { - "test_fan": { - "value_template": "{{ 'on' }}", - "turn_off": {"service": "script.fan_off"}, - } - }, - }, - } - }, - { - FAN_DOMAIN: { - "platform": "template", - "fans": { - "platform": "template", - "fans": { - "test_fan": { - "value_template": "{{ 'on' }}", - "turn_on": {"service": "script.fan_on"}, - } - }, - }, - } + "value_template": "{{ 'on' }}", + "turn_on": {"service": "script.fan_on"}, }, ], ) -@pytest.mark.usefixtures("start_ha") +@pytest.mark.usefixtures("setup_fan") async def test_wrong_template_config(hass: HomeAssistant) -> None: - """Test: missing 'value_template' will fail.""" + """Test: missing 'turn_on' or 'turn_off' will fail.""" assert hass.states.async_all("fan") == [] -@pytest.mark.parametrize(("count", "domain"), [(1, FAN_DOMAIN)]) @pytest.mark.parametrize( - "config", - [ - { - FAN_DOMAIN: { - "platform": "template", - "fans": { - "test_fan": { - "value_template": "{{ is_state('input_boolean.state', 'True') }}", - "percentage_template": ( - "{{ states('input_number.percentage') }}" - ), - **OPTIMISTIC_ON_OFF_CONFIG, - **PERCENTAGE_ACTION, - "preset_mode_template": ( - "{{ states('input_select.preset_mode') }}" - ), - **PRESET_MODE_ACTION, - "oscillating_template": "{{ states('input_select.osc') }}", - **OSCILLATE_ACTION, - "direction_template": "{{ states('input_select.direction') }}", - **DIRECTION_ACTION, - "speed_count": "3", - } - }, - } - }, - ], + ("count", "state_template"), [(1, "{{ is_state('input_boolean.state', 'on') }}")] ) -@pytest.mark.usefixtures("start_ha") -async def test_templates_with_entities(hass: HomeAssistant) -> None: - """Test tempalates with values from other entities.""" - _verify(hass, STATE_OFF, 0, None, None, None) +@pytest.mark.parametrize( + "style", [ConfigurationStyle.LEGACY, ConfigurationStyle.MODERN] +) +@pytest.mark.usefixtures("setup_state_fan") +async def test_state_template(hass: HomeAssistant) -> None: + """Test state template.""" + _verify(hass, STATE_OFF, None, None, None, None) - hass.states.async_set(_STATE_INPUT_BOOLEAN, True) - hass.states.async_set(_PERCENTAGE_INPUT_NUMBER, 66) - hass.states.async_set(_OSC_INPUT, "True") - - for set_state, set_value, value in ( - (_DIRECTION_INPUT_SELECT, DIRECTION_FORWARD, 66), - (_PERCENTAGE_INPUT_NUMBER, 33, 33), - (_PERCENTAGE_INPUT_NUMBER, 66, 66), - (_PERCENTAGE_INPUT_NUMBER, 100, 100), - (_PERCENTAGE_INPUT_NUMBER, "dog", 0), - ): - hass.states.async_set(set_state, set_value) - await hass.async_block_till_done() - _verify(hass, STATE_ON, value, True, DIRECTION_FORWARD, None) - - hass.states.async_set(_STATE_INPUT_BOOLEAN, False) + hass.states.async_set(_STATE_INPUT_BOOLEAN, STATE_ON) await hass.async_block_till_done() - _verify(hass, STATE_OFF, 0, True, DIRECTION_FORWARD, None) + + _verify(hass, STATE_ON, None, None, None, None) + + hass.states.async_set(_STATE_INPUT_BOOLEAN, STATE_OFF) + await hass.async_block_till_done() + + _verify(hass, STATE_OFF, None, None, None, None) -@pytest.mark.parametrize(("count", "domain"), [(1, FAN_DOMAIN)]) +@pytest.mark.parametrize("count", [1]) @pytest.mark.parametrize( - ("config", "entity", "tests"), + ("state_template", "expected"), + [ + ("{{ True }}", STATE_ON), + ("{{ False }}", STATE_OFF), + ("{{ x - 1 }}", STATE_UNAVAILABLE), + ("{{ 7.45 }}", STATE_OFF), + ], +) +@pytest.mark.parametrize( + "style", [ConfigurationStyle.LEGACY, ConfigurationStyle.MODERN] +) +@pytest.mark.usefixtures("setup_state_fan") +async def test_state_template_states(hass: HomeAssistant, expected: str) -> None: + """Test state template.""" + _verify(hass, expected, None, None, None, None) + + +@pytest.mark.parametrize( + ("count", "state_template", "attribute_template", "extra_config"), [ ( + 1, + "{{ 1 == 1}}", + "{% if states.input_boolean.state.state %}/local/switch.png{% endif %}", + {}, + ) + ], +) +@pytest.mark.parametrize( + ("style", "attribute"), + [ + (ConfigurationStyle.MODERN, "picture"), + ], +) +@pytest.mark.usefixtures("setup_single_attribute_state_fan") +async def test_picture_template(hass: HomeAssistant) -> None: + """Test picture template.""" + state = hass.states.get(TEST_ENTITY_ID) + assert state.attributes.get("entity_picture") in ("", None) + + hass.states.async_set(_STATE_INPUT_BOOLEAN, STATE_ON) + await hass.async_block_till_done() + + state = hass.states.get(TEST_ENTITY_ID) + assert state.attributes["entity_picture"] == "/local/switch.png" + + +@pytest.mark.parametrize( + ("count", "state_template", "attribute_template", "extra_config"), + [ + ( + 1, + "{{ 1 == 1}}", + "{% if states.input_boolean.state.state %}mdi:eye{% endif %}", + {}, + ) + ], +) +@pytest.mark.parametrize( + ("style", "attribute"), + [ + (ConfigurationStyle.MODERN, "icon"), + ], +) +@pytest.mark.usefixtures("setup_single_attribute_state_fan") +async def test_icon_template(hass: HomeAssistant) -> None: + """Test icon template.""" + state = hass.states.get(TEST_ENTITY_ID) + assert state.attributes.get("icon") in ("", None) + + hass.states.async_set(_STATE_INPUT_BOOLEAN, STATE_ON) + await hass.async_block_till_done() + + state = hass.states.get(TEST_ENTITY_ID) + assert state.attributes["icon"] == "mdi:eye" + + +@pytest.mark.parametrize( + ("count", "state_template", "attribute_template", "extra_config"), + [ + ( + 1, + "{{ 1 == 1 }}", + "{{ states('sensor.percentage') }}", + PERCENTAGE_ACTION, + ) + ], +) +@pytest.mark.parametrize( + ("style", "attribute"), + [ + (ConfigurationStyle.LEGACY, "percentage_template"), + (ConfigurationStyle.MODERN, "percentage"), + ], +) +@pytest.mark.parametrize( + ("percent", "expected"), + [ + ("0", 0), + ("33", 33), + ("invalid", 0), + ("5000", 0), + ("100", 100), + ], +) +@pytest.mark.usefixtures("setup_single_attribute_state_fan") +async def test_percentage_template( + hass: HomeAssistant, percent: str, expected: int, calls: list[ServiceCall] +) -> None: + """Test templates with fan percentages from other entities.""" + hass.states.async_set("sensor.percentage", percent) + await hass.async_block_till_done() + _verify(hass, STATE_ON, expected, None, None, None) + + +@pytest.mark.parametrize( + ("count", "state_template", "attribute_template", "extra_config"), + [ + ( + 1, + "{{ 1 == 1 }}", + "{{ states('sensor.preset_mode') }}", + {"preset_modes": ["auto", "smart"], **PRESET_MODE_ACTION}, + ) + ], +) +@pytest.mark.parametrize( + ("style", "attribute"), + [ + (ConfigurationStyle.LEGACY, "preset_mode_template"), + (ConfigurationStyle.MODERN, "preset_mode"), + ], +) +@pytest.mark.parametrize( + ("preset_mode", "expected"), + [ + ("0", None), + ("invalid", None), + ("auto", "auto"), + ("smart", "smart"), + ], +) +@pytest.mark.usefixtures("setup_single_attribute_state_fan") +async def test_preset_mode_template( + hass: HomeAssistant, preset_mode: str, expected: int +) -> None: + """Test preset_mode template.""" + hass.states.async_set("sensor.preset_mode", preset_mode) + await hass.async_block_till_done() + _verify(hass, STATE_ON, None, None, None, expected) + + +@pytest.mark.parametrize( + ("count", "state_template", "attribute_template", "extra_config"), + [ + ( + 1, + "{{ 1 == 1 }}", + "{{ is_state('binary_sensor.oscillating', 'on') }}", + OSCILLATE_ACTION, + ) + ], +) +@pytest.mark.parametrize( + ("style", "attribute"), + [ + (ConfigurationStyle.LEGACY, "oscillating_template"), + (ConfigurationStyle.MODERN, "oscillating"), + ], +) +@pytest.mark.parametrize( + ("oscillating", "expected"), + [ + (STATE_ON, True), + (STATE_OFF, False), + ], +) +@pytest.mark.usefixtures("setup_single_attribute_state_fan") +async def test_oscillating_template( + hass: HomeAssistant, oscillating: str, expected: bool | None +) -> None: + """Test oscillating template.""" + hass.states.async_set("binary_sensor.oscillating", oscillating) + await hass.async_block_till_done() + _verify(hass, STATE_ON, None, expected, None, None) + + +@pytest.mark.parametrize( + ("count", "state_template", "attribute_template", "extra_config"), + [ + ( + 1, + "{{ 1 == 1 }}", + "{{ states('sensor.direction') }}", + DIRECTION_ACTION, + ) + ], +) +@pytest.mark.parametrize( + ("style", "attribute"), + [ + (ConfigurationStyle.LEGACY, "direction_template"), + (ConfigurationStyle.MODERN, "direction"), + ], +) +@pytest.mark.parametrize( + ("direction", "expected"), + [ + (DIRECTION_FORWARD, DIRECTION_FORWARD), + (DIRECTION_REVERSE, DIRECTION_REVERSE), + ], +) +@pytest.mark.usefixtures("setup_single_attribute_state_fan") +async def test_direction_template( + hass: HomeAssistant, direction: str, expected: bool | None +) -> None: + """Test direction template.""" + hass.states.async_set("sensor.direction", direction) + await hass.async_block_till_done() + _verify(hass, STATE_ON, None, None, expected, None) + + +@pytest.mark.parametrize("count", [1]) +@pytest.mark.parametrize( + ("style", "fan_config"), + [ + ( + ConfigurationStyle.LEGACY, { - FAN_DOMAIN: { - "platform": "template", - "fans": { - "test_fan": { - "value_template": "{{ 'on' }}", - "percentage_template": "{{ states('sensor.percentage') }}", - **OPTIMISTIC_PERCENTAGE_CONFIG, - }, - }, - } + "availability_template": ( + "{{ is_state('availability_boolean.state', 'on') }}" + ), + "value_template": "{{ 'on' }}", + "oscillating_template": "{{ 1 == 1 }}", + "direction_template": "{{ 'forward' }}", + "turn_on": {"service": "script.fan_on"}, + "turn_off": {"service": "script.fan_off"}, }, - "sensor.percentage", - [ - ("0", 0, None), - ("33", 33, None), - ("invalid", 0, None), - ("5000", 0, None), - ("100", 100, None), - ("0", 0, None), - ], ), ( + ConfigurationStyle.MODERN, { - FAN_DOMAIN: { - "platform": "template", - "fans": { - "test_fan": { - "value_template": "{{ 'on' }}", - "preset_modes": ["auto", "smart"], - "preset_mode_template": ( - "{{ states('sensor.preset_mode') }}" - ), - **OPTIMISTIC_PRESET_MODE_CONFIG, - }, - }, - } + "availability": ("{{ is_state('availability_boolean.state', 'on') }}"), + "state": "{{ 'on' }}", + "oscillating": "{{ 1 == 1 }}", + "direction": "{{ 'forward' }}", + "turn_on": {"service": "script.fan_on"}, + "turn_off": {"service": "script.fan_off"}, }, - "sensor.preset_mode", - [ - ("0", None, None), - ("invalid", None, None), - ("auto", None, "auto"), - ("smart", None, "smart"), - ("invalid", None, None), - ], ), ], ) -@pytest.mark.usefixtures("start_ha") -async def test_templates_with_entities2(hass: HomeAssistant, entity, tests) -> None: - """Test templates with values from other entities.""" - for set_percentage, test_percentage, test_type in tests: - hass.states.async_set(entity, set_percentage) - await hass.async_block_till_done() - _verify(hass, STATE_ON, test_percentage, None, None, test_type) - - -@pytest.mark.parametrize(("count", "domain"), [(1, FAN_DOMAIN)]) -@pytest.mark.parametrize( - "config", - [ - { - FAN_DOMAIN: { - "platform": "template", - "fans": { - "test_fan": { - "availability_template": ( - "{{ is_state('availability_boolean.state', 'on') }}" - ), - "value_template": "{{ 'on' }}", - "oscillating_template": "{{ 1 == 1 }}", - "direction_template": "{{ 'forward' }}", - "turn_on": {"service": "script.fan_on"}, - "turn_off": {"service": "script.fan_off"}, - } - }, - } - }, - ], -) -@pytest.mark.usefixtures("start_ha") +@pytest.mark.usefixtures("setup_named_fan") async def test_availability_template_with_entities(hass: HomeAssistant) -> None: """Test availability tempalates with values from other entities.""" for state, test_assert in ((STATE_ON, True), (STATE_OFF, False)): hass.states.async_set(_STATE_AVAILABILITY_BOOLEAN, state) await hass.async_block_till_done() - assert (hass.states.get(_TEST_FAN).state != STATE_UNAVAILABLE) == test_assert + assert ( + hass.states.get(TEST_ENTITY_ID).state != STATE_UNAVAILABLE + ) == test_assert -@pytest.mark.parametrize(("count", "domain"), [(1, FAN_DOMAIN)]) +@pytest.mark.parametrize("count", [1]) @pytest.mark.parametrize( - ("config", "states"), + ("style", "fan_config", "states"), [ ( + ConfigurationStyle.LEGACY, { - FAN_DOMAIN: { - "platform": "template", - "fans": { - "test_fan": { - "value_template": "{{ 'unavailable' }}", - **OPTIMISTIC_ON_OFF_CONFIG, - } - }, - } + "value_template": "{{ 'unavailable' }}", + **OPTIMISTIC_ON_OFF_ACTIONS, }, [STATE_OFF, None, None, None], ), ( + ConfigurationStyle.MODERN, { - FAN_DOMAIN: { - "platform": "template", - "fans": { - "test_fan": { - "value_template": "{{ 'on' }}", - "percentage_template": "{{ 0 }}", - **OPTIMISTIC_PERCENTAGE_CONFIG, - "oscillating_template": "{{ 'unavailable' }}", - **OSCILLATE_ACTION, - "direction_template": "{{ 'unavailable' }}", - **DIRECTION_ACTION, - } - }, - } + "state": "{{ 'unavailable' }}", + **OPTIMISTIC_ON_OFF_ACTIONS, + }, + [STATE_OFF, None, None, None], + ), + ( + ConfigurationStyle.LEGACY, + { + "value_template": "{{ 'on' }}", + "percentage_template": "{{ 0 }}", + **OPTIMISTIC_PERCENTAGE_CONFIG, + "oscillating_template": "{{ 'unavailable' }}", + **OSCILLATE_ACTION, + "direction_template": "{{ 'unavailable' }}", + **DIRECTION_ACTION, }, [STATE_ON, 0, None, None], ), ( + ConfigurationStyle.MODERN, { - FAN_DOMAIN: { - "platform": "template", - "fans": { - "test_fan": { - "value_template": "{{ 'on' }}", - "percentage_template": "{{ 66 }}", - **OPTIMISTIC_PERCENTAGE_CONFIG, - "oscillating_template": "{{ 1 == 1 }}", - **OSCILLATE_ACTION, - "direction_template": "{{ 'forward' }}", - **DIRECTION_ACTION, - } - }, - } + "state": "{{ 'on' }}", + "percentage": "{{ 0 }}", + **OPTIMISTIC_PERCENTAGE_CONFIG, + "oscillating": "{{ 'unavailable' }}", + **OSCILLATE_ACTION, + "direction": "{{ 'unavailable' }}", + **DIRECTION_ACTION, + }, + [STATE_ON, 0, None, None], + ), + ( + ConfigurationStyle.LEGACY, + { + "value_template": "{{ 'on' }}", + "percentage_template": "{{ 66 }}", + **OPTIMISTIC_PERCENTAGE_CONFIG, + "oscillating_template": "{{ 1 == 1 }}", + **OSCILLATE_ACTION, + "direction_template": "{{ 'forward' }}", + **DIRECTION_ACTION, }, [STATE_ON, 66, True, DIRECTION_FORWARD], ), ( + ConfigurationStyle.MODERN, { - FAN_DOMAIN: { - "platform": "template", - "fans": { - "test_fan": { - "value_template": "{{ 'abc' }}", - "percentage_template": "{{ 0 }}", - **OPTIMISTIC_PERCENTAGE_CONFIG, - "oscillating_template": "{{ 'xyz' }}", - **OSCILLATE_ACTION, - "direction_template": "{{ 'right' }}", - **DIRECTION_ACTION, - } - }, - } + "state": "{{ 'on' }}", + "percentage": "{{ 66 }}", + **OPTIMISTIC_PERCENTAGE_CONFIG, + "oscillating": "{{ 1 == 1 }}", + **OSCILLATE_ACTION, + "direction": "{{ 'forward' }}", + **DIRECTION_ACTION, + }, + [STATE_ON, 66, True, DIRECTION_FORWARD], + ), + ( + ConfigurationStyle.LEGACY, + { + "value_template": "{{ 'abc' }}", + "percentage_template": "{{ 0 }}", + **OPTIMISTIC_PERCENTAGE_CONFIG, + "oscillating_template": "{{ 'xyz' }}", + **OSCILLATE_ACTION, + "direction_template": "{{ 'right' }}", + **DIRECTION_ACTION, + }, + [STATE_OFF, 0, None, None], + ), + ( + ConfigurationStyle.MODERN, + { + "state": "{{ 'abc' }}", + "percentage": "{{ 0 }}", + **OPTIMISTIC_PERCENTAGE_CONFIG, + "oscillating": "{{ 'xyz' }}", + **OSCILLATE_ACTION, + "direction": "{{ 'right' }}", + **DIRECTION_ACTION, }, [STATE_OFF, 0, None, None], ), ], ) -@pytest.mark.usefixtures("start_ha") +@pytest.mark.usefixtures("setup_named_fan") async def test_template_with_unavailable_entities(hass: HomeAssistant, states) -> None: """Test unavailability with value_template.""" _verify(hass, states[0], states[1], states[2], states[3], None) -@pytest.mark.parametrize(("count", "domain"), [(1, FAN_DOMAIN)]) +@pytest.mark.parametrize("count", [1]) @pytest.mark.parametrize( - "config", + ("style", "fan_config"), [ - { - FAN_DOMAIN: { - "platform": "template", - "fans": { - "test_fan": { - "value_template": "{{ 'on' }}", - "availability_template": "{{ x - 12 }}", - "preset_mode_template": ( - "{{ states('input_select.preset_mode') }}" - ), - "oscillating_template": "{{ states('input_select.osc') }}", - "direction_template": "{{ states('input_select.direction') }}", - "turn_on": {"service": "script.fan_on"}, - "turn_off": {"service": "script.fan_off"}, - } - }, - } - }, + ( + ConfigurationStyle.LEGACY, + { + "value_template": "{{ 'on' }}", + "availability_template": "{{ x - 12 }}", + "preset_mode_template": ("{{ states('input_select.preset_mode') }}"), + "oscillating_template": "{{ states('input_select.osc') }}", + "direction_template": "{{ states('input_select.direction') }}", + "turn_on": {"service": "script.fan_on"}, + "turn_off": {"service": "script.fan_off"}, + }, + ), + ( + ConfigurationStyle.MODERN, + { + "state": "{{ 'on' }}", + "availability": "{{ x - 12 }}", + "preset_mode": ("{{ states('input_select.preset_mode') }}"), + "oscillating": "{{ states('input_select.osc') }}", + "direction": "{{ states('input_select.direction') }}", + "turn_on": {"service": "script.fan_on"}, + "turn_off": {"service": "script.fan_off"}, + }, + ), ], ) -@pytest.mark.usefixtures("start_ha") +@pytest.mark.usefixtures("setup_named_fan") async def test_invalid_availability_template_keeps_component_available( hass: HomeAssistant, caplog_setup_text ) -> None: @@ -551,147 +833,380 @@ async def test_invalid_availability_template_keeps_component_available( assert "x" in caplog_setup_text +@pytest.mark.parametrize(("count", "extra_config"), [(1, OPTIMISTIC_ON_OFF_ACTIONS)]) +@pytest.mark.parametrize( + ("style", "fan_config"), + [ + ( + ConfigurationStyle.LEGACY, + { + "value_template": "{{ 'off' }}", + }, + ), + ( + ConfigurationStyle.MODERN, + { + "state": "{{ 'off' }}", + }, + ), + ], +) +@pytest.mark.usefixtures("setup_test_fan_with_extra_config") async def test_on_off(hass: HomeAssistant, calls: list[ServiceCall]) -> None: """Test turn on and turn off.""" - await _register_components(hass) - for expected_calls, (func, state, action) in enumerate( + state = hass.states.get(TEST_ENTITY_ID) + assert state.state == STATE_OFF + + for expected_calls, (func, action) in enumerate( [ - (common.async_turn_on, STATE_ON, "turn_on"), - (common.async_turn_off, STATE_OFF, "turn_off"), + (common.async_turn_on, "turn_on"), + (common.async_turn_off, "turn_off"), ] ): - await func(hass, _TEST_FAN) - assert hass.states.get(_STATE_INPUT_BOOLEAN).state == state - _verify(hass, state, 0, None, None, None) + await func(hass, TEST_ENTITY_ID) + assert len(calls) == expected_calls + 1 assert calls[-1].data["action"] == action - assert calls[-1].data["caller"] == _TEST_FAN + assert calls[-1].data["caller"] == TEST_ENTITY_ID -async def test_set_invalid_direction_from_initial_stage( +@pytest.mark.parametrize( + ("count", "extra_config"), + [ + ( + 1, + { + **OPTIMISTIC_ON_OFF_ACTIONS, + **OPTIMISTIC_PRESET_MODE_CONFIG2, + **OPTIMISTIC_PERCENTAGE_CONFIG, + }, + ) + ], +) +@pytest.mark.parametrize( + ("style", "fan_config"), + [ + ( + ConfigurationStyle.LEGACY, + { + "value_template": "{{ 'off' }}", + }, + ), + ( + ConfigurationStyle.MODERN, + { + "state": "{{ 'off' }}", + }, + ), + ], +) +@pytest.mark.usefixtures("setup_test_fan_with_extra_config") +async def test_on_with_extra_attributes( hass: HomeAssistant, calls: list[ServiceCall] ) -> None: + """Test turn on and turn off.""" + + state = hass.states.get(TEST_ENTITY_ID) + assert state.state == STATE_OFF + + await common.async_turn_on(hass, TEST_ENTITY_ID, 100) + + assert len(calls) == 2 + assert calls[-2].data["action"] == "turn_on" + assert calls[-2].data["caller"] == TEST_ENTITY_ID + + assert calls[-1].data["action"] == "set_percentage" + assert calls[-1].data["caller"] == TEST_ENTITY_ID + assert calls[-1].data["percentage"] == 100 + + await common.async_turn_off(hass, TEST_ENTITY_ID) + + assert len(calls) == 3 + assert calls[-1].data["action"] == "turn_off" + assert calls[-1].data["caller"] == TEST_ENTITY_ID + + await common.async_turn_on(hass, TEST_ENTITY_ID, None, "auto") + + assert len(calls) == 5 + assert calls[-2].data["action"] == "turn_on" + assert calls[-2].data["caller"] == TEST_ENTITY_ID + + assert calls[-1].data["action"] == "set_preset_mode" + assert calls[-1].data["caller"] == TEST_ENTITY_ID + assert calls[-1].data["preset_mode"] == "auto" + + await common.async_turn_off(hass, TEST_ENTITY_ID) + + assert len(calls) == 6 + assert calls[-1].data["action"] == "turn_off" + assert calls[-1].data["caller"] == TEST_ENTITY_ID + + await common.async_turn_on(hass, TEST_ENTITY_ID, 50, "high") + + assert len(calls) == 9 + assert calls[-3].data["action"] == "turn_on" + assert calls[-3].data["caller"] == TEST_ENTITY_ID + + assert calls[-2].data["action"] == "set_preset_mode" + assert calls[-2].data["caller"] == TEST_ENTITY_ID + assert calls[-2].data["preset_mode"] == "high" + + assert calls[-1].data["action"] == "set_percentage" + assert calls[-1].data["caller"] == TEST_ENTITY_ID + assert calls[-1].data["percentage"] == 50 + + await common.async_turn_off(hass, TEST_ENTITY_ID) + + assert len(calls) == 10 + assert calls[-1].data["action"] == "turn_off" + assert calls[-1].data["caller"] == TEST_ENTITY_ID + + +@pytest.mark.parametrize( + ("count", "extra_config"), [(1, {**OPTIMISTIC_ON_OFF_ACTIONS, **DIRECTION_ACTION})] +) +@pytest.mark.parametrize( + ("style", "fan_config"), + [ + ( + ConfigurationStyle.LEGACY, + { + "value_template": "{{ 'on' }}", + }, + ), + ( + ConfigurationStyle.MODERN, + { + "state": "{{ 'on' }}", + }, + ), + ], +) +@pytest.mark.usefixtures("setup_test_fan_with_extra_config") +async def test_set_invalid_direction_from_initial_stage(hass: HomeAssistant) -> None: """Test set invalid direction when fan is in initial state.""" - await _register_components(hass) - - await common.async_turn_on(hass, _TEST_FAN) - - await common.async_set_direction(hass, _TEST_FAN, "invalid") - - assert hass.states.get(_DIRECTION_INPUT_SELECT).state == "" - _verify(hass, STATE_ON, 0, None, None, None) + await common.async_set_direction(hass, TEST_ENTITY_ID, "invalid") + _verify(hass, STATE_ON, None, None, None, None) +@pytest.mark.parametrize( + ("count", "extra_config"), [(1, {**OPTIMISTIC_ON_OFF_ACTIONS, **OSCILLATE_ACTION})] +) +@pytest.mark.parametrize( + ("style", "fan_config"), + [ + ( + ConfigurationStyle.LEGACY, + { + "value_template": "{{ 'on' }}", + }, + ), + ( + ConfigurationStyle.MODERN, + { + "state": "{{ 'on' }}", + }, + ), + ], +) +@pytest.mark.usefixtures("setup_test_fan_with_extra_config") async def test_set_osc(hass: HomeAssistant, calls: list[ServiceCall]) -> None: """Test set oscillating.""" - await _register_components(hass) expected_calls = 0 - await common.async_turn_on(hass, _TEST_FAN) + await common.async_turn_on(hass, TEST_ENTITY_ID) expected_calls += 1 for state in (True, False): - await common.async_oscillate(hass, _TEST_FAN, state) - assert hass.states.get(_OSC_INPUT).state == str(state) - _verify(hass, STATE_ON, 0, state, None, None) + await common.async_oscillate(hass, TEST_ENTITY_ID, state) + _verify(hass, STATE_ON, None, state, None, None) expected_calls += 1 assert len(calls) == expected_calls assert calls[-1].data["action"] == "set_oscillating" - assert calls[-1].data["caller"] == _TEST_FAN - assert calls[-1].data["option"] == state + assert calls[-1].data["caller"] == TEST_ENTITY_ID + assert calls[-1].data["oscillating"] == state +@pytest.mark.parametrize( + ("count", "extra_config"), [(1, {**OPTIMISTIC_ON_OFF_ACTIONS, **DIRECTION_ACTION})] +) +@pytest.mark.parametrize( + ("style", "fan_config"), + [ + ( + ConfigurationStyle.LEGACY, + { + "value_template": "{{ 'on' }}", + }, + ), + ( + ConfigurationStyle.MODERN, + { + "state": "{{ 'on' }}", + }, + ), + ], +) +@pytest.mark.usefixtures("setup_test_fan_with_extra_config") async def test_set_direction(hass: HomeAssistant, calls: list[ServiceCall]) -> None: """Test set valid direction.""" - await _register_components(hass) expected_calls = 0 - await common.async_turn_on(hass, _TEST_FAN) + await common.async_turn_on(hass, TEST_ENTITY_ID) expected_calls += 1 - for cmd in (DIRECTION_FORWARD, DIRECTION_REVERSE): - await common.async_set_direction(hass, _TEST_FAN, cmd) - assert hass.states.get(_DIRECTION_INPUT_SELECT).state == cmd - _verify(hass, STATE_ON, 0, None, cmd, None) + for direction in (DIRECTION_FORWARD, DIRECTION_REVERSE): + await common.async_set_direction(hass, TEST_ENTITY_ID, direction) + _verify(hass, STATE_ON, None, None, direction, None) expected_calls += 1 assert len(calls) == expected_calls assert calls[-1].data["action"] == "set_direction" - assert calls[-1].data["caller"] == _TEST_FAN - assert calls[-1].data["option"] == cmd + assert calls[-1].data["caller"] == TEST_ENTITY_ID + assert calls[-1].data["direction"] == direction +@pytest.mark.parametrize( + ("count", "extra_config"), [(1, {**OPTIMISTIC_ON_OFF_ACTIONS, **DIRECTION_ACTION})] +) +@pytest.mark.parametrize( + ("style", "fan_config"), + [ + ( + ConfigurationStyle.LEGACY, + { + "value_template": "{{ 'on' }}", + }, + ), + ( + ConfigurationStyle.MODERN, + { + "state": "{{ 'on' }}", + }, + ), + ], +) +@pytest.mark.usefixtures("setup_test_fan_with_extra_config") async def test_set_invalid_direction( hass: HomeAssistant, calls: list[ServiceCall] ) -> None: """Test set invalid direction when fan has valid direction.""" - await _register_components(hass) - - await common.async_turn_on(hass, _TEST_FAN) - for cmd in (DIRECTION_FORWARD, "invalid"): - await common.async_set_direction(hass, _TEST_FAN, cmd) - assert hass.states.get(_DIRECTION_INPUT_SELECT).state == DIRECTION_FORWARD - _verify(hass, STATE_ON, 0, None, DIRECTION_FORWARD, None) + expected_calls = 1 + for direction in (DIRECTION_FORWARD, "invalid"): + await common.async_set_direction(hass, TEST_ENTITY_ID, direction) + _verify(hass, STATE_ON, None, None, DIRECTION_FORWARD, None) + assert len(calls) == expected_calls + assert calls[-1].data["action"] == "set_direction" + assert calls[-1].data["caller"] == TEST_ENTITY_ID + assert calls[-1].data["direction"] == DIRECTION_FORWARD +@pytest.mark.parametrize( + ("count", "extra_config"), [(1, OPTIMISTIC_PRESET_MODE_CONFIG2)] +) +@pytest.mark.parametrize( + ("style", "fan_config"), + [ + ( + ConfigurationStyle.LEGACY, + { + "value_template": "{{ 'on' }}", + }, + ), + ( + ConfigurationStyle.MODERN, + { + "state": "{{ 'on' }}", + }, + ), + ], +) +@pytest.mark.usefixtures("setup_test_fan_with_extra_config") async def test_preset_modes(hass: HomeAssistant, calls: list[ServiceCall]) -> None: """Test preset_modes.""" - await _register_components( - hass, ["off", "low", "medium", "high", "auto", "smart"], ["auto", "smart"] - ) - - await common.async_turn_on(hass, _TEST_FAN) - for extra, state, expected_calls in ( - ("auto", "auto", 2), - ("smart", "smart", 3), - ("invalid", "smart", 3), - ): - if extra != state: + expected_calls = 0 + valid_modes = OPTIMISTIC_PRESET_MODE_CONFIG2["preset_modes"] + for mode in ("auto", "low", "medium", "high", "invalid", "smart"): + if mode not in valid_modes: with pytest.raises(NotValidPresetModeError): - await common.async_set_preset_mode(hass, _TEST_FAN, extra) + await common.async_set_preset_mode(hass, TEST_ENTITY_ID, mode) else: - await common.async_set_preset_mode(hass, _TEST_FAN, extra) - assert hass.states.get(_PRESET_MODE_INPUT_SELECT).state == state - assert len(calls) == expected_calls - assert calls[-1].data["action"] == "set_preset_mode" - assert calls[-1].data["caller"] == _TEST_FAN - assert calls[-1].data["option"] == state + await common.async_set_preset_mode(hass, TEST_ENTITY_ID, mode) + expected_calls += 1 - await common.async_turn_on(hass, _TEST_FAN, preset_mode="auto") - assert hass.states.get(_PRESET_MODE_INPUT_SELECT).state == "auto" + assert len(calls) == expected_calls + assert calls[-1].data["action"] == "set_preset_mode" + assert calls[-1].data["caller"] == TEST_ENTITY_ID + assert calls[-1].data["preset_mode"] == mode +@pytest.mark.parametrize(("count", "extra_config"), [(1, OPTIMISTIC_PERCENTAGE_CONFIG)]) +@pytest.mark.parametrize( + ("style", "fan_config"), + [ + ( + ConfigurationStyle.LEGACY, + { + "value_template": "{{ 'on' }}", + }, + ), + ( + ConfigurationStyle.MODERN, + { + "state": "{{ 'on' }}", + }, + ), + ], +) +@pytest.mark.usefixtures("setup_test_fan_with_extra_config") async def test_set_percentage(hass: HomeAssistant, calls: list[ServiceCall]) -> None: """Test set valid speed percentage.""" - await _register_components(hass) expected_calls = 0 - await common.async_turn_on(hass, _TEST_FAN) + await common.async_turn_on(hass, TEST_ENTITY_ID) expected_calls += 1 for state, value in ( (STATE_ON, 100), (STATE_ON, 66), (STATE_ON, 0), ): - await common.async_set_percentage(hass, _TEST_FAN, value) - assert int(float(hass.states.get(_PERCENTAGE_INPUT_NUMBER).state)) == value + await common.async_set_percentage(hass, TEST_ENTITY_ID, value) _verify(hass, state, value, None, None, None) expected_calls += 1 assert len(calls) == expected_calls - assert calls[-1].data["action"] == "set_value" - assert calls[-1].data["caller"] == _TEST_FAN - assert calls[-1].data["value"] == value + assert calls[-1].data["action"] == "set_percentage" + assert calls[-1].data["caller"] == TEST_ENTITY_ID + assert calls[-1].data["percentage"] == value - await common.async_turn_on(hass, _TEST_FAN, percentage=50) - assert int(float(hass.states.get(_PERCENTAGE_INPUT_NUMBER).state)) == 50 + await common.async_turn_on(hass, TEST_ENTITY_ID, percentage=50) _verify(hass, STATE_ON, 50, None, None, None) +@pytest.mark.parametrize( + ("count", "extra_config"), [(1, {"speed_count": 3, **OPTIMISTIC_PERCENTAGE_CONFIG})] +) +@pytest.mark.parametrize( + ("style", "fan_config"), + [ + ( + ConfigurationStyle.LEGACY, + { + "value_template": "{{ 'on' }}", + }, + ), + ( + ConfigurationStyle.MODERN, + { + "state": "{{ 'on' }}", + }, + ), + ], +) +@pytest.mark.usefixtures("setup_test_fan_with_extra_config") async def test_increase_decrease_speed( hass: HomeAssistant, calls: list[ServiceCall] ) -> None: """Test set valid increase and decrease speed.""" - await _register_components(hass, speed_count=3) - await common.async_turn_on(hass, _TEST_FAN) + await common.async_turn_on(hass, TEST_ENTITY_ID) for func, extra, state, value in ( (common.async_set_percentage, 100, STATE_ON, 100), (common.async_decrease_speed, None, STATE_ON, 66), @@ -699,100 +1214,101 @@ async def test_increase_decrease_speed( (common.async_decrease_speed, None, STATE_ON, 0), (common.async_increase_speed, None, STATE_ON, 33), ): - await func(hass, _TEST_FAN, extra) - assert int(float(hass.states.get(_PERCENTAGE_INPUT_NUMBER).state)) == value + await func(hass, TEST_ENTITY_ID, extra) _verify(hass, state, value, None, None, None) +@pytest.mark.parametrize( + ("count", "fan_config"), + [ + ( + 1, + { + **OPTIMISTIC_ON_OFF_ACTIONS, + "preset_modes": ["auto"], + **PRESET_MODE_ACTION, + **PERCENTAGE_ACTION, + **OSCILLATE_ACTION, + **DIRECTION_ACTION, + }, + ) + ], +) +@pytest.mark.parametrize( + "style", + [ConfigurationStyle.LEGACY, ConfigurationStyle.MODERN], +) +@pytest.mark.usefixtures("setup_named_fan") async def test_optimistic_state(hass: HomeAssistant, calls: list[ServiceCall]) -> None: """Test a fan without a value_template.""" - await _register_fan_sources(hass) - with assert_setup_component(1, "fan"): - test_fan_config = { - **OPTIMISTIC_ON_OFF_CONFIG, - "preset_modes": ["auto"], - **PRESET_MODE_ACTION, - **PERCENTAGE_ACTION, - **OSCILLATE_ACTION, - **DIRECTION_ACTION, - } - assert await setup.async_setup_component( - hass, - "fan", - {"fan": {"platform": "template", "fans": {"test_fan": test_fan_config}}}, - ) - - await hass.async_block_till_done() - await hass.async_start() - await hass.async_block_till_done() - - await common.async_turn_on(hass, _TEST_FAN) + await common.async_turn_on(hass, TEST_ENTITY_ID) _verify(hass, STATE_ON) assert len(calls) == 1 assert calls[-1].data["action"] == "turn_on" - assert calls[-1].data["caller"] == _TEST_FAN + assert calls[-1].data["caller"] == TEST_ENTITY_ID - await common.async_turn_off(hass, _TEST_FAN) + await common.async_turn_off(hass, TEST_ENTITY_ID) _verify(hass, STATE_OFF) assert len(calls) == 2 assert calls[-1].data["action"] == "turn_off" - assert calls[-1].data["caller"] == _TEST_FAN + assert calls[-1].data["caller"] == TEST_ENTITY_ID percent = 100 - await common.async_set_percentage(hass, _TEST_FAN, percent) + await common.async_set_percentage(hass, TEST_ENTITY_ID, percent) _verify(hass, STATE_ON, percent) assert len(calls) == 3 assert calls[-1].data["action"] == "set_percentage" assert calls[-1].data["percentage"] == 100 - assert calls[-1].data["caller"] == _TEST_FAN + assert calls[-1].data["caller"] == TEST_ENTITY_ID - await common.async_turn_off(hass, _TEST_FAN) + await common.async_turn_off(hass, TEST_ENTITY_ID) _verify(hass, STATE_OFF, percent) assert len(calls) == 4 assert calls[-1].data["action"] == "turn_off" - assert calls[-1].data["caller"] == _TEST_FAN + assert calls[-1].data["caller"] == TEST_ENTITY_ID preset = "auto" - await common.async_set_preset_mode(hass, _TEST_FAN, preset) - assert hass.states.get(_PRESET_MODE_INPUT_SELECT).state == preset + await common.async_set_preset_mode(hass, TEST_ENTITY_ID, preset) _verify(hass, STATE_ON, percent, None, None, preset) assert len(calls) == 5 assert calls[-1].data["action"] == "set_preset_mode" assert calls[-1].data["preset_mode"] == preset - assert calls[-1].data["caller"] == _TEST_FAN + assert calls[-1].data["caller"] == TEST_ENTITY_ID - await common.async_turn_off(hass, _TEST_FAN) + await common.async_turn_off(hass, TEST_ENTITY_ID) _verify(hass, STATE_OFF, percent, None, None, preset) assert len(calls) == 6 assert calls[-1].data["action"] == "turn_off" - assert calls[-1].data["caller"] == _TEST_FAN + assert calls[-1].data["caller"] == TEST_ENTITY_ID - await common.async_set_direction(hass, _TEST_FAN, DIRECTION_FORWARD) + await common.async_set_direction(hass, TEST_ENTITY_ID, DIRECTION_FORWARD) _verify(hass, STATE_OFF, percent, None, DIRECTION_FORWARD, preset) assert len(calls) == 7 assert calls[-1].data["action"] == "set_direction" assert calls[-1].data["direction"] == DIRECTION_FORWARD - assert calls[-1].data["caller"] == _TEST_FAN + assert calls[-1].data["caller"] == TEST_ENTITY_ID - await common.async_oscillate(hass, _TEST_FAN, True) + await common.async_oscillate(hass, TEST_ENTITY_ID, True) _verify(hass, STATE_OFF, percent, True, DIRECTION_FORWARD, preset) assert len(calls) == 8 assert calls[-1].data["action"] == "set_oscillating" assert calls[-1].data["oscillating"] is True - assert calls[-1].data["caller"] == _TEST_FAN + assert calls[-1].data["caller"] == TEST_ENTITY_ID @pytest.mark.parametrize("count", [1]) -@pytest.mark.parametrize("style", [ConfigurationStyle.LEGACY]) +@pytest.mark.parametrize( + "style", [ConfigurationStyle.LEGACY, ConfigurationStyle.MODERN] +) @pytest.mark.parametrize( ("extra_config", "attribute", "action", "verify_attr", "coro", "value"), [ @@ -830,6 +1346,7 @@ async def test_optimistic_state(hass: HomeAssistant, calls: list[ServiceCall]) - ), ], ) +@pytest.mark.usefixtures("setup_optimistic_fan_attribute") async def test_optimistic_attributes( hass: HomeAssistant, attribute: str, @@ -837,27 +1354,43 @@ async def test_optimistic_attributes( verify_attr: str, coro, value: Any, - setup_optimistic_fan_attribute, calls: list[ServiceCall], ) -> None: """Test setting percentage with optimistic template.""" - await coro(hass, _TEST_FAN, value) + await coro(hass, TEST_ENTITY_ID, value) _verify(hass, STATE_ON, **{verify_attr: value}) assert len(calls) == 1 assert calls[-1].data["action"] == action assert calls[-1].data[attribute] == value - assert calls[-1].data["caller"] == _TEST_FAN + assert calls[-1].data["caller"] == TEST_ENTITY_ID +@pytest.mark.parametrize(("count", "extra_config"), [(1, OPTIMISTIC_PERCENTAGE_CONFIG)]) +@pytest.mark.parametrize( + ("style", "fan_config"), + [ + ( + ConfigurationStyle.LEGACY, + { + "value_template": "{{ 'on' }}", + }, + ), + ( + ConfigurationStyle.MODERN, + { + "state": "{{ 'on' }}", + }, + ), + ], +) +@pytest.mark.usefixtures("setup_test_fan_with_extra_config") async def test_increase_decrease_speed_default_speed_count( hass: HomeAssistant, calls: list[ServiceCall] ) -> None: """Test set valid increase and decrease speed.""" - await _register_components(hass) - - await common.async_turn_on(hass, _TEST_FAN) + await common.async_turn_on(hass, TEST_ENTITY_ID) for func, extra, state, value in ( (common.async_set_percentage, 100, STATE_ON, 100), (common.async_decrease_speed, None, STATE_ON, 99), @@ -865,432 +1398,146 @@ async def test_increase_decrease_speed_default_speed_count( (common.async_decrease_speed, 31, STATE_ON, 67), (common.async_decrease_speed, None, STATE_ON, 66), ): - await func(hass, _TEST_FAN, extra) - assert int(float(hass.states.get(_PERCENTAGE_INPUT_NUMBER).state)) == value + await func(hass, TEST_ENTITY_ID, extra) _verify(hass, state, value, None, None, None) +@pytest.mark.parametrize( + ("count", "extra_config"), [(1, {**OPTIMISTIC_ON_OFF_ACTIONS, **OSCILLATE_ACTION})] +) +@pytest.mark.parametrize( + ("style", "fan_config"), + [ + ( + ConfigurationStyle.LEGACY, + { + "value_template": "{{ 'on' }}", + }, + ), + ( + ConfigurationStyle.MODERN, + { + "state": "{{ 'on' }}", + }, + ), + ], +) +@pytest.mark.usefixtures("setup_test_fan_with_extra_config") async def test_set_invalid_osc_from_initial_state( hass: HomeAssistant, calls: list[ServiceCall] ) -> None: """Test set invalid oscillating when fan is in initial state.""" - await _register_components(hass) - - await common.async_turn_on(hass, _TEST_FAN) + await common.async_turn_on(hass, TEST_ENTITY_ID) with pytest.raises(vol.Invalid): - await common.async_oscillate(hass, _TEST_FAN, "invalid") - assert hass.states.get(_OSC_INPUT).state == "" - _verify(hass, STATE_ON, 0, None, None, None) + await common.async_oscillate(hass, TEST_ENTITY_ID, "invalid") + _verify(hass, STATE_ON, None, None, None, None) -async def test_set_invalid_osc(hass: HomeAssistant, calls: list[ServiceCall]) -> None: - """Test set invalid oscillating when fan has valid osc.""" - await _register_components(hass) - - await common.async_turn_on(hass, _TEST_FAN) - await common.async_oscillate(hass, _TEST_FAN, True) - assert hass.states.get(_OSC_INPUT).state == "True" - _verify(hass, STATE_ON, 0, True, None, None) - - with pytest.raises(vol.Invalid): - await common.async_oscillate(hass, _TEST_FAN, None) - assert hass.states.get(_OSC_INPUT).state == "True" - _verify(hass, STATE_ON, 0, True, None, None) - - -def _verify( - hass: HomeAssistant, - expected_state: str, - expected_percentage: int | None = None, - expected_oscillating: bool | None = None, - expected_direction: str | None = None, - expected_preset_mode: str | None = None, -) -> None: - """Verify fan's state, speed and osc.""" - state = hass.states.get(_TEST_FAN) - attributes = state.attributes - assert state.state == str(expected_state) - assert attributes.get(ATTR_PERCENTAGE) == expected_percentage - assert attributes.get(ATTR_OSCILLATING) == expected_oscillating - assert attributes.get(ATTR_DIRECTION) == expected_direction - assert attributes.get(ATTR_PRESET_MODE) == expected_preset_mode - - -async def _register_fan_sources(hass: HomeAssistant) -> None: - with assert_setup_component(1, "input_boolean"): - assert await setup.async_setup_component( - hass, "input_boolean", {"input_boolean": {"state": None}} - ) - - with assert_setup_component(1, "input_number"): - assert await setup.async_setup_component( - hass, - "input_number", - { - "input_number": { - "percentage": { - "min": 0.0, - "max": 100.0, - "name": "Percentage", - "step": 1.0, - "mode": "slider", - } - } - }, - ) - - with assert_setup_component(3, "input_select"): - assert await setup.async_setup_component( - hass, - "input_select", - { - "input_select": { - "preset_mode": { - "name": "Preset Mode", - "options": ["auto", "smart"], - }, - "osc": {"name": "oscillating", "options": ["", "True", "False"]}, - "direction": { - "name": "Direction", - "options": ["", DIRECTION_FORWARD, DIRECTION_REVERSE], - }, - } - }, - ) - - -async def _register_components( - hass: HomeAssistant, - speed_list: list[str] | None = None, - preset_modes: list[str] | None = None, - speed_count: int | None = None, -) -> None: - """Register basic components for testing.""" - await _register_fan_sources(hass) - - with assert_setup_component(1, "fan"): - value_template = """ - {% if is_state('input_boolean.state', 'on') %} - {{ 'on' }} - {% else %} - {{ 'off' }} - {% endif %} - """ - - test_fan_config = { - "value_template": value_template, - "preset_mode_template": "{{ states('input_select.preset_mode') }}", - "percentage_template": "{{ states('input_number.percentage') }}", - "oscillating_template": "{{ states('input_select.osc') }}", - "direction_template": "{{ states('input_select.direction') }}", - "turn_on": [ - { - "service": "input_boolean.turn_on", - "entity_id": _STATE_INPUT_BOOLEAN, - }, - { - "service": "test.automation", - "data_template": { - "action": "turn_on", - "caller": "{{ this.entity_id }}", - }, - }, - ], - "turn_off": [ - { - "service": "input_boolean.turn_off", - "entity_id": _STATE_INPUT_BOOLEAN, - }, - { - "service": "input_number.set_value", - "data_template": { - "entity_id": _PERCENTAGE_INPUT_NUMBER, - "value": 0, - }, - }, - { - "service": "test.automation", - "data_template": { - "action": "turn_off", - "caller": "{{ this.entity_id }}", - }, - }, - ], - "set_preset_mode": [ - { - "service": "input_select.select_option", - "data_template": { - "entity_id": _PRESET_MODE_INPUT_SELECT, - "option": "{{ preset_mode }}", - }, - }, - { - "service": "test.automation", - "data_template": { - "action": "set_preset_mode", - "caller": "{{ this.entity_id }}", - "option": "{{ preset_mode }}", - }, - }, - ], - "set_percentage": [ - { - "service": "input_number.set_value", - "data_template": { - "entity_id": _PERCENTAGE_INPUT_NUMBER, - "value": "{{ percentage }}", - }, - }, - { - "service": "test.automation", - "data_template": { - "action": "set_value", - "caller": "{{ this.entity_id }}", - "value": "{{ percentage }}", - }, - }, - ], - "set_oscillating": [ - { - "service": "input_select.select_option", - "data_template": { - "entity_id": _OSC_INPUT, - "option": "{{ oscillating }}", - }, - }, - { - "service": "test.automation", - "data_template": { - "action": "set_oscillating", - "caller": "{{ this.entity_id }}", - "option": "{{ oscillating }}", - }, - }, - ], - "set_direction": [ - { - "service": "input_select.select_option", - "data_template": { - "entity_id": _DIRECTION_INPUT_SELECT, - "option": "{{ direction }}", - }, - }, - { - "service": "test.automation", - "data_template": { - "action": "set_direction", - "caller": "{{ this.entity_id }}", - "option": "{{ direction }}", - }, - }, - ], - } - - if preset_modes: - test_fan_config["preset_modes"] = preset_modes - - if speed_count: - test_fan_config["speed_count"] = speed_count - - assert await setup.async_setup_component( - hass, - "fan", - {"fan": {"platform": "template", "fans": {"test_fan": test_fan_config}}}, - ) - - await hass.async_block_till_done() - await hass.async_start() - await hass.async_block_till_done() - - -@pytest.mark.parametrize(("count", "domain"), [(1, FAN_DOMAIN)]) @pytest.mark.parametrize( - "config", + ("count", "extra_config"), [(1, {**OPTIMISTIC_ON_OFF_ACTIONS, **OSCILLATE_ACTION})] +) +@pytest.mark.parametrize( + ("style", "fan_config"), [ - { - FAN_DOMAIN: { - "platform": "template", - "fans": { - "test_template_fan_01": { - "unique_id": "not-so-unique-anymore", - "value_template": "{{ true }}", - "turn_on": { - "service": "fan.turn_on", - "entity_id": "fan.test_state", - }, - "turn_off": { - "service": "fan.turn_off", - "entity_id": "fan.test_state", - }, - }, - "test_template_fan_02": { - "unique_id": "not-so-unique-anymore", - "value_template": "{{ false }}", - "turn_on": { - "service": "fan.turn_on", - "entity_id": "fan.test_state", - }, - "turn_off": { - "service": "fan.turn_off", - "entity_id": "fan.test_state", - }, - }, - }, - } - }, + ( + ConfigurationStyle.LEGACY, + { + "value_template": "{{ 'on' }}", + }, + ), + ( + ConfigurationStyle.MODERN, + { + "state": "{{ 'on' }}", + }, + ), ], ) -@pytest.mark.usefixtures("start_ha") +@pytest.mark.usefixtures("setup_test_fan_with_extra_config") +async def test_set_invalid_osc(hass: HomeAssistant, calls: list[ServiceCall]) -> None: + """Test set invalid oscillating when fan has valid osc.""" + await common.async_turn_on(hass, TEST_ENTITY_ID) + await common.async_oscillate(hass, TEST_ENTITY_ID, True) + _verify(hass, STATE_ON, None, True, None, None) + + await common.async_oscillate(hass, TEST_ENTITY_ID, False) + _verify(hass, STATE_ON, None, False, None, None) + + with pytest.raises(vol.Invalid): + await common.async_oscillate(hass, TEST_ENTITY_ID, None) + _verify(hass, STATE_ON, None, False, None, None) + + +@pytest.mark.parametrize("count", [1]) +@pytest.mark.parametrize( + ("fan_config", "style"), + [ + ( + { + "test_template_cover_01": UNIQUE_ID_CONFIG, + "test_template_cover_02": UNIQUE_ID_CONFIG, + }, + ConfigurationStyle.LEGACY, + ), + ( + [ + { + "name": "test_template_cover_01", + **UNIQUE_ID_CONFIG, + }, + { + "name": "test_template_cover_02", + **UNIQUE_ID_CONFIG, + }, + ], + ConfigurationStyle.MODERN, + ), + ], +) +@pytest.mark.usefixtures("setup_fan") async def test_unique_id(hass: HomeAssistant) -> None: """Test unique_id option only creates one fan per id.""" assert len(hass.states.async_all()) == 1 @pytest.mark.parametrize( - ("speed_count", "percentage_step"), [(0, 1), (100, 1), (3, 100 / 3)] + ("count", "extra_config"), + [(1, {**OPTIMISTIC_ON_OFF_ACTIONS, **OPTIMISTIC_PERCENTAGE_CONFIG})], ) -async def test_implemented_percentage( - hass: HomeAssistant, speed_count, percentage_step -) -> None: +@pytest.mark.parametrize( + "style", + [ConfigurationStyle.LEGACY, ConfigurationStyle.MODERN], +) +@pytest.mark.parametrize( + ("fan_config", "percentage_step"), + [({"speed_count": 0}, 1), ({"speed_count": 100}, 1), ({"speed_count": 3}, 100 / 3)], +) +@pytest.mark.usefixtures("setup_test_fan_with_extra_config") +async def test_speed_percentage_step(hass: HomeAssistant, percentage_step) -> None: """Test a fan that implements percentage.""" - await setup.async_setup_component( - hass, - "fan", - { - "fan": { - "platform": "template", - "fans": { - "mechanical_ventilation": { - "friendly_name": "Mechanische ventilatie", - "unique_id": "a2fd2e38-674b-4b47-b5ef-cc2362211a72", - "value_template": "{{ states('light.mv_snelheid') }}", - "percentage_template": ( - "{{ (state_attr('light.mv_snelheid','brightness') | int /" - " 255 * 100) | int }}" - ), - "turn_on": [ - { - "service": "switch.turn_off", - "target": { - "entity_id": "switch.mv_automatisch", - }, - }, - { - "service": "light.turn_on", - "target": { - "entity_id": "light.mv_snelheid", - }, - "data": {"brightness_pct": 40}, - }, - ], - "turn_off": [ - { - "service": "light.turn_off", - "target": { - "entity_id": "light.mv_snelheid", - }, - }, - { - "service": "switch.turn_on", - "target": { - "entity_id": "switch.mv_automatisch", - }, - }, - ], - "set_percentage": [ - { - "service": "light.turn_on", - "target": { - "entity_id": "light.mv_snelheid", - }, - "data": {"brightness_pct": "{{ percentage }}"}, - } - ], - "speed_count": speed_count, - }, - }, - }, - }, - ) - - await hass.async_block_till_done() - await hass.async_start() - await hass.async_block_till_done() - assert len(hass.states.async_all()) == 1 - state = hass.states.get("fan.mechanical_ventilation") + state = hass.states.get(TEST_ENTITY_ID) attributes = state.attributes assert attributes["percentage_step"] == percentage_step assert attributes.get("supported_features") & FanEntityFeature.SET_SPEED -@pytest.mark.parametrize(("count", "domain"), [(1, FAN_DOMAIN)]) @pytest.mark.parametrize( - "config", - [ - { - FAN_DOMAIN: { - "platform": "template", - "fans": { - "mechanical_ventilation": { - "friendly_name": "Mechanische ventilatie", - "unique_id": "a2fd2e38-674b-4b47-b5ef-cc2362211a72", - "value_template": "{{ states('light.mv_snelheid') }}", - "preset_mode_template": "{{ 'any' }}", - "preset_modes": ["any"], - "set_preset_mode": [ - { - "service": "light.turn_on", - "target": { - "entity_id": "light.mv_snelheid", - }, - "data": {"brightness_pct": "{{ percentage }}"}, - } - ], - "turn_on": [ - { - "service": "switch.turn_off", - "target": { - "entity_id": "switch.mv_automatisch", - }, - }, - { - "service": "light.turn_on", - "target": { - "entity_id": "light.mv_snelheid", - }, - "data": {"brightness_pct": 40}, - }, - ], - "turn_off": [ - { - "service": "light.turn_off", - "target": { - "entity_id": "light.mv_snelheid", - }, - }, - { - "service": "switch.turn_on", - "target": { - "entity_id": "switch.mv_automatisch", - }, - }, - ], - }, - }, - } - }, - ], + ("count", "fan_config"), + [(1, {**OPTIMISTIC_ON_OFF_ACTIONS, **OPTIMISTIC_PRESET_MODE_CONFIG2})], ) -@pytest.mark.usefixtures("start_ha") -async def test_implemented_preset_mode(hass: HomeAssistant) -> None: +@pytest.mark.parametrize( + "style", + [ConfigurationStyle.LEGACY, ConfigurationStyle.MODERN], +) +@pytest.mark.usefixtures("setup_named_fan") +async def test_preset_mode_supported_features(hass: HomeAssistant) -> None: """Test a fan that implements preset_mode.""" assert len(hass.states.async_all()) == 1 - state = hass.states.get("fan.mechanical_ventilation") + state = hass.states.get(TEST_ENTITY_ID) attributes = state.attributes - assert attributes.get("percentage") is None assert attributes.get("supported_features") & FanEntityFeature.PRESET_MODE @@ -1305,6 +1552,13 @@ async def test_implemented_preset_mode(hass: HomeAssistant) -> None: "turn_off": [], }, ), + ( + ConfigurationStyle.MODERN, + { + "turn_on": [], + "turn_off": [], + }, + ), ], ) @pytest.mark.parametrize( @@ -1342,7 +1596,51 @@ async def test_empty_action_config( setup_test_fan_with_extra_config, ) -> None: """Test configuration with empty script.""" - state = hass.states.get(_TEST_FAN) + state = hass.states.get(TEST_ENTITY_ID) assert state.attributes["supported_features"] == ( FanEntityFeature.TURN_OFF | FanEntityFeature.TURN_ON | supported_features ) + + +async def test_nested_unique_id( + hass: HomeAssistant, entity_registry: er.EntityRegistry +) -> None: + """Test a template unique_id propagates to switch unique_ids.""" + with assert_setup_component(1, template.DOMAIN): + assert await async_setup_component( + hass, + template.DOMAIN, + { + "template": { + "unique_id": "x", + "fan": [ + { + **OPTIMISTIC_ON_OFF_ACTIONS, + "name": "test_a", + "unique_id": "a", + "state": "{{ true }}", + }, + { + **OPTIMISTIC_ON_OFF_ACTIONS, + "name": "test_b", + "unique_id": "b", + "state": "{{ true }}", + }, + ], + }, + }, + ) + + await hass.async_block_till_done() + await hass.async_start() + await hass.async_block_till_done() + + assert len(hass.states.async_all("fan")) == 2 + + entry = entity_registry.async_get("fan.test_a") + assert entry + assert entry.unique_id == "x-a" + + entry = entity_registry.async_get("fan.test_b") + assert entry + assert entry.unique_id == "x-b"