From 5a127a11d9c68bc3d9cf276cd1ab24bb4b0d4417 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Sun, 19 Dec 2021 21:30:27 -0800 Subject: [PATCH] Add support for enum --- tests/test_lib.py | 16 ++++++++++++++++ voluptuous_serialize/__init__.py | 7 +++++++ 2 files changed, 23 insertions(+) diff --git a/tests/test_lib.py b/tests/test_lib.py index 32b1163..570cf6f 100644 --- a/tests/test_lib.py +++ b/tests/test_lib.py @@ -1,3 +1,5 @@ +from enum import Enum + import voluptuous as vol from voluptuous_serialize import UNSUPPORTED, convert @@ -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))) diff --git a/voluptuous_serialize/__init__.py b/voluptuous_serialize/__init__.py index c542aac..2fc09b3 100644 --- a/voluptuous_serialize/__init__.py +++ b/voluptuous_serialize/__init__.py @@ -1,5 +1,6 @@ """Module to convert voluptuous schemas to dictionaries.""" from collections.abc import Mapping +from enum import Enum import voluptuous as vol @@ -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))