lovasoa / marshmallow_dataclass

Automatic generation of marshmallow schemas from dataclasses.
https://lovasoa.github.io/marshmallow_dataclass/html/marshmallow_dataclass.html
MIT License
459 stars 78 forks source link

Getting a ValidationError obj per every type defined in Union type #126

Open chespinoza opened 3 years ago

chespinoza commented 3 years ago

Hi folks, I've found this behaviour in my tests for failure cases, so realised that here was a Union type example so tried introducing validation error and got the same issue, basically every time you add a new type into a Union when validating an error case it results in nested Validation Errors objects which is something I wouldn't expect.

For this example for this code I'm getting this error, if you add another class to the union you'll get another ValidationError obj appended in the list.

marshmallow.exceptions.ValidationError: {
    "elements": {
        0: [
            ValidationError(
                {
                    "type": ["Missing data for required field."],
                    "typo": ["Unknown field."],
                }
            ),
            ValidationError(
                {
                    "type": ["Missing data for required field."],
                    "typo": ["Unknown field."],
                }
            ),
        ]
    }
}
from marshmallow_dataclass import dataclass
from dataclasses import field
from typing import List, Union
from marshmallow.validate import Equal

@dataclass
class Vector:
    type: str = field(metadata={"validate": Equal("Vector")})
    x: float
    y: float

@dataclass
class Point:
    type: str = field(metadata={"validate": Equal("Point")})
    x: float
    y: float

@dataclass
class Geometries:
    elements: List[Union[Point, Vector]]

pts = Geometries.Schema().load({"elements": [
    {"typo":"Point", "x": 1, "y": 1},
    {"type":"Vector", "x": 1, "y": 1},
]})

print(pts)

I would expect just receiving one serialisable (*.messages) ValidationError as the exception is thrown when validating the Point type, not getting nested ValidationErrors per every type (Point,Vector) defined into a Union.

Thanks in advance.

antoine-chopin commented 7 months ago

Hello, I have this issue as well, were you able to find a solution for it?