Add multi select support to config validation and to custom serializer (#31798)

pull/31812/head
Robert Svensson 2020-02-13 22:12:09 +01:00 committed by GitHub
parent fdfe88566b
commit 6211a2bb98
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 36 additions and 0 deletions

View File

@ -588,6 +588,23 @@ def ensure_list_csv(value: Any) -> List:
return ensure_list(value)
def multi_select(options: dict) -> Callable[[List], List]:
"""Multi select validator returning list of selected values."""
def validator(selected: List) -> list:
"""Return list of selected values."""
if not isinstance(selected, list):
raise vol.Invalid("Not a list")
for value in selected:
if value not in options:
raise vol.Invalid(f"{value} is not a valid option")
return selected
return validator
def deprecated(
key: str,
replacement_key: Optional[str] = None,
@ -713,6 +730,9 @@ 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"}
return voluptuous_serialize.UNSUPPORTED

View File

@ -472,6 +472,22 @@ def test_datetime():
schema("2016-11-23T18:59:08")
def test_multi_select():
"""Test multi select validation.
Expected behavior:
- Will not accept any input but a list
- Will not accept selections outside of configured scope
"""
schema = vol.Schema(cv.multi_select({"paulus": "Paulus", "robban": "Robban"}))
with pytest.raises(vol.Invalid):
schema("robban")
schema(["paulus", "martinhj"])
schema(["robban", "paulus"])
@pytest.fixture
def schema():
"""Create a schema used for testing deprecation."""