Skip to content

Commit

Permalink
Fix enum strict JSON validation when validators are present
Browse files Browse the repository at this point in the history
  • Loading branch information
Viicos committed Feb 12, 2025
1 parent 51bae7d commit f7a81ac
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/validators/enum_.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use pyo3::types::{PyDict, PyFloat, PyInt, PyList, PyString, PyType};

use crate::build_tools::{is_strict, py_schema_err};
use crate::errors::{ErrorType, ValError, ValResult};
use crate::input::Input;
use crate::input::{Input, InputType};
use crate::tools::{safe_repr, SchemaDict};

use super::is_instance::class_repr;
Expand Down Expand Up @@ -107,7 +107,7 @@ impl<T: EnumValidateValue> Validator for EnumValidator<T> {
return Ok(exact_py_input.clone().unbind());
}
let strict = state.strict_or(self.strict);
if strict && input.as_python().is_some() {
if strict && state.extra().input_type == InputType::Python {
// TODO what about instances of subclasses?
return Err(ValError::new(
ErrorType::IsInstanceOf {
Expand Down
17 changes: 17 additions & 0 deletions tests/validators/test_enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -487,3 +487,20 @@ def __new__(cls, species: str, sound: str):
assert v.validate_python('meow') is Animal.CAT
assert v.validate_python('dog') is Animal.DOG
assert v.validate_python('woof') is Animal.DOG


def test_strict_enum_wrap_json() -> None:
"""https://github.com/pydantic/pydantic/issues/11070"""

class Animal(str, Enum):
CAT = 'cat'
DOG = 'dog'

schema = core_schema.no_info_wrap_validator_function(
lambda v, handler: handler(v),
core_schema.enum_schema(Animal, list(Animal.__members__.values()), sub_type='str', strict=True),
)
v = SchemaValidator(schema)

assert v.validate_python(Animal.CAT) == Animal.CAT
assert v.validate_json('"dog"') == Animal.DOG

0 comments on commit f7a81ac

Please sign in to comment.