lovasoa / marshmallow_dataclass

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

"dump" ignores validation #254

Closed rayrapetyan closed 6 months ago

rayrapetyan commented 6 months ago

Seems Schema().dump ignores all kind of validation, e.g. given code below:

import dataclasses
from marshmallow_dataclass import dataclass

class Animal:
    color: str
    age: int

@dataclass
class AnimalDTO:
    color: str = dataclasses.field(metadata={'required':True})
    age: int = dataclasses.field(metadata={'required':True})
    foo: str = dataclasses.field(metadata={'required':True})

a = Animal()
a.color = "green"
a.age = 34

a_dct: dict = AnimalDTO.Schema().dump(a)
print(a_dct)

"a" misses field foo defined in AnimalDTO, but dump passes successfully just ignoring the foo field. It looks like dump is always succeeding no matter what...

dv297 commented 6 months ago

I haven't used this library directly but I was browsing resources around Marshmallow and stumbled upon this. Since this library is built on-top of Marshmallow, it probably inherits Marshmallow's dump behavior.

From the original Mashmallow docs

Validation occurs on deserialization but not on serialization. 
To improve serialization performance, data passed to Schema.dump() are considered valid.

https://marshmallow.readthedocs.io/en/stable/quickstart.html#validation

For what it's worth, Marshmallow's behavior on this also surprised me 🤷 But yea, it might be outside the scope of this library.

dairiki commented 6 months ago

Since this library is built on-top of Marshmallow, it probably inherits Marshmallow's dump behavior.

This is the correct answer. Marshmallow schemas (which is what marshmallow_dataclass constructs) do not validate on serialization. (The model is: untrusted user data is validated when deserialized, after which the python-side data --- including that constructed programmatically --- is assumed to be valid.)

Closing.