Skip to content

Commit

Permalink
Improve enum error message (#7506)
Browse files Browse the repository at this point in the history
  • Loading branch information
hramezani committed Sep 19, 2023
1 parent f468466 commit 02f963c
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pydantic/_internal/_std_types_schema.py
Expand Up @@ -72,7 +72,7 @@ def get_enum_core_schema(enum_type: type[Enum], config: ConfigDict) -> CoreSchem
if len(cases) == 1:
expected = repr(cases[0].value)
else:
expected = ','.join([repr(case.value) for case in cases[:-1]]) + f' or {cases[-1].value!r}'
expected = ', '.join([repr(case.value) for case in cases[:-1]]) + f' or {cases[-1].value!r}'

def to_enum(__input_value: Any) -> Enum:
try:
Expand Down
1 change: 1 addition & 0 deletions tests/test_fastapi.sh
Expand Up @@ -31,3 +31,4 @@ cd .. && pip install . && cd fastapi
--deselect tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001.py::test_openapi_schema \
--deselect tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py310.py::test_openapi_schema \
--deselect tests/test_tutorial/test_separate_openapi_schemas/test_tutorial001_py39.py::test_openapi_schema \
--deselect tests/test_tutorial/test_path_params/test_tutorial005.py::test_get_enums_invalid \
23 changes: 23 additions & 0 deletions tests/test_types.py
Expand Up @@ -1522,6 +1522,29 @@ def test_enum_fails(cooking_model):
]


def test_enum_fails_error_msg():
class Number(IntEnum):
one = 1
two = 2
three = 3

class Model(BaseModel):
num: Number

with pytest.raises(ValueError) as exc_info:
Model(num=4)
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'enum',
'loc': ('num',),
'msg': 'Input should be 1, 2 or 3',
'input': 4,
'ctx': {'expected': '1, 2 or 3'},
}
]


def test_int_enum_successful_for_str_int(cooking_model):
FruitEnum, ToolEnum, CookingModel = cooking_model
m = CookingModel(tool='2')
Expand Down

0 comments on commit 02f963c

Please sign in to comment.