Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions homeassistant/helpers/config_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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


Expand Down
16 changes: 16 additions & 0 deletions tests/helpers/test_config_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down