Skip to content

Commit

Permalink
Change multi_select config validator to class (#31828)
Browse files Browse the repository at this point in the history
* Move multi_select to class

* Fix serializer and add test

* Serializer should also return options
  • Loading branch information
Kane610 committed Feb 14, 2020
1 parent d6f0c26 commit 043d36f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
18 changes: 10 additions & 8 deletions homeassistant/helpers/config_validation.py
Expand Up @@ -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,
Expand Down Expand Up @@ -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

Expand Down
8 changes: 8 additions & 0 deletions tests/helpers/test_config_validation.py
Expand Up @@ -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."""
Expand Down

0 comments on commit 043d36f

Please sign in to comment.