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 float serialization behavior in strict mode #1400

Merged
merged 4 commits into from
Aug 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions src/serializers/type_serializers/float.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ use crate::tools::SchemaDict;
use super::simple::to_str_json_key;
use super::{
infer_json_key, infer_serialize, infer_to_python, BuildSerializer, CombinedSerializer, Extra, IsType, ObType,
SerMode, TypeSerializer,
SerCheck, SerMode, TypeSerializer,
};
use crate::serializers::errors::PydanticSerializationUnexpectedValue;

#[derive(Debug, Clone)]
pub struct FloatSerializer {
Expand Down Expand Up @@ -73,12 +74,15 @@ impl TypeSerializer for FloatSerializer {
let py = value.py();
match extra.ob_type_lookup.is_type(value, ObType::Float) {
IsType::Exact => Ok(value.into_py(py)),
IsType::Subclass => match extra.mode {
SerMode::Json => {
let rust_value = value.extract::<f64>()?;
Ok(rust_value.to_object(py))
}
_ => infer_to_python(value, include, exclude, extra),
IsType::Subclass => match extra.check {
SerCheck::Strict => Err(PydanticSerializationUnexpectedValue::new_err(None)),
SerCheck::Lax | SerCheck::None => match extra.mode {
SerMode::Json => {
let rust_value = value.extract::<f64>()?;
Ok(rust_value.to_object(py))
}
_ => infer_to_python(value, include, exclude, extra),
},
},
IsType::False => {
extra.warnings.on_fallback_py(self.get_name(), value, extra)?;
Expand Down
12 changes: 12 additions & 0 deletions tests/serializers/test_union.py
Original file line number Diff line number Diff line change
Expand Up @@ -628,6 +628,18 @@ def test_union_serializer_picks_exact_type_over_subclass_json(
assert s.to_json(input_value) == json.dumps(expected_value).encode()


def test_union_float_int() -> None:
s = SchemaSerializer(core_schema.union_schema([core_schema.float_schema(), core_schema.int_schema()]))

assert s.to_python(1) == 1
assert json.loads(s.to_json(1)) == 1

s = SchemaSerializer(core_schema.union_schema([core_schema.int_schema(), core_schema.float_schema()]))

assert s.to_python(1) == 1
assert json.loads(s.to_json(1)) == 1


def test_custom_serializer() -> None:
s = SchemaSerializer(
core_schema.union_schema(
Expand Down
Loading