diff --git a/homeassistant/helpers/config_validation.py b/homeassistant/helpers/config_validation.py index ed619cc9678..40457ef92c8 100644 --- a/homeassistant/helpers/config_validation.py +++ b/homeassistant/helpers/config_validation.py @@ -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 diff --git a/tests/helpers/test_config_validation.py b/tests/helpers/test_config_validation.py index 232d7bbb8b6..02303825bbd 100644 --- a/tests/helpers/test_config_validation.py +++ b/tests/helpers/test_config_validation.py @@ -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 (