Skip to content

Commit 6cf017e

Browse files
epenetalecthomas
authored andcommitted
Display valid Enum values in Coerce
1 parent 980a55f commit 6cf017e

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

voluptuous/tests/tests.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import copy
22
import collections
3+
from enum import Enum
34
import os
45
import sys
56

@@ -1599,3 +1600,39 @@ def test_any_with_discriminant():
15991600
assert_equal(str(e), 'expected bool for dictionary value @ data[\'implementation\'][\'c-value\']')
16001601
else:
16011602
assert False, "Did not raise correct Invalid"
1603+
1604+
def test_coerce_enum():
1605+
"""Test Coerce Enum"""
1606+
class Choice(Enum):
1607+
Easy = 1
1608+
Medium = 2
1609+
Hard = 3
1610+
1611+
class StringChoice(str, Enum):
1612+
Easy = "easy"
1613+
Medium = "medium"
1614+
Hard = "hard"
1615+
1616+
schema = Schema(Coerce(Choice))
1617+
string_schema = Schema(Coerce(StringChoice))
1618+
1619+
# Valid value
1620+
assert schema(1) == Choice.Easy
1621+
assert string_schema("easy") == StringChoice.Easy
1622+
1623+
# Invalid value
1624+
try:
1625+
schema(4)
1626+
except Invalid as e:
1627+
assert_equal(str(e),
1628+
"expected Choice or one of 1, 2, 3")
1629+
else:
1630+
assert False, "Did not raise Invalid for String"
1631+
1632+
try:
1633+
string_schema("hello")
1634+
except Invalid as e:
1635+
assert_equal(str(e),
1636+
"expected StringChoice or one of 'easy', 'medium', 'hard'")
1637+
else:
1638+
assert False, "Did not raise Invalid for String"

voluptuous/validators.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import sys
55
from functools import wraps
66
from decimal import Decimal, InvalidOperation
7+
from enum import Enum
78

89
from voluptuous.schema_builder import Schema, raises, message
910
from voluptuous.error import (MultipleInvalid, CoerceInvalid, TrueInvalid, FalseInvalid, BooleanInvalid, Invalid,
@@ -95,6 +96,8 @@ def __call__(self, v):
9596
return self.type(v)
9697
except (ValueError, TypeError, InvalidOperation):
9798
msg = self.msg or ('expected %s' % self.type_name)
99+
if not self.msg and issubclass(self.type, Enum):
100+
msg += " or one of %s" % str([e.value for e in self.type])[1:-1]
98101
raise CoerceInvalid(msg)
99102

100103
def __repr__(self):

0 commit comments

Comments
 (0)