diff --git a/homeassistant/helpers/condition/models.py b/homeassistant/helpers/condition/models.py index 56031e61ebff..fa4818986b38 100644 --- a/homeassistant/helpers/condition/models.py +++ b/homeassistant/helpers/condition/models.py @@ -38,7 +38,9 @@ CONDITION_BASE_SCHEMA = probatio.Schema( _CONDITION_SCHEMA = CONDITION_BASE_SCHEMA.extend( { probatio.Optional(CONF_OPTIONS): object, - probatio.Optional(CONF_TARGET): cv.TARGET_FIELDS, + probatio.Optional(CONF_TARGET): probatio.All( + cv.TARGET_FIELDS, cv.exclude_requires_target + ), } ) diff --git a/homeassistant/helpers/config_validation.py b/homeassistant/helpers/config_validation.py index ec6fd874c5ce..8d5cc48992de 100644 --- a/homeassistant/helpers/config_validation.py +++ b/homeassistant/helpers/config_validation.py @@ -1308,6 +1308,17 @@ TARGET_FIELDS: VolDictType = { probatio.Optional(CONF_EXCLUDE): probatio.Schema(TARGET_ID_FIELDS), } + +def exclude_requires_target(value: dict[str, Any]) -> dict[str, Any]: + """Reject a target which only has an exclude block. + + Not part of TARGET_FIELDS, which also validates partial targets while editing. + """ + if CONF_EXCLUDE in value and not any(value.get(key) for key in TARGET_ID_KEYS): + raise probatio.Invalid("an exclude block requires a target to exclude from") + return value + + ENTITY_SERVICE_EXCLUDE_SCHEMA = probatio.Schema( { probatio.Optional(ATTR_ENTITY_ID): entity_ids, @@ -1544,7 +1555,8 @@ SERVICE_SCHEMA = probatio.All( ), probatio.Optional(CONF_ENTITY_ID): comp_entity_ids, probatio.Optional(CONF_TARGET): probatio.Any( - _TARGET_SERVICE_FIELDS_TEMPLATED, dynamic_template + probatio.All(_TARGET_SERVICE_FIELDS_TEMPLATED, exclude_requires_target), + dynamic_template, ), probatio.Optional(CONF_RESPONSE_VARIABLE): str, # The frontend stores data here. Don't use in core. diff --git a/homeassistant/helpers/trigger/models.py b/homeassistant/helpers/trigger/models.py index d5b30e2be3c4..83a61830db16 100644 --- a/homeassistant/helpers/trigger/models.py +++ b/homeassistant/helpers/trigger/models.py @@ -19,7 +19,9 @@ TRIGGERS: HassKey[dict[str, str]] = HassKey("triggers") _TRIGGER_SCHEMA = cv.TRIGGER_BASE_SCHEMA.extend( { probatio.Optional(CONF_OPTIONS): object, - probatio.Optional(CONF_TARGET): cv.TARGET_FIELDS, + probatio.Optional(CONF_TARGET): probatio.All( + cv.TARGET_FIELDS, cv.exclude_requires_target + ), } ) diff --git a/tests/components/websocket_api/test_commands.py b/tests/components/websocket_api/test_commands.py index 64ef66d1f26a..7bbe13f43b07 100644 --- a/tests/components/websocket_api/test_commands.py +++ b/tests/components/websocket_api/test_commands.py @@ -4406,6 +4406,10 @@ async def test_extract_from_target( areas={label_area.id}, ) + # A target which only has an exclude block is accepted while editing + msg = await call_command({"exclude": {"entity_id": ["light.direct"]}}) + _assert_extract_from_target_command_result(msg) + async def test_extract_from_target_expand_group( hass: HomeAssistant, websocket_client: MockHAClientWebSocket diff --git a/tests/helpers/test_condition.py b/tests/helpers/test_condition.py index 58126549c9ef..9ab959429651 100644 --- a/tests/helpers/test_condition.py +++ b/tests/helpers/test_condition.py @@ -6742,6 +6742,43 @@ async def test_state_condition_primary_entities_only_with_duration( assert test.async_check() is True +async def test_condition_target_exclude_only_invalid(hass: HomeAssistant) -> None: + """Test a condition target consisting of only an exclude block is rejected.""" + + class MockCondition(Condition): + """Mock condition.""" + + @classmethod + async def async_validate_config( + cls, hass: HomeAssistant, config: ConfigType + ) -> ConfigType: + """Validate config.""" + return config + + def _async_check(self, **kwargs) -> bool: + """Check the condition.""" + return True + + 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.Invalid, match="an exclude block requires a target to exclude from" + ): + await async_validate_condition_config( + hass, + { + CONF_CONDITION: "test", + CONF_TARGET: {CONF_EXCLUDE: {CONF_ENTITY_ID: "test.excluded"}}, + }, + ) + + _INCLUDED_ENTITY_ID = "test.included" _EXCLUDED_ENTITY_ID = "test.excluded" diff --git a/tests/helpers/test_config_validation.py b/tests/helpers/test_config_validation.py index cdb3d13bb496..5fa500812636 100644 --- a/tests/helpers/test_config_validation.py +++ b/tests/helpers/test_config_validation.py @@ -570,6 +570,21 @@ def test_service() -> None: "alias": "turn on kitchen lights", }, {"action": "scene.turn_on", "metadata": {}}, + { + "action": "light.turn_on", + "target": { + "area_id": "kitchen", + "exclude": {"entity_id": "light.pantry"}, + }, + }, + { + "action": "light.turn_on", + "target": { + "area_id": "{{ 'kitchen' }}", + "exclude": {"entity_id": "light.pantry"}, + }, + }, + {"action": "light.turn_on", "target": "{{ {'area_id': 'kitchen'} }}"}, ], ) def test_service_schema(hass: HomeAssistant, config: dict[str, Any]) -> None: @@ -613,6 +628,10 @@ def test_service_schema(hass: HomeAssistant, config: dict[str, Any]) -> None: "action": "homeassistant.turn_on", "data_template": {"brightness": "{{ no_end"}, }, + { + "action": "light.turn_on", + "target": {"exclude": {"entity_id": "light.pantry"}}, + }, ], ) def test_invalid_service_schema( @@ -730,6 +749,40 @@ def test_target_fields_exclude(schema: probatio.Schema) -> None: schema(value) +@pytest.mark.parametrize( + "value", + [ + pytest.param({}, id="empty"), + pytest.param({"area_id": ["kitchen"]}, id="no_exclude"), + pytest.param( + {"area_id": ["kitchen"], "exclude": {"label_id": ["christmas"]}}, + id="target_and_exclude", + ), + ], +) +def test_exclude_requires_target_valid(value: dict[str, Any]) -> None: + """Test targets which are accepted by exclude_requires_target.""" + assert cv.exclude_requires_target(value) == value + + +@pytest.mark.parametrize( + "value", + [ + pytest.param({"exclude": {"label_id": ["christmas"]}}, id="exclude_only"), + pytest.param( + {"entity_id": [], "exclude": {"label_id": ["christmas"]}}, + id="empty_target_and_exclude", + ), + ], +) +def test_exclude_requires_target_invalid(value: dict[str, Any]) -> None: + """Test a target consisting of only an exclude block is rejected.""" + with pytest.raises( + probatio.Invalid, match="an exclude block requires a target to exclude from" + ): + cv.exclude_requires_target(value) + + def test_entity_service_schema_with_metadata() -> None: """Test make_entity_service_schema with overridden metadata key.""" schema = cv.make_entity_service_schema( diff --git a/tests/helpers/test_trigger.py b/tests/helpers/test_trigger.py index cb6ea65c022e..9c1167bcd760 100644 --- a/tests/helpers/test_trigger.py +++ b/tests/helpers/test_trigger.py @@ -5203,6 +5203,39 @@ async def test_entity_trigger_duration_each_cancelled_when_entity_leaves_target( unsub() +async def test_trigger_target_exclude_only_invalid(hass: HomeAssistant) -> None: + """Test a trigger target consisting of only an exclude block is rejected.""" + + class MockTrigger(Trigger): + """Mock trigger.""" + + @classmethod + async def async_validate_config( + cls, hass: HomeAssistant, config: ConfigType + ) -> ConfigType: + """Validate config.""" + return 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.Invalid, match="an exclude block requires a target to exclude from" + ): + await async_validate_trigger_config( + hass, + [ + { + CONF_PLATFORM: "test", + CONF_TARGET: {CONF_EXCLUDE: {CONF_ENTITY_ID: "test.excluded"}}, + } + ], + ) + + _INCLUDED_ENTITY_ID = "test.included" _EXCLUDED_ENTITY_ID = "test.excluded"