Repository: adamboche/python-marshmallow-union

Issue:
_serialize ignores the given value
The `_serialize` method of `Union` calls the `serialize` method (instead of `_serialize`) on the underlying fields. This means that it ignores the given `value` parameter, and may try to serialize a completely different value.

See: https://github.com/adamboche/python-marshmallow-union/blob/master/src/marshmallow_union/__init__.py#L66-L68

Initially reported in: https://github.com/lovasoa/marshmallow_dataclass/issues/67

Discussion:

Patch:
diff --git a/src/marshmallow_union/__init__.py b/src/marshmallow_union/__init__.py
index 22d5ef4..ee47920 100644
--- a/src/marshmallow_union/__init__.py
+++ b/src/marshmallow_union/__init__.py
@@ -13,6 +13,7 @@ class MarshmallowUnionException(Exception):
 
 class ExceptionGroup(MarshmallowUnionException):
     """Collection of possibly multiple exceptions."""
+
     def __init__(self, msg: str, errors):
         self.msg = msg
         self.errors = errors
@@ -63,8 +64,8 @@ class Union(marshmallow.fields.Field):
         for candidate_field in fields:
 
             try:
-                return candidate_field.serialize(
-                    attr, obj, error_store=error_store, **kwargs
+                return candidate_field._serialize(
+                    value, attr, obj, error_store=error_store, **kwargs
                 )
             except ValueError as e:
                 error_store.store_error({attr: e})


Test patch:
diff --git a/tests/test_union.py b/tests/test_union.py
index 6377c06..c93f004 100644
--- a/tests/test_union.py
+++ b/tests/test_union.py
@@ -52,6 +52,14 @@ class IntStrSchema(marshmallow.Schema):
     x = marshmallow_union.Union([marshmallow.fields.Int(), marshmallow.fields.String()])
 
 
+class ListUnionSchema(marshmallow.Schema):
+    """Schema with a list of unions."""
+
+    l = marshmallow.fields.List(
+        marshmallow_union.Union([marshmallow.fields.Int(), marshmallow.fields.String()])
+    )
+
+
 @pytest.mark.parametrize(
     "data, schema",
     [
@@ -59,6 +67,7 @@ class IntStrSchema(marshmallow.Schema):
         ({"name": "Alice", "number_or_numbers": [25, 50]}, PersonSchema()),
         ({"name": "Alice", "number_or_numbers": [25, 50]}, OtherSchema()),
         ({"x": 5}, IntStrSchema()),
+        ({"l": ["h", 5, "n", 1]}, ListUnionSchema()),
         ({"x": "hello"}, IntStrSchema()),
         ({"items": {"a": 42, "b": [17]}}, MappingSchema()),
     ],