Skip to content

Commit

Permalink
Update error message for enum validator (#673)
Browse files Browse the repository at this point in the history
* Update error message for enum validator

* Update history
  • Loading branch information
dmontagu authored and samuelcolvin committed Jul 24, 2019
1 parent b09e697 commit b702eb8
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 4 deletions.
1 change: 1 addition & 0 deletions HISTORY.rst
Expand Up @@ -8,6 +8,7 @@ v0.31 (unreleased)
* better support for floating point `multiple_of` values, #652 by @justindujardin
* fix schema generation for ``NewType`` and ``Literal``, #649 by @dmontagu
* fix ``alias_generator`` and field config conflict, #645 by @gmetzker and #658 by @MrMrRobat
* more detailed message for ``EnumError``, #673 by @dmontagu
* add advanced exclude support for ``dict``, ``json`` and ``copy``, #648 by @MrMrRobat
* fix bug in ``GenericModel`` for models with concrete parameterized fields, #672 by @dmontagu
* add documentation for Literal type, #651 by @dmontagu
Expand Down
4 changes: 3 additions & 1 deletion pydantic/errors.py
Expand Up @@ -86,7 +86,9 @@ class UrlRegexError(PydanticValueError):


class EnumError(PydanticTypeError):
msg_template = 'value is not a valid enumeration member'
def __str__(self) -> str:
permitted = ', '.join(repr(v.value) for v in self.ctx['enum_type']) # type: ignore
return f'value is not a valid enumeration member; permitted: {permitted}'


class IntegerError(PydanticTypeError):
Expand Down
5 changes: 3 additions & 2 deletions pydantic/validators.py
Expand Up @@ -219,9 +219,10 @@ def set_validator(v: Any) -> Set[Any]:


def enum_validator(v: Any, field: 'Field', config: 'BaseConfig') -> Enum:
with change_exception(errors.EnumError, ValueError):
try:
enum_v = field.type_(v)

except ValueError:
raise errors.EnumError(enum_type=field.type_)
return enum_v.value if config.use_enum_values else enum_v


Expand Down
7 changes: 6 additions & 1 deletion tests/test_types.py
Expand Up @@ -473,7 +473,12 @@ def test_enum_fails():
with pytest.raises(ValueError) as exc_info:
CookingModel(tool=3)
assert exc_info.value.errors() == [
{'loc': ('tool',), 'msg': 'value is not a valid enumeration member', 'type': 'type_error.enum'}
{
'loc': ('tool',),
'msg': 'value is not a valid enumeration member; permitted: 1, 2',
'type': 'type_error.enum',
'ctx': {'enum_type': ToolEnum},
}
]


Expand Down

0 comments on commit b702eb8

Please sign in to comment.