From c0c656f9108f38ec1f8ee8a4e309e5688692fadf Mon Sep 17 00:00:00 2001 From: Erik Montnemery Date: Wed, 2 Dec 2026 16:27:21 +0100 Subject: [PATCH] Fix validation error paths for trigger and condition options (#196035) --- homeassistant/components/calendar/trigger.py | 8 +- homeassistant/components/knx/trigger.py | 8 +- homeassistant/components/sun/condition.py | 8 +- homeassistant/components/sun/trigger.py | 8 +- .../components/webostv/triggers/turn_on.py | 8 +- homeassistant/components/zone/condition.py | 8 +- homeassistant/components/zone/trigger.py | 8 +- .../components/zwave_js/triggers/event.py | 8 +- .../zwave_js/triggers/value_updated.py | 8 +- homeassistant/helpers/automation.py | 59 +++- homeassistant/helpers/trigger/__init__.py | 14 +- tests/components/calendar/test_trigger.py | 53 ++++ .../triggers/test_numeric_state.py | 34 ++ .../homeassistant/triggers/test_state.py | 49 +++ tests/components/knx/test_trigger.py | 46 ++- tests/components/sun/test_condition.py | 44 +++ tests/components/sun/test_trigger.py | 43 +++ tests/components/webostv/test_trigger.py | 40 +++ tests/components/zone/test_condition.py | 43 +++ tests/components/zone/test_trigger.py | 40 +++ tests/components/zwave_js/test_trigger.py | 107 +++++++ tests/helpers/test_automation.py | 297 ++++++++++++++++++ tests/helpers/test_condition.py | 82 +++++ tests/helpers/test_trigger.py | 168 ++++++++++ 24 files changed, 1147 insertions(+), 44 deletions(-) diff --git a/homeassistant/components/calendar/trigger.py b/homeassistant/components/calendar/trigger.py index 9ea753394b13..abbddf5068e5 100644 --- a/homeassistant/components/calendar/trigger.py +++ b/homeassistant/components/calendar/trigger.py @@ -20,7 +20,7 @@ from homeassistant.const import ( from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback, split_entity_id from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import config_validation as cv -from homeassistant.helpers.automation import move_top_level_schema_fields_to_options +from homeassistant.helpers.automation import validate_top_level_schema_fields_in_options from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.event import ( async_track_point_in_time, @@ -425,10 +425,10 @@ class SingleEntityEventTrigger(Trigger): cls, hass: HomeAssistant, complete_config: ConfigType ) -> ConfigType: """Validate complete config.""" - complete_config = move_top_level_schema_fields_to_options( + with validate_top_level_schema_fields_in_options( complete_config, _SINGLE_ENTITY_EVENT_OPTIONS_SCHEMA - ) - return await super().async_validate_complete_config(hass, complete_config) + ) as config: + return await super().async_validate_complete_config(hass, config) @classmethod @override diff --git a/homeassistant/components/knx/trigger.py b/homeassistant/components/knx/trigger.py index f0d19856007a..0de71697049b 100644 --- a/homeassistant/components/knx/trigger.py +++ b/homeassistant/components/knx/trigger.py @@ -12,7 +12,7 @@ from xknx.telegram.apci import GroupValueRead, GroupValueResponse, GroupValueWri from homeassistant.const import CONF_OPTIONS, CONF_TYPE from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback from homeassistant.helpers import config_validation as cv -from homeassistant.helpers.automation import move_top_level_schema_fields_to_options +from homeassistant.helpers.automation import validate_top_level_schema_fields_in_options from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.trigger import ( Trigger, @@ -134,10 +134,10 @@ class TelegramTrigger(Trigger): cls, hass: HomeAssistant, complete_config: ConfigType ) -> ConfigType: """Validate complete config, migrating the legacy top-level fields.""" - complete_config = move_top_level_schema_fields_to_options( + with validate_top_level_schema_fields_in_options( complete_config, _OPTIONS_SCHEMA_DICT - ) - return await super().async_validate_complete_config(hass, complete_config) + ) as config: + return await super().async_validate_complete_config(hass, config) @override @classmethod diff --git a/homeassistant/components/sun/condition.py b/homeassistant/components/sun/condition.py index 06311a649387..bba7b11428ca 100644 --- a/homeassistant/components/sun/condition.py +++ b/homeassistant/components/sun/condition.py @@ -19,7 +19,7 @@ from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv from homeassistant.helpers.automation import ( DomainSpec, - move_top_level_schema_fields_to_options, + validate_top_level_schema_fields_in_options, ) from homeassistant.helpers.condition import ( ATTR_BEHAVIOR, @@ -169,10 +169,10 @@ class SunCondition(Condition): cls, hass: HomeAssistant, complete_config: ConfigType ) -> ConfigType: """Validate complete config.""" - complete_config = move_top_level_schema_fields_to_options( + with validate_top_level_schema_fields_in_options( complete_config, _OPTIONS_SCHEMA_DICT - ) - return await super().async_validate_complete_config(hass, complete_config) + ) as config: + return await super().async_validate_complete_config(hass, config) @classmethod @override diff --git a/homeassistant/components/sun/trigger.py b/homeassistant/components/sun/trigger.py index c8d333bc6bec..f0064d5627ce 100644 --- a/homeassistant/components/sun/trigger.py +++ b/homeassistant/components/sun/trigger.py @@ -22,7 +22,7 @@ from homeassistant.core import CALLBACK_TYPE, Event, HomeAssistant, callback from homeassistant.helpers import config_validation as cv from homeassistant.helpers.automation import ( DomainSpec, - move_top_level_schema_fields_to_options, + validate_top_level_schema_fields_in_options, ) from homeassistant.helpers.event import async_track_point_in_utc_time from homeassistant.helpers.selector import ( @@ -592,10 +592,10 @@ class LegacySunTrigger(SunEventTrigger): cls, hass: HomeAssistant, complete_config: ConfigType ) -> ConfigType: """Validate complete config, migrating the legacy top-level fields.""" - complete_config = move_top_level_schema_fields_to_options( + with validate_top_level_schema_fields_in_options( complete_config, _LEGACY_OPTIONS_SCHEMA_DICT - ) - return await super().async_validate_complete_config(hass, complete_config) + ) as config: + return await super().async_validate_complete_config(hass, config) def __init__(self, hass: HomeAssistant, config: TriggerConfig) -> None: """Initialize the trigger.""" diff --git a/homeassistant/components/webostv/triggers/turn_on.py b/homeassistant/components/webostv/triggers/turn_on.py index c7278fe8fa32..bd98f8a71fe7 100644 --- a/homeassistant/components/webostv/triggers/turn_on.py +++ b/homeassistant/components/webostv/triggers/turn_on.py @@ -16,7 +16,7 @@ from homeassistant.const import ( ) from homeassistant.core import CALLBACK_TYPE, Context, HomeAssistant, callback from homeassistant.helpers import config_validation as cv -from homeassistant.helpers.automation import move_top_level_schema_fields_to_options +from homeassistant.helpers.automation import validate_top_level_schema_fields_in_options from homeassistant.helpers.trigger import ( PluggableAction, Trigger, @@ -79,10 +79,10 @@ class TurnOnTrigger(Trigger): cls, hass: HomeAssistant, complete_config: ConfigType ) -> ConfigType: """Validate complete config, moving legacy fields to options.""" - complete_config = move_top_level_schema_fields_to_options( + with validate_top_level_schema_fields_in_options( complete_config, _OPTIONS_SCHEMA_DICT - ) - return await super().async_validate_complete_config(hass, complete_config) + ) as config: + return await super().async_validate_complete_config(hass, config) @classmethod @override diff --git a/homeassistant/components/zone/condition.py b/homeassistant/components/zone/condition.py index 83d409e174d7..92d7d3df7a04 100644 --- a/homeassistant/components/zone/condition.py +++ b/homeassistant/components/zone/condition.py @@ -28,7 +28,7 @@ from homeassistant.exceptions import ConditionErrorContainer, ConditionErrorMess from homeassistant.helpers import config_validation as cv from homeassistant.helpers.automation import ( DomainSpec, - move_top_level_schema_fields_to_options, + validate_top_level_schema_fields_in_options, ) from homeassistant.helpers.condition import ( ATTR_BEHAVIOR, @@ -138,10 +138,10 @@ class ZoneCondition(Condition): cls, hass: HomeAssistant, complete_config: ConfigType ) -> ConfigType: """Validate complete config.""" - complete_config = move_top_level_schema_fields_to_options( + with validate_top_level_schema_fields_in_options( complete_config, _OPTIONS_SCHEMA_DICT - ) - return await super().async_validate_complete_config(hass, complete_config) + ) as config: + return await super().async_validate_complete_config(hass, config) @classmethod @override diff --git a/homeassistant/components/zone/trigger.py b/homeassistant/components/zone/trigger.py index 94584c5d614b..5c5a3902a8e7 100644 --- a/homeassistant/components/zone/trigger.py +++ b/homeassistant/components/zone/trigger.py @@ -29,7 +29,7 @@ from homeassistant.helpers import ( ) from homeassistant.helpers.automation import ( DomainSpec, - move_top_level_schema_fields_to_options, + validate_top_level_schema_fields_in_options, ) from homeassistant.helpers.event import async_track_state_change_event from homeassistant.helpers.trigger import ( @@ -107,10 +107,10 @@ class LegacyZoneTrigger(Trigger): cls, hass: HomeAssistant, complete_config: ConfigType ) -> ConfigType: """Validate complete config, migrating legacy format to options.""" - complete_config = move_top_level_schema_fields_to_options( + with validate_top_level_schema_fields_in_options( complete_config, _LEGACY_OPTIONS_SCHEMA - ) - return await super().async_validate_complete_config(hass, complete_config) + ) as config: + return await super().async_validate_complete_config(hass, config) @classmethod @override diff --git a/homeassistant/components/zwave_js/triggers/event.py b/homeassistant/components/zwave_js/triggers/event.py index 12a99d59f303..2ff668fb9d7d 100644 --- a/homeassistant/components/zwave_js/triggers/event.py +++ b/homeassistant/components/zwave_js/triggers/event.py @@ -18,7 +18,7 @@ from homeassistant.const import ( ) from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback from homeassistant.helpers import config_validation as cv, device_registry as dr -from homeassistant.helpers.automation import move_top_level_schema_fields_to_options +from homeassistant.helpers.automation import validate_top_level_schema_fields_in_options from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.trigger import ( Trigger, @@ -149,10 +149,10 @@ class EventTrigger(Trigger): cls, hass: HomeAssistant, complete_config: ConfigType ) -> ConfigType: """Validate complete config.""" - complete_config = move_top_level_schema_fields_to_options( + with validate_top_level_schema_fields_in_options( complete_config, _OPTIONS_SCHEMA_DICT - ) - return await super().async_validate_complete_config(hass, complete_config) + ) as config: + return await super().async_validate_complete_config(hass, config) @classmethod @override diff --git a/homeassistant/components/zwave_js/triggers/value_updated.py b/homeassistant/components/zwave_js/triggers/value_updated.py index 2802aad873df..578e45fbba52 100644 --- a/homeassistant/components/zwave_js/triggers/value_updated.py +++ b/homeassistant/components/zwave_js/triggers/value_updated.py @@ -12,7 +12,7 @@ from zwave_js_server.model.value import Value, get_value_id_str from homeassistant.const import ATTR_DEVICE_ID, ATTR_ENTITY_ID, CONF_OPTIONS, MATCH_ALL from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback from homeassistant.helpers import config_validation as cv, device_registry as dr -from homeassistant.helpers.automation import move_top_level_schema_fields_to_options +from homeassistant.helpers.automation import validate_top_level_schema_fields_in_options from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.trigger import ( Trigger, @@ -302,10 +302,10 @@ class ValueUpdatedTrigger(Trigger): cls, hass: HomeAssistant, complete_config: ConfigType ) -> ConfigType: """Validate complete config.""" - complete_config = move_top_level_schema_fields_to_options( + with validate_top_level_schema_fields_in_options( complete_config, _OPTIONS_SCHEMA_DICT - ) - return await super().async_validate_complete_config(hass, complete_config) + ) as config: + return await super().async_validate_complete_config(hass, config) @classmethod @override diff --git a/homeassistant/helpers/automation.py b/homeassistant/helpers/automation.py index 22e11944154b..f725151fb8fb 100644 --- a/homeassistant/helpers/automation.py +++ b/homeassistant/helpers/automation.py @@ -1,6 +1,7 @@ """Helpers for automation.""" -from collections.abc import Mapping +from collections.abc import Collection, Generator, Mapping +from contextlib import contextmanager from dataclasses import dataclass from enum import Enum from typing import Any, Final, Self @@ -136,6 +137,62 @@ def move_options_fields_to_top_level( return new_config +def _iter_errors(err: probatio.Invalid) -> Generator[probatio.Invalid]: + """Iterate over the errors of a validation error.""" + if not isinstance(err, probatio.MultipleInvalid): + yield err + return + for sub_err in err.errors: + yield from _iter_errors(sub_err) + + +@contextmanager +def validate_top_level_schema_fields_in_options( + config: ConfigType, options_schema_dict: dict[probatio.Marker, Any] +) -> Generator[ConfigType]: + """Move top-level fields to options for validation. + + Yields the config returned by move_top_level_schema_fields_to_options. Errors + raised in the context about a moved field are reported at the top-level, where + the field was before it was moved. + """ + moved_config = move_top_level_schema_fields_to_options(config, options_schema_dict) + moved_keys: Collection[str] = ( + () if CONF_OPTIONS in config else set(moved_config[CONF_OPTIONS]) + ) + try: + yield moved_config + except probatio.Invalid as err: + for sub_err in _iter_errors(err): + path = sub_err.path + if len(path) > 1 and path[0] == CONF_OPTIONS and path[1] in moved_keys: + del path[0] + raise + + +@contextmanager +def validate_options_fields_at_top_level( + config: ConfigType, base_schema: probatio.Schema +) -> Generator[ConfigType]: + """Move options fields to top-level for validation. + + Yields the config returned by move_options_fields_to_top_level. Errors raised + in the context about a field are reported in options, unless the field was + set at the top-level. + """ + moved_config = move_options_fields_to_top_level(config, base_schema) + try: + yield moved_config + except probatio.Invalid as err: + if moved_config is not config: + options = config[CONF_OPTIONS] + for sub_err in _iter_errors(err): + path = sub_err.path + if path and (path[0] in options or path[0] not in config): + sub_err.prepend([CONF_OPTIONS]) + raise + + @dataclass(frozen=True, kw_only=True) class ThresholdConfig: """Configuration for threshold conditions and triggers.""" diff --git a/homeassistant/helpers/trigger/__init__.py b/homeassistant/helpers/trigger/__init__.py index bae9341850f6..e10dd132a468 100644 --- a/homeassistant/helpers/trigger/__init__.py +++ b/homeassistant/helpers/trigger/__init__.py @@ -44,7 +44,7 @@ from homeassistant.helpers import config_validation as cv from homeassistant.helpers.automation import ( get_absolute_description_key, get_relative_description_key, - move_options_fields_to_top_level, + validate_options_fields_at_top_level, ) from homeassistant.helpers.frame import report_usage from homeassistant.helpers.integration_platform import ( @@ -528,12 +528,14 @@ async def _async_validate_trigger(hass: HomeAssistant, conf: ConfigType) -> Conf if not (trigger := trigger_descriptors.get(relative_trigger_key)): raise probatio.Invalid(f"Invalid trigger '{trigger_key}' specified") conf = await trigger.async_validate_complete_config(hass, conf) - elif hasattr(platform, "async_validate_trigger_config"): - conf = move_options_fields_to_top_level(conf, cv.TRIGGER_BASE_SCHEMA) - conf = await platform.async_validate_trigger_config(hass, conf) else: - conf = move_options_fields_to_top_level(conf, cv.TRIGGER_BASE_SCHEMA) - conf = platform.TRIGGER_SCHEMA(conf) + with validate_options_fields_at_top_level( + conf, cv.TRIGGER_BASE_SCHEMA + ) as legacy_conf: + if hasattr(platform, "async_validate_trigger_config"): + conf = await platform.async_validate_trigger_config(hass, legacy_conf) + else: + conf = platform.TRIGGER_SCHEMA(legacy_conf) return conf diff --git a/tests/components/calendar/test_trigger.py b/tests/components/calendar/test_trigger.py index f22f166afa21..3c5eca8a626d 100644 --- a/tests/components/calendar/test_trigger.py +++ b/tests/components/calendar/test_trigger.py @@ -17,6 +17,7 @@ from unittest.mock import patch import zoneinfo from freezegun.api import FrozenDateTimeFactory +import probatio import pytest from pytest_homeassistant.common import ( MockConfigEntry, @@ -49,6 +50,7 @@ from homeassistant.helpers import ( entity_registry as er, label_registry as lr, ) +from homeassistant.helpers.trigger import async_validate_trigger_config from homeassistant.setup import async_setup_component from homeassistant.util import dt as dt_util @@ -1544,3 +1546,54 @@ async def test_trigger_with_targets( {TargetKey.ENTITY_ID: "automation.end_trigger"}, blocking=True, ) + + +@pytest.mark.parametrize( + ("config", "expected_errors"), + [ + pytest.param( + {"platform": "calendar", "entity_id": "calendar.x", "event": "bad"}, + [([0, "event"], "value must be one of ['end', 'start'] at '[0].event'")], + id="top_level", + ), + pytest.param( + { + "platform": "calendar", + "entity_id": "calendar.x", + "event": "bad", + "offset": "bad", + }, + [ + ([0, "event"], "value must be one of ['end', 'start'] at '[0].event'"), + ( + [0, "offset"], + "offset bad should be format 'HH:MM', 'HH:MM:SS' or 'HH:MM:SS.F' at '[0].offset'", + ), + ], + id="top_level_multiple", + ), + pytest.param( + { + "platform": "calendar", + "options": {"entity_id": "calendar.x", "event": "bad"}, + }, + [ + ( + [0, "options", "event"], + "value must be one of ['end', 'start'] at '[0].options.event'", + ) + ], + id="options", + ), + ], +) +async def test_legacy_trigger_error_paths( + hass: HomeAssistant, + config: dict[str, Any], + expected_errors: list[tuple[list[Any], str]], +) -> None: + """Test errors are reported where the fields were set.""" + with pytest.raises(probatio.MultipleInvalid) as exc_info: + await async_validate_trigger_config(hass, [config]) + + assert [(err.path, str(err)) for err in exc_info.value.errors] == expected_errors diff --git a/tests/components/homeassistant/triggers/test_numeric_state.py b/tests/components/homeassistant/triggers/test_numeric_state.py index 67882d4d0a4f..e355acf3dea4 100644 --- a/tests/components/homeassistant/triggers/test_numeric_state.py +++ b/tests/components/homeassistant/triggers/test_numeric_state.py @@ -2,6 +2,7 @@ from datetime import timedelta import logging +from typing import Any from unittest.mock import patch from freezegun.api import FrozenDateTimeFactory @@ -25,6 +26,7 @@ from homeassistant.const import ( ) from homeassistant.core import Context, HomeAssistant, ServiceCall from homeassistant.helpers import entity_registry as er +from homeassistant.helpers.trigger import async_validate_trigger_config from homeassistant.setup import async_setup_component from homeassistant.util import dt as dt_util @@ -2009,3 +2011,35 @@ async def test_template_variable( assert len(service_calls) == 1 else: assert len(service_calls) == 0 + + +@pytest.mark.parametrize( + ("config", "expected_errors"), + [ + pytest.param( + {"platform": "numeric_state", "above": 5}, + [([0, "entity_id"], "required key not provided at '[0].entity_id'")], + id="top_level_missing_field", + ), + pytest.param( + {"platform": "numeric_state", "options": {"above": 5}}, + [ + ( + [0, "options", "entity_id"], + "required key not provided at '[0].options.entity_id'", + ) + ], + id="options_missing_field", + ), + ], +) +async def test_legacy_trigger_error_paths( + hass: HomeAssistant, + config: dict[str, Any], + expected_errors: list[tuple[list[Any], str]], +) -> None: + """Test errors are reported where the fields were set.""" + with pytest.raises(probatio.MultipleInvalid) as exc_info: + await async_validate_trigger_config(hass, [config]) + + assert [(err.path, str(err)) for err in exc_info.value.errors] == expected_errors diff --git a/tests/components/homeassistant/triggers/test_state.py b/tests/components/homeassistant/triggers/test_state.py index a816548ad0c1..e291e9d709e8 100644 --- a/tests/components/homeassistant/triggers/test_state.py +++ b/tests/components/homeassistant/triggers/test_state.py @@ -1,9 +1,11 @@ """The test for state automation.""" from datetime import timedelta +from typing import Any from unittest.mock import patch from freezegun.api import FrozenDateTimeFactory +import probatio import pytest from pytest_homeassistant.common import ( assert_setup_component, @@ -21,6 +23,7 @@ from homeassistant.const import ( ) from homeassistant.core import Context, HomeAssistant, ServiceCall from homeassistant.helpers import entity_registry as er +from homeassistant.helpers.trigger import async_validate_trigger_config from homeassistant.setup import async_setup_component from homeassistant.util import dt as dt_util @@ -1826,3 +1829,49 @@ async def test_variables_priority( await hass.async_block_till_done() assert len(service_calls) == 2 assert service_calls[1].data["some"] == "test.entity_2 - 0:00:10" + + +@pytest.mark.parametrize( + ("config", "expected_errors"), + [ + pytest.param( + {"platform": "state", "to": "on"}, + [([0, "entity_id"], "required key not provided at '[0].entity_id'")], + id="top_level_missing_field", + ), + pytest.param( + {"platform": "state", "options": {"to": "on"}}, + [ + ( + [0, "options", "entity_id"], + "required key not provided at '[0].options.entity_id'", + ) + ], + id="options_missing_field", + ), + pytest.param( + { + "platform": "state", + "options": {"entity_id": "test.entity", "to": "on", "not_to": "off"}, + }, + [ + ( + [0, "options", "to"], + "two or more values in the same group of exclusion " + " at '[0].options.'", + ) + ], + id="options_exclusive", + ), + ], +) +async def test_legacy_trigger_error_paths( + hass: HomeAssistant, + config: dict[str, Any], + expected_errors: list[tuple[list[Any], str]], +) -> None: + """Test errors are reported where the fields were set.""" + with pytest.raises(probatio.MultipleInvalid) as exc_info: + await async_validate_trigger_config(hass, [config]) + + assert [(err.path, str(err)) for err in exc_info.value.errors] == expected_errors diff --git a/tests/components/knx/test_trigger.py b/tests/components/knx/test_trigger.py index b660da542032..fef121011de1 100644 --- a/tests/components/knx/test_trigger.py +++ b/tests/components/knx/test_trigger.py @@ -4,13 +4,17 @@ from collections.abc import Callable import logging from typing import Any +import probatio import pytest from homeassistant.components import automation from homeassistant.components.knx import DOMAIN from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TURN_OFF from homeassistant.core import HomeAssistant, ServiceCall -from homeassistant.helpers.trigger import async_get_all_descriptions +from homeassistant.helpers.trigger import ( + async_get_all_descriptions, + async_validate_trigger_config, +) from homeassistant.setup import async_setup_component from .conftest import KNXTestKit @@ -393,3 +397,43 @@ async def test_invalid_trigger( "not a valid option at 'trigger.invalid'. Got True" in caplog.records[0].message ) + + +@pytest.mark.parametrize( + ("config", "expected_errors"), + [ + pytest.param( + {"platform": "knx.telegram", "incoming": "bad"}, + [([0, "incoming"], "invalid boolean value bad at '[0].incoming'")], + id="top_level", + ), + pytest.param( + {"platform": "knx.telegram", "incoming": "bad", "outgoing": "bad"}, + [ + ([0, "incoming"], "invalid boolean value bad at '[0].incoming'"), + ([0, "outgoing"], "invalid boolean value bad at '[0].outgoing'"), + ], + id="top_level_multiple", + ), + pytest.param( + {"platform": "knx.telegram", "options": {"incoming": "bad"}}, + [ + ( + [0, "options", "incoming"], + "invalid boolean value bad at '[0].options.incoming'", + ) + ], + id="options", + ), + ], +) +async def test_telegram_trigger_error_paths( + hass: HomeAssistant, + config: dict[str, Any], + expected_errors: list[tuple[list[Any], str]], +) -> None: + """Test errors are reported where the fields were set.""" + with pytest.raises(probatio.MultipleInvalid) as exc_info: + await async_validate_trigger_config(hass, [config]) + + assert [(err.path, str(err)) for err in exc_info.value.errors] == expected_errors diff --git a/tests/components/sun/test_condition.py b/tests/components/sun/test_condition.py index ac1c462a61e2..5c8b436fcc2e 100644 --- a/tests/components/sun/test_condition.py +++ b/tests/components/sun/test_condition.py @@ -2,6 +2,7 @@ from contextlib import AbstractContextManager, nullcontext from datetime import datetime, timedelta +from typing import Any from freezegun import freeze_time import probatio @@ -1936,3 +1937,46 @@ async def test_golden_blue_hour_condition_period_validation( config = {"condition": condition_key, "options": {"period": period}} with expectation: await async_validate_condition_config(hass, config) + + +@pytest.mark.parametrize( + ("config", "expected_errors"), + [ + pytest.param( + {"condition": "sun", "after": "bad"}, + [(["after"], "expected 'sunset' or 'sunrise' at 'after'")], + id="top_level", + ), + pytest.param( + {"condition": "sun", "after": "bad", "before_offset": "bad"}, + [ + ( + ["before_offset"], + "offset bad should be format 'HH:MM', 'HH:MM:SS' or 'HH:MM:SS.F' at 'before_offset'", + ), + (["after"], "expected 'sunset' or 'sunrise' at 'after'"), + ], + id="top_level_multiple", + ), + pytest.param( + {"condition": "sun", "options": {"after": "bad"}}, + [ + ( + ["options", "after"], + "expected 'sunset' or 'sunrise' at 'options.after'", + ) + ], + id="options", + ), + ], +) +async def test_legacy_condition_error_paths( + hass: HomeAssistant, + config: dict[str, Any], + expected_errors: list[tuple[list[Any], str]], +) -> None: + """Test errors are reported where the fields were set.""" + with pytest.raises(probatio.MultipleInvalid) as exc_info: + await async_validate_condition_config(hass, config) + + assert [(err.path, str(err)) for err in exc_info.value.errors] == expected_errors diff --git a/tests/components/sun/test_trigger.py b/tests/components/sun/test_trigger.py index 3cc3b4e65ec6..f040ffac3920 100644 --- a/tests/components/sun/test_trigger.py +++ b/tests/components/sun/test_trigger.py @@ -1085,3 +1085,46 @@ async def test_golden_blue_hour_period_validation( config = {"platform": trigger_key, "options": {"period": period}} with expectation: await async_validate_trigger_config(hass, [config]) + + +@pytest.mark.parametrize( + ("config", "expected_errors"), + [ + pytest.param( + {"platform": "sun", "event": "bad"}, + [([0, "event"], "expected 'sunset' or 'sunrise' at '[0].event'")], + id="top_level", + ), + pytest.param( + {"platform": "sun", "event": "bad", "offset": "bad"}, + [ + ([0, "event"], "expected 'sunset' or 'sunrise' at '[0].event'"), + ( + [0, "offset"], + "offset bad should be format 'HH:MM', 'HH:MM:SS' or 'HH:MM:SS.F' at '[0].offset'", + ), + ], + id="top_level_multiple", + ), + pytest.param( + {"platform": "sun", "options": {"event": "bad"}}, + [ + ( + [0, "options", "event"], + "expected 'sunset' or 'sunrise' at '[0].options.event'", + ) + ], + id="options", + ), + ], +) +async def test_legacy_trigger_error_paths( + hass: HomeAssistant, + config: dict[str, Any], + expected_errors: list[tuple[list[Any], str]], +) -> None: + """Test errors are reported where the fields were set.""" + with pytest.raises(probatio.MultipleInvalid) as exc_info: + await async_validate_trigger_config(hass, [config]) + + assert [(err.path, str(err)) for err in exc_info.value.errors] == expected_errors diff --git a/tests/components/webostv/test_trigger.py b/tests/components/webostv/test_trigger.py index e2e38d4d5d27..a89b897b7eac 100644 --- a/tests/components/webostv/test_trigger.py +++ b/tests/components/webostv/test_trigger.py @@ -1,7 +1,9 @@ """The tests for LG webOS TV automation triggers.""" +from typing import Any from unittest.mock import MagicMock, patch +import probatio import pytest from pytest_homeassistant.common import MockEntity, MockEntityPlatform @@ -11,6 +13,7 @@ from homeassistant.const import ATTR_DEVICE_ID, ATTR_ENTITY_ID, SERVICE_RELOAD from homeassistant.core import HomeAssistant, ServiceCall from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import device_registry as dr +from homeassistant.helpers.trigger import async_validate_trigger_config from homeassistant.setup import async_setup_component from . import setup_webostv @@ -231,3 +234,40 @@ async def test_trigger_invalid_entity_id( ) assert f"Entity {invalid_entity} is not a valid webOS TV entity" in caplog.text + + +@pytest.mark.parametrize( + ("config", "expected_errors"), + [ + pytest.param( + {"platform": "webostv.turn_on", "entity_id": "bad id"}, + [ + ( + [0, "entity_id"], + "Entity ID bad id is an invalid entity ID at '[0].entity_id'", + ) + ], + id="top_level", + ), + pytest.param( + {"platform": "webostv.turn_on", "options": {"entity_id": "bad id"}}, + [ + ( + [0, "options", "entity_id"], + "Entity ID bad id is an invalid entity ID at '[0].options.entity_id'", + ) + ], + id="options", + ), + ], +) +async def test_turn_on_trigger_error_paths( + hass: HomeAssistant, + config: dict[str, Any], + expected_errors: list[tuple[list[Any], str]], +) -> None: + """Test errors are reported where the fields were set.""" + with pytest.raises(probatio.MultipleInvalid) as exc_info: + await async_validate_trigger_config(hass, [config]) + + assert [(err.path, str(err)) for err in exc_info.value.errors] == expected_errors diff --git a/tests/components/zone/test_condition.py b/tests/components/zone/test_condition.py index 5ec1ca12b5f4..3e4688b98dea 100644 --- a/tests/components/zone/test_condition.py +++ b/tests/components/zone/test_condition.py @@ -792,3 +792,46 @@ async def test_zone_occupancy_condition_evaluates( ) test = await condition.async_from_config(hass, config) assert test.async_check() is expected + + +@pytest.mark.parametrize( + ("config", "expected_errors"), + [ + pytest.param( + {"condition": "zone", "entity_id": "person.a", "zone": 5}, + [(["zone"], "Entity IDs must be a string or a list at 'zone'")], + id="top_level", + ), + pytest.param( + {"condition": "zone", "entity_id": "bad id", "zone": 5}, + [ + ( + ["entity_id"], + "Entity ID bad id is an invalid entity ID at 'entity_id'", + ), + (["zone"], "Entity IDs must be a string or a list at 'zone'"), + ], + id="top_level_multiple", + ), + pytest.param( + {"condition": "zone", "options": {"entity_id": "person.a", "zone": 5}}, + [ + ( + ["options", "zone"], + "Entity IDs must be a string or a list at 'options.zone'", + ) + ], + id="options", + ), + ], +) +async def test_legacy_condition_error_paths( + hass: HomeAssistant, + config: dict[str, Any], + expected_errors: list[tuple[list[Any], str]], +) -> None: + """Test errors are reported where the fields were set.""" + with pytest.raises(probatio.MultipleInvalid) as exc_info: + await condition.async_validate_condition_config(hass, config) + + assert [(err.path, str(err)) for err in exc_info.value.errors] == expected_errors diff --git a/tests/components/zone/test_trigger.py b/tests/components/zone/test_trigger.py index 433a0098a6ee..ee18401e659f 100644 --- a/tests/components/zone/test_trigger.py +++ b/tests/components/zone/test_trigger.py @@ -991,3 +991,43 @@ async def test_zone_occupancy_trigger_for_duration( async_fire_time_changed(hass) await hass.async_block_till_done() assert len(service_calls) == 1 + + +@pytest.mark.parametrize( + ("config", "expected_errors"), + [ + pytest.param( + {"platform": "zone", "entity_id": "person.a", "zone": 5}, + [([0, "zone"], "Entity ID 5 is an invalid entity ID at '[0].zone'")], + id="top_level", + ), + pytest.param( + {"platform": "zone", "entity_id": "person.a", "zone": 5, "event": "bad"}, + [ + ([0, "zone"], "Entity ID 5 is an invalid entity ID at '[0].zone'"), + ([0, "event"], "expected 'enter' or 'leave' at '[0].event'"), + ], + id="top_level_multiple", + ), + pytest.param( + {"platform": "zone", "options": {"entity_id": "person.a", "zone": 5}}, + [ + ( + [0, "options", "zone"], + "Entity ID 5 is an invalid entity ID at '[0].options.zone'", + ) + ], + id="options", + ), + ], +) +async def test_legacy_trigger_error_paths( + hass: HomeAssistant, + config: dict[str, Any], + expected_errors: list[tuple[list[Any], str]], +) -> None: + """Test errors are reported where the fields were set.""" + with pytest.raises(probatio.MultipleInvalid) as exc_info: + await async_validate_trigger_config(hass, [config]) + + assert [(err.path, str(err)) for err in exc_info.value.errors] == expected_errors diff --git a/tests/components/zwave_js/test_trigger.py b/tests/components/zwave_js/test_trigger.py index 0424be20c3e5..0f0206b8cbfb 100644 --- a/tests/components/zwave_js/test_trigger.py +++ b/tests/components/zwave_js/test_trigger.py @@ -2250,3 +2250,110 @@ async def test_trigger_description_fields_match_schema( assert {name for name, field in fields.items() if field["required"]} == { str(key) for key in options_schema if isinstance(key, probatio.Required) } + + +@pytest.mark.parametrize( + ("config", "expected_errors"), + [ + pytest.param( + {"platform": "zwave_js.event", "event_source": "bad", "event": "x"}, + [ + ( + [0, "event_source"], + "value must be one of ['controller', 'driver', 'node'] at '[0].event_source'", + ) + ], + id="event_top_level", + ), + pytest.param( + { + "platform": "zwave_js.event", + "entity_id": "bad id", + "event_source": "bad", + "event": "x", + }, + [ + ( + [0, "entity_id"], + "Entity ID bad id is an invalid entity ID at '[0].entity_id'", + ), + ( + [0, "event_source"], + "value must be one of ['controller', 'driver', 'node'] at '[0].event_source'", + ), + ], + id="event_top_level_multiple", + ), + pytest.param( + { + "platform": "zwave_js.event", + "options": {"event_source": "bad", "event": "x"}, + }, + [ + ( + [0, "options", "event_source"], + "value must be one of ['controller', 'driver', 'node'] at '[0].options.event_source'", + ) + ], + id="event_options", + ), + pytest.param( + { + "platform": "zwave_js.value_updated", + "entity_id": "bad id", + "command_class": 98, + "property": "x", + }, + [ + ( + [0, "entity_id"], + "Entity ID bad id is an invalid entity ID at '[0].entity_id'", + ) + ], + id="value_updated_top_level", + ), + pytest.param( + { + "platform": "zwave_js.value_updated", + "entity_id": "bad id", + "command_class": "bad", + "property": "x", + }, + [ + ( + [0, "entity_id"], + "Entity ID bad id is an invalid entity ID at '[0].entity_id'", + ), + ([0, "command_class"], "expected int at '[0].command_class'"), + ], + id="value_updated_top_level_multiple", + ), + pytest.param( + { + "platform": "zwave_js.value_updated", + "options": { + "entity_id": "bad id", + "command_class": 98, + "property": "x", + }, + }, + [ + ( + [0, "options", "entity_id"], + "Entity ID bad id is an invalid entity ID at '[0].options.entity_id'", + ) + ], + id="value_updated_options", + ), + ], +) +async def test_trigger_error_paths( + hass: HomeAssistant, + config: dict[str, Any], + expected_errors: list[tuple[list[Any], str]], +) -> None: + """Test errors are reported where the fields were set.""" + with pytest.raises(probatio.MultipleInvalid) as exc_info: + await trigger.async_validate_trigger_config(hass, [config]) + + assert [(err.path, str(err)) for err in exc_info.value.errors] == expected_errors diff --git a/tests/helpers/test_automation.py b/tests/helpers/test_automation.py index 00a1e82f0032..6d72598768f9 100644 --- a/tests/helpers/test_automation.py +++ b/tests/helpers/test_automation.py @@ -1,5 +1,7 @@ """Test automation helpers.""" +from typing import Any + import probatio import pytest @@ -8,8 +10,21 @@ from homeassistant.helpers.automation import ( get_relative_description_key, move_options_fields_to_top_level, move_top_level_schema_fields_to_options, + validate_options_fields_at_top_level, + validate_top_level_schema_fields_in_options, ) +_OPTIONS_SCHEMA_DICT: dict[probatio.Marker, Any] = { + probatio.Required("number"): int, + probatio.Optional("nested"): {"value": int}, + probatio.Optional("numbers"): [int], +} +_BASE_SCHEMA = probatio.Schema({probatio.Required("platform"): str}) +_NEW_STYLE_SCHEMA = _BASE_SCHEMA.extend( + {probatio.Required("options"): _OPTIONS_SCHEMA_DICT} +) +_LEGACY_SCHEMA = _BASE_SCHEMA.extend(_OPTIONS_SCHEMA_DICT) + @pytest.mark.parametrize( ("relative_key", "absolute_key"), @@ -180,3 +195,285 @@ async def test_move_options_fields_to_top_level(config, expected_config) -> None original_config = config.copy() assert move_options_fields_to_top_level(config, base_schema) == expected_config assert config == original_config # Ensure original config is not modified + + +@pytest.mark.parametrize( + ("config", "expected_errors"), + [ + pytest.param( + {"platform": "test", "number": "bad"}, + [(["number"], "expected int at 'number'")], + id="moved_field", + ), + pytest.param( + {"platform": "test", "number": 1, "nested": {"value": "bad"}}, + [(["nested", "value"], "expected int at 'nested.value'")], + id="moved_field_nested", + ), + pytest.param( + {"platform": "test", "number": 1, "numbers": [1, "bad"]}, + [(["numbers", 1], "expected int at 'numbers[1]'")], + id="moved_field_list_item", + ), + pytest.param( + {"platform": "test", "number": "bad", "nested": {"value": "bad"}}, + [ + (["number"], "expected int at 'number'"), + (["nested", "value"], "expected int at 'nested.value'"), + ], + id="multiple_moved_fields", + ), + pytest.param( + {"platform": "test", "number": "bad", "unknown": 1}, + [ + (["unknown"], "not a valid option at 'unknown'"), + (["number"], "expected int at 'number'"), + ], + id="moved_field_and_unknown_field", + ), + pytest.param( + {"platform": "test", "nested": {"value": 1}}, + [ + ( + ["options", "number"], + "required key not provided at 'options.number'", + ) + ], + id="missing_field", + ), + pytest.param( + {"platform": "test", "options": {"number": "bad"}}, + [(["options", "number"], "expected int at 'options.number'")], + id="field_in_options", + ), + pytest.param( + {"platform": "test", "options": {"number": 1}, "nested": {"value": 1}}, + [(["nested"], "not a valid option at 'nested'")], + id="options_and_top_level_field", + ), + ], +) +def test_validate_top_level_schema_fields_in_options_error_paths( + config: dict[str, Any], expected_errors: list[tuple[list[Any], str]] +) -> None: + """Test errors about fields moved to options are reported at the top-level.""" + original_config = config.copy() + with ( + pytest.raises(probatio.MultipleInvalid) as exc_info, + validate_top_level_schema_fields_in_options( + config, _OPTIONS_SCHEMA_DICT + ) as moved_config, + ): + _NEW_STYLE_SCHEMA(moved_config) + + assert [(err.path, str(err)) for err in exc_info.value.errors] == expected_errors + assert config == original_config + + +@pytest.mark.parametrize( + ("path", "expected_path", "expected_message"), + [ + pytest.param(["options", "number"], ["number"], "bad at 'number'", id="moved"), + pytest.param( + ["options", "nested"], + ["options", "nested"], + "bad at 'options.nested'", + id="not_moved", + ), + pytest.param(["options"], ["options"], "bad at 'options'", id="options"), + pytest.param(["number"], ["number"], "bad at 'number'", id="top_level"), + pytest.param([], [], "bad", id="no_path"), + ], +) +def test_validate_top_level_schema_fields_in_options_single_error( + path: list[Any], expected_path: list[Any], expected_message: str +) -> None: + """Test the path of a single error raised with fields moved to options.""" + with ( + pytest.raises(probatio.Invalid) as exc_info, + validate_top_level_schema_fields_in_options( + {"platform": "test", "number": 1}, _OPTIONS_SCHEMA_DICT + ), + ): + raise probatio.Invalid("bad", path=path) + + assert exc_info.value.path == expected_path + assert str(exc_info.value) == expected_message + + +def test_validate_top_level_schema_fields_in_options_nested_errors() -> None: + """Test the paths of nested errors raised with fields moved to options.""" + errors = [ + probatio.Invalid("bad", path=path) + for path in (["options", "number"], ["options", "nested", "value"], ["id"]) + ] + with ( + pytest.raises(probatio.MultipleInvalid), + validate_top_level_schema_fields_in_options( + {"platform": "test", "number": 1, "nested": {}}, _OPTIONS_SCHEMA_DICT + ), + ): + raise probatio.MultipleInvalid( + [errors[0], probatio.MultipleInvalid(errors[1:])] + ) + + assert [err.path for err in errors] == [["number"], ["nested", "value"], ["id"]] + + +def test_validate_top_level_schema_fields_in_options_valid() -> None: + """Test a valid config with fields moved to options.""" + config = {"platform": "test", "number": 1} + with validate_top_level_schema_fields_in_options( + config, _OPTIONS_SCHEMA_DICT + ) as moved_config: + validated_config = _NEW_STYLE_SCHEMA(moved_config) + + assert validated_config == {"platform": "test", "options": {"number": 1}} + assert config == {"platform": "test", "number": 1} + + +@pytest.mark.parametrize( + ("config", "expected_errors"), + [ + pytest.param( + {"platform": "test", "options": {"number": "bad"}}, + [(["options", "number"], "expected int at 'options.number'")], + id="moved_field", + ), + pytest.param( + {"platform": "test", "options": {"number": 1, "nested": {"value": "bad"}}}, + [ + ( + ["options", "nested", "value"], + "expected int at 'options.nested.value'", + ) + ], + id="moved_field_nested", + ), + pytest.param( + {"platform": "test", "options": {"number": 1, "numbers": [1, "bad"]}}, + [(["options", "numbers", 1], "expected int at 'options.numbers[1]'")], + id="moved_field_list_item", + ), + pytest.param( + { + "platform": "test", + "options": {"number": "bad", "nested": {"value": "bad"}}, + }, + [ + (["options", "number"], "expected int at 'options.number'"), + ( + ["options", "nested", "value"], + "expected int at 'options.nested.value'", + ), + ], + id="multiple_moved_fields", + ), + pytest.param( + {"platform": "test", "options": {"number": 1, "unknown": 1}}, + [(["options", "unknown"], "not a valid option at 'options.unknown'")], + id="moved_unknown_field", + ), + pytest.param( + {"platform": "test", "options": {"nested": {"value": 1}}}, + [ + ( + ["options", "number"], + "required key not provided at 'options.number'", + ) + ], + id="missing_field", + ), + pytest.param( + {"platform": "test", "number": "bad"}, + [(["number"], "expected int at 'number'")], + id="field_at_top_level", + ), + pytest.param( + {"platform": "test", "options": {"nested": {}}, "number": "bad"}, + [ + (["options"], "not a valid option at 'options'"), + (["number"], "expected int at 'number'"), + ], + id="options_and_top_level_field", + ), + ], +) +def test_validate_options_fields_at_top_level_error_paths( + config: dict[str, Any], expected_errors: list[tuple[list[Any], str]] +) -> None: + """Test errors are reported in options unless the field was set at the top-level.""" + original_config = config.copy() + with ( + pytest.raises(probatio.MultipleInvalid) as exc_info, + validate_options_fields_at_top_level(config, _BASE_SCHEMA) as moved_config, + ): + _LEGACY_SCHEMA(moved_config) + + assert [(err.path, str(err)) for err in exc_info.value.errors] == expected_errors + assert config == original_config + + +@pytest.mark.parametrize( + ("path", "expected_path", "expected_message"), + [ + pytest.param( + ["number"], ["options", "number"], "bad at 'options.number'", id="moved" + ), + pytest.param( + ["nested"], + ["options", "nested"], + "bad at 'options.nested'", + id="not_written", + ), + pytest.param(["platform"], ["platform"], "bad at 'platform'", id="top_level"), + pytest.param([], [], "bad", id="no_path"), + ], +) +def test_validate_options_fields_at_top_level_single_error( + path: list[Any], expected_path: list[Any], expected_message: str +) -> None: + """Test the path of a single error raised with options moved to the top-level.""" + with ( + pytest.raises(probatio.Invalid) as exc_info, + validate_options_fields_at_top_level( + {"platform": "test", "options": {"number": 1}}, _BASE_SCHEMA + ), + ): + raise probatio.Invalid("bad", path=path) + + assert exc_info.value.path == expected_path + assert str(exc_info.value) == expected_message + + +def test_validate_options_fields_at_top_level_nested_errors() -> None: + """Test the paths of nested errors raised with options moved to the top-level.""" + errors = [ + probatio.Invalid("bad", path=path) + for path in (["number"], ["nested", "value"], ["platform"]) + ] + with ( + pytest.raises(probatio.MultipleInvalid), + validate_options_fields_at_top_level( + {"platform": "test", "options": {"number": 1, "nested": {}}}, _BASE_SCHEMA + ), + ): + raise probatio.MultipleInvalid( + [errors[0], probatio.MultipleInvalid(errors[1:])] + ) + + assert [err.path for err in errors] == [ + ["options", "number"], + ["options", "nested", "value"], + ["platform"], + ] + + +def test_validate_options_fields_at_top_level_valid() -> None: + """Test a valid config with options moved to the top-level.""" + config = {"platform": "test", "options": {"number": 1}} + with validate_options_fields_at_top_level(config, _BASE_SCHEMA) as moved_config: + validated_config = _LEGACY_SCHEMA(moved_config) + + assert validated_config == {"platform": "test", "number": 1} + assert config == {"platform": "test", "options": {"number": 1}} diff --git a/tests/helpers/test_condition.py b/tests/helpers/test_condition.py index 3bf16ba76bdd..44423c12910d 100644 --- a/tests/helpers/test_condition.py +++ b/tests/helpers/test_condition.py @@ -73,6 +73,7 @@ from homeassistant.helpers import ( from homeassistant.helpers.automation import ( DomainSpec, move_top_level_schema_fields_to_options, + validate_top_level_schema_fields_in_options, ) from homeassistant.helpers.condition import ( ATTR_BEHAVIOR, @@ -2881,6 +2882,87 @@ async def test_platform_migrate_condition(hass: HomeAssistant) -> None: ) +@pytest.mark.parametrize( + ("config", "expected_errors"), + [ + pytest.param( + {"condition": "test", "option_1": "value_1", "option_2": "x"}, + [(["option_2"], "expected int at 'option_2'")], + id="field_at_top_level", + ), + pytest.param( + {"condition": "test", "option_1": 1, "option_2": "x"}, + [ + (["option_1"], "expected str at 'option_1'"), + (["option_2"], "expected int at 'option_2'"), + ], + id="multiple_fields_at_top_level", + ), + pytest.param( + {"condition": "test", "option_2": 2}, + [ + ( + ["options", "option_1"], + "required key not provided at 'options.option_1'", + ) + ], + id="missing_field", + ), + pytest.param( + {"condition": "test", "options": {"option_1": "value_1", "option_2": "x"}}, + [(["options", "option_2"], "expected int at 'options.option_2'")], + id="field_in_options", + ), + ], +) +async def test_platform_migrate_condition_error_paths( + hass: HomeAssistant, + config: ConfigType, + expected_errors: list[tuple[list[Any], str]], +) -> None: + """Test errors of migrated conditions are reported where the fields were set.""" + + OPTIONS_SCHEMA_DICT = { + probatio.Required("option_1"): str, + probatio.Optional("option_2"): int, + } + + class MockCondition(Condition): + """Mock condition.""" + + @classmethod + async def async_validate_complete_config( + cls, hass: HomeAssistant, complete_config: ConfigType + ) -> ConfigType: + """Validate complete config.""" + with validate_top_level_schema_fields_in_options( + complete_config, OPTIONS_SCHEMA_DICT + ) as moved_config: + return await super().async_validate_complete_config(hass, moved_config) + + @classmethod + async def async_validate_config( + cls, hass: HomeAssistant, config: ConfigType + ) -> ConfigType: + """Validate config.""" + return probatio.Schema({"options": OPTIONS_SCHEMA_DICT})(config) + + async def async_get_conditions(hass: HomeAssistant) -> dict[str, type[Condition]]: + return { + "_": MockCondition, + } + + mock_integration(hass, MockModule("test")) + mock_platform( + hass, "test.condition", Mock(async_get_conditions=async_get_conditions) + ) + + with pytest.raises(probatio.MultipleInvalid) as exc_info: + await async_validate_condition_config(hass, config) + + assert [(err.path, str(err)) for err in exc_info.value.errors] == expected_errors + + async def test_platform_backwards_compatibility_for_new_style_configs( hass: HomeAssistant, ) -> None: diff --git a/tests/helpers/test_trigger.py b/tests/helpers/test_trigger.py index 9cf16bf95b99..eb00927768ed 100644 --- a/tests/helpers/test_trigger.py +++ b/tests/helpers/test_trigger.py @@ -70,6 +70,7 @@ from homeassistant.helpers import ( from homeassistant.helpers.automation import ( DomainSpec, move_top_level_schema_fields_to_options, + validate_top_level_schema_fields_in_options, ) from homeassistant.helpers.event import async_track_state_change_event from homeassistant.helpers.template import Template @@ -1187,6 +1188,173 @@ async def test_platform_backwards_compatibility_for_new_style_configs( assert result == config_old_style +class _MockLegacySchemaTriggerPlatform: + """Mock legacy trigger platform with a schema.""" + + TRIGGER_SCHEMA = cv.TRIGGER_BASE_SCHEMA.extend( + { + probatio.Required("option_1"): str, + probatio.Optional("option_2"): int, + } + ) + + +class _MockLegacyValidatorTriggerPlatform: + """Mock legacy trigger platform with a validator.""" + + @staticmethod + async def async_validate_trigger_config( + hass: HomeAssistant, config: ConfigType + ) -> ConfigType: + """Validate config.""" + return _MockLegacySchemaTriggerPlatform.TRIGGER_SCHEMA(config) + + +@pytest.mark.parametrize( + "platform", + [ + pytest.param(_MockLegacySchemaTriggerPlatform, id="schema"), + pytest.param(_MockLegacyValidatorTriggerPlatform, id="validator"), + ], +) +@pytest.mark.parametrize( + ("config", "expected_errors"), + [ + pytest.param( + {"platform": "test", "options": {"option_1": "value_1", "option_2": "x"}}, + [([0, "options", "option_2"], "expected int at '[0].options.option_2'")], + id="field_in_options", + ), + pytest.param( + {"platform": "test", "options": {"option_1": 1, "option_2": "x"}}, + [ + ([0, "options", "option_1"], "expected str at '[0].options.option_1'"), + ([0, "options", "option_2"], "expected int at '[0].options.option_2'"), + ], + id="multiple_fields_in_options", + ), + pytest.param( + {"platform": "test", "options": {"option_1": "value_1", "unknown": 1}}, + [ + ( + [0, "options", "unknown"], + "not a valid option at '[0].options.unknown'", + ) + ], + id="unknown_field_in_options", + ), + pytest.param( + {"platform": "test", "options": {"option_2": 2}}, + [ + ( + [0, "options", "option_1"], + "required key not provided at '[0].options.option_1'", + ) + ], + id="missing_field", + ), + pytest.param( + {"platform": "test", "option_1": "value_1", "option_2": "x"}, + [([0, "option_2"], "expected int at '[0].option_2'")], + id="field_at_top_level", + ), + ], +) +async def test_legacy_platform_new_style_config_error_paths( + hass: HomeAssistant, + platform: type, + config: ConfigType, + expected_errors: list[tuple[list[Any], str]], +) -> None: + """Test errors of old-style triggers are reported where the fields were set.""" + mock_integration(hass, MockModule("test")) + mock_platform(hass, "test.trigger", platform()) + + with pytest.raises(probatio.MultipleInvalid) as exc_info: + await async_validate_trigger_config(hass, [config]) + + assert [(err.path, str(err)) for err in exc_info.value.errors] == expected_errors + + +@pytest.mark.parametrize( + ("config", "expected_errors"), + [ + pytest.param( + {"platform": "test", "option_1": "value_1", "option_2": "x"}, + [([0, "option_2"], "expected int at '[0].option_2'")], + id="field_at_top_level", + ), + pytest.param( + {"platform": "test", "option_1": 1, "option_2": "x"}, + [ + ([0, "option_1"], "expected str at '[0].option_1'"), + ([0, "option_2"], "expected int at '[0].option_2'"), + ], + id="multiple_fields_at_top_level", + ), + pytest.param( + {"platform": "test", "option_2": 2}, + [ + ( + [0, "options", "option_1"], + "required key not provided at '[0].options.option_1'", + ) + ], + id="missing_field", + ), + pytest.param( + {"platform": "test", "options": {"option_1": "value_1", "option_2": "x"}}, + [([0, "options", "option_2"], "expected int at '[0].options.option_2'")], + id="field_in_options", + ), + ], +) +async def test_platform_migrate_trigger_error_paths( + hass: HomeAssistant, + config: ConfigType, + expected_errors: list[tuple[list[Any], str]], +) -> None: + """Test errors of migrated triggers are reported where the fields were set.""" + + OPTIONS_SCHEMA_DICT = { + probatio.Required("option_1"): str, + probatio.Optional("option_2"): int, + } + + class MockTrigger(Trigger): + """Mock trigger.""" + + @classmethod + async def async_validate_complete_config( + cls, hass: HomeAssistant, complete_config: ConfigType + ) -> ConfigType: + """Validate complete config.""" + with validate_top_level_schema_fields_in_options( + complete_config, OPTIONS_SCHEMA_DICT + ) as moved_config: + return await super().async_validate_complete_config(hass, moved_config) + + @classmethod + async def async_validate_config( + cls, hass: HomeAssistant, config: ConfigType + ) -> ConfigType: + """Validate config.""" + return probatio.Schema({"options": OPTIONS_SCHEMA_DICT})(config) + + async def async_get_triggers(hass: HomeAssistant) -> dict[str, type[Trigger]]: + return { + "_": MockTrigger, + } + + mock_integration(hass, MockModule("test")) + mock_platform(hass, "test.trigger", Mock(async_get_triggers=async_get_triggers)) + + with pytest.raises(probatio.MultipleInvalid) as exc_info: + await async_validate_trigger_config(hass, [config]) + + assert [(err.path, str(err)) for err in exc_info.value.errors] == expected_errors + + async def test_get_trigger_platform_registers_triggers( hass: HomeAssistant, ) -> None: