Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve enum error message #7506

Merged
merged 2 commits into from Sep 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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