Improve condition schema validation (#144793)

This commit is contained in:
Erik Montnemery
2025-09-16 10:44:26 +02:00
committed by GitHub
parent 4bba167ab3
commit 0f372f4b47
3 changed files with 105 additions and 10 deletions

View File

@@ -1108,11 +1108,21 @@ def key_value_schemas(
value_schemas: ValueSchemas,
default_schema: VolSchemaType | Callable[[Any], dict[str, Any]] | None = None,
default_description: str | None = None,
list_alternatives: bool = True,
) -> Callable[[Any], dict[Hashable, Any]]:
"""Create a validator that validates based on a value for specific key.
This gives better error messages.
default_schema: An optional schema to use if the key value is not in value_schemas.
default_description: A description of what is expected by the default schema, this
will be added to the error message.
list_alternatives: If True, list the keys in `value_schemas` in the error message.
"""
if not list_alternatives and not default_description:
raise ValueError(
"default_description must be provided if list_alternatives is False"
)
def key_value_validator(value: Any) -> dict[Hashable, Any]:
if not isinstance(value, dict):
@@ -1127,9 +1137,13 @@ def key_value_schemas(
with contextlib.suppress(vol.Invalid):
return cast(dict[Hashable, Any], default_schema(value))
alternatives = ", ".join(str(alternative) for alternative in value_schemas)
if default_description:
alternatives = f"{alternatives}, {default_description}"
if list_alternatives:
alternatives = ", ".join(str(alternative) for alternative in value_schemas)
if default_description:
alternatives = f"{alternatives}, {default_description}"
else:
# mypy does not understand that default_description is not None here
alternatives = default_description # type: ignore[assignment]
raise vol.Invalid(
f"Unexpected value for {key}: '{key_value}'. Expected {alternatives}"
)
@@ -1753,7 +1767,7 @@ def _base_condition_validator(value: Any) -> Any:
vol.Schema(
{
**CONDITION_BASE_SCHEMA,
CONF_CONDITION: vol.NotIn(BUILT_IN_CONDITIONS),
CONF_CONDITION: vol.All(str, vol.NotIn(BUILT_IN_CONDITIONS)),
},
extra=vol.ALLOW_EXTRA,
)(value)
@@ -1768,6 +1782,8 @@ CONDITION_SCHEMA: vol.Schema = vol.Schema(
CONF_CONDITION,
BUILT_IN_CONDITIONS,
_base_condition_validator,
"a condition, a list of conditions or a valid template",
list_alternatives=False,
),
),
dynamic_template_condition,
@@ -1799,7 +1815,8 @@ CONDITION_ACTION_SCHEMA: vol.Schema = vol.Schema(
dynamic_template_condition_action,
_base_condition_validator,
),
"a list of conditions or a valid template",
"a condition, a list of conditions or a valid template",
list_alternatives=False,
),
)
)