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

Fix str subclass validation for enums #1273

Merged
merged 9 commits into from
May 21, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/validators/enum_.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::marker::PhantomData;
use pyo3::exceptions::PyTypeError;
use pyo3::intern;
use pyo3::prelude::*;
use pyo3::types::PyString;
use pyo3::types::{PyDict, PyList, PyType};

use crate::build_tools::{is_strict, py_schema_err};
Expand Down Expand Up @@ -159,8 +160,16 @@ impl EnumValidateValue for PlainEnumValidator {
py: Python<'py>,
input: &I,
lookup: &LiteralLookup<PyObject>,
_strict: bool,
strict: bool,
) -> ValResult<Option<PyObject>> {
// if value is a subclass of str, use validate_str approach
if let Some(py_input) = input.as_python() {
sydney-runkle marked this conversation as resolved.
Show resolved Hide resolved
if !strict && py_input.is_instance_of::<PyString>() {
return Ok(lookup.validate_str(input, false)?.map(|v| v.clone_ref(py)));
}
}

// otherwise, use generic literal lookup
Ok(lookup.validate(py, input)?.map(|(_, v)| v.clone_ref(py)))
}
}
Expand Down
18 changes: 18 additions & 0 deletions tests/validators/test_enums.py
Original file line number Diff line number Diff line change
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_enum_with_str_subclass():
class MyEnum(Enum):
a = 'a'
b = 'b'

v = SchemaValidator(core_schema.enum_schema(MyEnum, list(MyEnum.__members__.values()), sub_type='str'))
sydney-runkle marked this conversation as resolved.
Show resolved Hide resolved

assert v.validate_python(MyEnum.a) is MyEnum.a
assert v.validate_python('a') is MyEnum.a

class MyStr(str):
pass

assert v.validate_python(MyStr('a')) is MyEnum.a
with pytest.raises(ValidationError):
v.validate_python(MyStr('a'), strict=True)