Skip to content

Commit

Permalink
Add support for enum (#34)
Browse files Browse the repository at this point in the history
  • Loading branch information
balloob authored Dec 20, 2021
1 parent 19e4655 commit aee46ba
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
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))

0 comments on commit aee46ba

Please sign in to comment.