Improve config validation for key_value_schemas (#49429)
parent
ed9b199372
commit
45e1473f83
|
@ -770,25 +770,25 @@ def deprecated(
|
||||||
|
|
||||||
|
|
||||||
def key_value_schemas(
|
def key_value_schemas(
|
||||||
key: str, value_schemas: dict[str, vol.Schema]
|
key: str, value_schemas: dict[Hashable, vol.Schema]
|
||||||
) -> Callable[[Any], dict[str, Any]]:
|
) -> Callable[[Any], dict[Hashable, Any]]:
|
||||||
"""Create a validator that validates based on a value for specific key.
|
"""Create a validator that validates based on a value for specific key.
|
||||||
|
|
||||||
This gives better error messages.
|
This gives better error messages.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def key_value_validator(value: Any) -> dict[str, Any]:
|
def key_value_validator(value: Any) -> dict[Hashable, Any]:
|
||||||
if not isinstance(value, dict):
|
if not isinstance(value, dict):
|
||||||
raise vol.Invalid("Expected a dictionary")
|
raise vol.Invalid("Expected a dictionary")
|
||||||
|
|
||||||
key_value = value.get(key)
|
key_value = value.get(key)
|
||||||
|
|
||||||
if key_value not in value_schemas:
|
if isinstance(key_value, Hashable) and key_value in value_schemas:
|
||||||
raise vol.Invalid(
|
return cast(Dict[Hashable, Any], value_schemas[key_value](value))
|
||||||
f"Unexpected value for {key}: '{key_value}'. Expected {', '.join(value_schemas)}"
|
|
||||||
)
|
|
||||||
|
|
||||||
return cast(Dict[str, Any], value_schemas[key_value](value))
|
raise vol.Invalid(
|
||||||
|
f"Unexpected value for {key}: '{key_value}'. Expected {', '.join(str(key) for key in value_schemas)}"
|
||||||
|
)
|
||||||
|
|
||||||
return key_value_validator
|
return key_value_validator
|
||||||
|
|
||||||
|
|
|
@ -1024,7 +1024,7 @@ def test_key_value_schemas():
|
||||||
schema(True)
|
schema(True)
|
||||||
assert str(excinfo.value) == "Expected a dictionary"
|
assert str(excinfo.value) == "Expected a dictionary"
|
||||||
|
|
||||||
for mode in None, "invalid":
|
for mode in None, {"a": "dict"}, "invalid":
|
||||||
with pytest.raises(vol.Invalid) as excinfo:
|
with pytest.raises(vol.Invalid) as excinfo:
|
||||||
schema({"mode": mode})
|
schema({"mode": mode})
|
||||||
assert (
|
assert (
|
||||||
|
|
Loading…
Reference in New Issue