From f537a03fad095e4e04c465fcfe29036bb2b2fe67 Mon Sep 17 00:00:00 2001 From: Sydney Runkle <54324534+sydney-runkle@users.noreply.github.com> Date: Mon, 22 Apr 2024 08:31:19 -0500 Subject: [PATCH] Handle error from `Enum`'s `missing` function as `ValidationError` (#1274) --- src/validators/enum_.rs | 10 +++++++++- tests/validators/test_enums.py | 20 +++++++++++++++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/validators/enum_.rs b/src/validators/enum_.rs index cf65c2f96..2c9ae4b28 100644 --- a/src/validators/enum_.rs +++ b/src/validators/enum_.rs @@ -121,7 +121,15 @@ impl Validator for EnumValidator { 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)? { diff --git a/tests/validators/test_enums.py b/tests/validators/test_enums.py index 89db8aa21..49abc415b 100644 --- a/tests/validators/test_enums.py +++ b/tests/validators/test_enums.py @@ -1,6 +1,6 @@ import re import sys -from enum import Enum +from enum import Enum, IntFlag import pytest @@ -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)