Change multi_select config validator to class (#31828)
* Move multi_select to class * Fix serializer and add test * Serializer should also return options
This commit is contained in:
parent
d6f0c26e7f
commit
043d36f7c6
2 changed files with 18 additions and 8 deletions
|
@ -588,22 +588,24 @@ def ensure_list_csv(value: Any) -> List:
|
|||
return ensure_list(value)
|
||||
|
||||
|
||||
def multi_select(options: dict) -> Callable[[List], List]:
|
||||
class multi_select:
|
||||
"""Multi select validator returning list of selected values."""
|
||||
|
||||
def validator(selected: List) -> list:
|
||||
"""Return list of selected values."""
|
||||
def __init__(self, options: dict) -> None:
|
||||
"""Initialize multi select."""
|
||||
self.options = options
|
||||
|
||||
def __call__(self, selected: list) -> list:
|
||||
"""Validate input."""
|
||||
if not isinstance(selected, list):
|
||||
raise vol.Invalid("Not a list")
|
||||
|
||||
for value in selected:
|
||||
if value not in options:
|
||||
if value not in self.options:
|
||||
raise vol.Invalid(f"{value} is not a valid option")
|
||||
|
||||
return selected
|
||||
|
||||
return validator
|
||||
|
||||
|
||||
def deprecated(
|
||||
key: str,
|
||||
|
@ -730,8 +732,8 @@ def custom_serializer(schema: Any) -> Any:
|
|||
if schema is positive_time_period_dict:
|
||||
return {"type": "positive_time_period_dict"}
|
||||
|
||||
if schema is multi_select:
|
||||
return {"type": "multi_select"}
|
||||
if isinstance(schema, multi_select):
|
||||
return {"type": "multi_select", "options": schema.options}
|
||||
|
||||
return voluptuous_serialize.UNSUPPORTED
|
||||
|
||||
|
|
|
@ -488,6 +488,14 @@ def test_multi_select():
|
|||
schema(["robban", "paulus"])
|
||||
|
||||
|
||||
def test_multi_select_in_serializer():
|
||||
"""Test multi_select with custom_serializer."""
|
||||
assert cv.custom_serializer(cv.multi_select({"paulus": "Paulus"})) == {
|
||||
"type": "multi_select",
|
||||
"options": {"paulus": "Paulus"},
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def schema():
|
||||
"""Create a schema used for testing deprecation."""
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue