Skip to content

Commit f537a03

Browse files
Handle error from Enum's missing function as ValidationError (#1274)
1 parent 3240277 commit f537a03

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

src/validators/enum_.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,15 @@ impl<T: EnumValidateValue> Validator for EnumValidator<T> {
121121
return Ok(v);
122122
} else if let Some(ref missing) = self.missing {
123123
state.floor_exactness(Exactness::Lax);
124-
let enum_value = missing.bind(py).call1((input.to_object(py),))?;
124+
let enum_value = missing.bind(py).call1((input.to_object(py),)).map_err(|_| {
125+
ValError::new(
126+
ErrorType::Enum {
127+
expected: self.expected_repr.clone(),
128+
context: None,
129+
},
130+
input,
131+
)
132+
})?;
125133
// check enum_value is an instance of the class like
126134
// https://github.com/python/cpython/blob/v3.12.2/Lib/enum.py#L1148
127135
if enum_value.is_instance(class)? {

tests/validators/test_enums.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import re
22
import sys
3-
from enum import Enum
3+
from enum import Enum, IntFlag
44

55
import pytest
66

@@ -267,3 +267,21 @@ class MyEnum(Enum):
267267

268268
with pytest.raises(SchemaError, match='`members` should have length > 0'):
269269
SchemaValidator(core_schema.enum_schema(MyEnum, []))
270+
271+
272+
def test_missing_error_converted_to_val_error() -> None:
273+
class MyFlags(IntFlag):
274+
OFF = 0
275+
ON = 1
276+
277+
v = SchemaValidator(
278+
core_schema.with_default_schema(
279+
schema=core_schema.enum_schema(MyFlags, list(MyFlags.__members__.values())), default=MyFlags.OFF
280+
)
281+
)
282+
283+
assert v.validate_python(MyFlags.OFF) is MyFlags.OFF
284+
assert v.validate_python(0) is MyFlags.OFF
285+
286+
with pytest.raises(ValidationError):
287+
v.validate_python(None)

0 commit comments

Comments
 (0)