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 support for enum #34

Merged
merged 1 commit into from
Dec 20, 2021
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
16 changes: 16 additions & 0 deletions tests/test_lib.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from enum import Enum

import voluptuous as vol

from voluptuous_serialize import UNSUPPORTED, convert
Expand Down Expand Up @@ -188,3 +190,17 @@ def custem_serializer(schema):
def test_constant():
for value in True, False, "Hello", 1:
assert {"type": "constant", "value": value} == convert(vol.Schema(value))


def test_enum():
class TestEnum(Enum):
ONE = "one"
TWO = 2

assert {
"type": "select",
"options": [
("one", "one"),
(2, 2),
],
} == convert(vol.Schema(vol.Coerce(TestEnum)))
7 changes: 7 additions & 0 deletions voluptuous_serialize/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Module to convert voluptuous schemas to dictionaries."""
from collections.abc import Mapping
from enum import Enum

import voluptuous as vol

Expand Down Expand Up @@ -109,4 +110,10 @@ def convert(schema, *, custom_serializer=None):
if isinstance(schema, (str, int, float, bool)):
return {"type": "constant", "value": schema}

if issubclass(schema, Enum):
return {
"type": "select",
"options": [(item.value, item.value) for item in schema],
}

raise ValueError("Unable to convert schema: {}".format(schema))