-
Notifications
You must be signed in to change notification settings - Fork 307
Validate enum values against other possible forms of expected values #1502
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
Open
changhc
wants to merge
9
commits into
pydantic:main
Choose a base branch
from
changhc:10629-fix-enum
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
6aac326
fix enum
changhc 578c893
fix test
changhc dd7f7ca
fix enum
changhc 85e8e09
fix test
changhc 27700b3
Merge branch '10629-fix-enum' of github.com:changhc/pydantic-core int…
changhc 48de7c6
validate values against their json form
changhc 5435ba7
Merge branch 'main' into 10629-fix-enum
changhc a1abde7
add tests
changhc 06ac56d
fix tests
changhc File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -9,10 +9,12 @@ 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::serializers::{to_jsonable_python, SerializationConfig}; | ||
use crate::tools::{safe_repr, SchemaDict}; | ||
|
||
use super::is_instance::class_repr; | ||
use super::literal::{expected_repr_name, LiteralLookup}; | ||
use super::InputType; | ||
use super::{BuildValidator, CombinedValidator, DefinitionsBuilder, Exactness, ValidationState, Validator}; | ||
|
||
#[derive(Debug, Clone)] | ||
|
@@ -33,27 +35,55 @@ impl BuildValidator for BuildEnumValidator { | |
|
||
let py = schema.py(); | ||
let value_str = intern!(py, "value"); | ||
let expected: Vec<(Bound<'_, PyAny>, PyObject)> = members | ||
let expected_py: Vec<(Bound<'_, PyAny>, PyObject)> = members | ||
.iter() | ||
.map(|v| Ok((v.getattr(value_str)?, v.into()))) | ||
.collect::<PyResult<_>>()?; | ||
let ser_config = SerializationConfig::from_config(config).unwrap_or_default(); | ||
let expected_json: Vec<(Bound<'_, PyAny>, PyObject)> = members | ||
.iter() | ||
.map(|v| { | ||
Ok(( | ||
to_jsonable_python( | ||
py, | ||
&v.getattr(value_str)?, | ||
None, | ||
None, | ||
false, | ||
false, | ||
false, | ||
&ser_config.timedelta_mode.to_string(), | ||
&ser_config.bytes_mode.to_string(), | ||
&ser_config.inf_nan_mode.to_string(), | ||
false, | ||
None, | ||
true, | ||
None, | ||
)? | ||
.into_bound(py), | ||
v.into(), | ||
)) | ||
}) | ||
.collect::<PyResult<_>>()?; | ||
|
||
let repr_args: Vec<String> = expected | ||
let repr_args: Vec<String> = expected_py | ||
.iter() | ||
.map(|(k, _)| k.repr()?.extract()) | ||
.collect::<PyResult<_>>()?; | ||
|
||
let class: Bound<PyType> = schema.get_as_req(intern!(py, "cls"))?; | ||
let class_repr = class_repr(schema, &class)?; | ||
|
||
let lookup = LiteralLookup::new(py, expected.into_iter())?; | ||
let py_lookup = LiteralLookup::new(py, expected_py.into_iter())?; | ||
let json_lookup = LiteralLookup::new(py, expected_json.into_iter())?; | ||
Comment on lines
+77
to
+78
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. To minimize memory usage we should probably do something here to avoid having |
||
|
||
macro_rules! build { | ||
($vv:ty, $name_prefix:literal) => { | ||
EnumValidator { | ||
phantom: PhantomData::<$vv>, | ||
class: class.clone().into(), | ||
lookup, | ||
py_lookup, | ||
json_lookup, | ||
missing: schema.get_as(intern!(py, "missing"))?, | ||
expected_repr: expected_repr_name(repr_args, "").0, | ||
strict: is_strict(schema, config)?, | ||
|
@@ -87,7 +117,8 @@ pub trait EnumValidateValue: std::fmt::Debug + Clone + Send + Sync { | |
pub struct EnumValidator<T: EnumValidateValue> { | ||
phantom: PhantomData<T>, | ||
class: Py<PyType>, | ||
lookup: LiteralLookup<PyObject>, | ||
py_lookup: LiteralLookup<PyObject>, | ||
json_lookup: LiteralLookup<PyObject>, | ||
missing: Option<PyObject>, | ||
expected_repr: String, | ||
strict: bool, | ||
|
@@ -120,7 +151,11 @@ impl<T: EnumValidateValue> Validator for EnumValidator<T> { | |
|
||
state.floor_exactness(Exactness::Lax); | ||
|
||
if let Some(v) = T::validate_value(py, input, &self.lookup, strict)? { | ||
let lookup = match state.extra().input_type { | ||
InputType::Json => &self.json_lookup, | ||
_ => &self.py_lookup, | ||
}; | ||
if let Some(v) = T::validate_value(py, input, lookup, strict)? { | ||
return Ok(v); | ||
} else if let Ok(res) = class.as_unbound().call1(py, (input.as_python(),)) { | ||
return Ok(res); | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We should probably refactor
to_jsonable_python
to take these values as enum members rather than strings, to avoid this round-trip.