Skip to content

Commit

Permalink
Handle error from Enum's missing function as ValidationError (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
sydney-runkle authored Apr 22, 2024
1 parent 3240277 commit f537a03
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
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)

0 comments on commit f537a03

Please sign in to comment.