diff --git a/src/serializers/type_serializers/float.rs b/src/serializers/type_serializers/float.rs index 13af9294c..132886c8c 100644 --- a/src/serializers/type_serializers/float.rs +++ b/src/serializers/type_serializers/float.rs @@ -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 { @@ -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::()?; - 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::()?; + 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)?; diff --git a/tests/serializers/test_union.py b/tests/serializers/test_union.py index 9ab121b70..83527f648 100644 --- a/tests/serializers/test_union.py +++ b/tests/serializers/test_union.py @@ -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(