Improve config validation for key_value_schemas (#49429)

pull/51339/head
Paulus Schoutsen 2021-06-01 02:23:59 -07:00 committed by GitHub
parent ed9b199372
commit 45e1473f83
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 9 additions and 9 deletions

View File

@ -770,25 +770,25 @@ def deprecated(
def key_value_schemas(
key: str, value_schemas: dict[str, vol.Schema]
) -> Callable[[Any], dict[str, Any]]:
key: str, value_schemas: dict[Hashable, vol.Schema]
) -> Callable[[Any], dict[Hashable, Any]]:
"""Create a validator that validates based on a value for specific key.
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):
raise vol.Invalid("Expected a dictionary")
key_value = value.get(key)
if key_value not in value_schemas:
raise vol.Invalid(
f"Unexpected value for {key}: '{key_value}'. Expected {', '.join(value_schemas)}"
)
if isinstance(key_value, Hashable) and key_value in value_schemas:
return cast(Dict[Hashable, Any], value_schemas[key_value](value))
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

View File

@ -1024,7 +1024,7 @@ def test_key_value_schemas():
schema(True)
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:
schema({"mode": mode})
assert (