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

Handle error from Enum's missing function as ValidationError #1274

Merged
merged 3 commits into from
Apr 22, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion src/validators/enum_.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,15 @@ impl<T: EnumValidateValue> Validator for EnumValidator<T> {
return Ok(v);
} else if let Some(ref missing) = self.missing {
state.floor_exactness(Exactness::Lax);
let enum_value = missing.bind(py).call1((input.to_object(py),))?;
let enum_value = missing.bind(py).call1((input.to_object(py),)).map_err(|_| {
ValError::new(
ErrorType::Enum {
expected: self.expected_repr.clone(),
context: None,
},
input,
)
})?;
// check enum_value is an instance of the class like
// https://github.com/python/cpython/blob/v3.12.2/Lib/enum.py#L1148
if enum_value.is_instance(class)? {
Expand Down
20 changes: 19 additions & 1 deletion tests/validators/test_enums.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import re
import sys
from enum import Enum
from enum import Enum, IntFlag

import pytest

Expand Down Expand Up @@ -267,3 +267,21 @@ class MyEnum(Enum):

with pytest.raises(SchemaError, match='`members` should have length > 0'):
SchemaValidator(core_schema.enum_schema(MyEnum, []))


def test_missing_error_converted_to_val_error() -> None:
class MyFlags(IntFlag):
OFF = 0
ON = 1

v = SchemaValidator(
core_schema.with_default_schema(
schema=core_schema.enum_schema(MyFlags, list(MyFlags.__members__.values())), default=MyFlags.OFF
)
)

assert v.validate_python(MyFlags.OFF) is MyFlags.OFF
assert v.validate_python(0) is MyFlags.OFF

with pytest.raises(ValidationError):
v.validate_python(None)
Loading