s-knibbs / dataclasses-jsonschema

JSON schema generation from dataclasses
MIT License
166 stars 38 forks source link

Validation: How to validate from "bad" dataclass object directly? #197

Open lezardo76 opened 1 year ago

lezardo76 commented 1 year ago

First, thanks for this library!

I'm testing it to replace marshmallow and validate our events/commands format before processing it within our message bus.

If I create dataclass objects directly (instead of deserializing from json or dict), they could hold attributes of wrong type ... and I don't see a simple way to execute the validation directly from the dataclass. The only way I found is to do:

myDataclassObject.from_dict(myDataclassObject.to_dict())

is there another way, or a public validate method somehow?

example:

@dataclass class CreateUserCommand(JsonSchemaMixin): id: int name: str

I can instantiate wrong dataclass like: myuser = CreateUserCommand(id='wrong', name=12)

I tried with no success: CreateUserCommand.from_object(myuser)

public validate method would make sense, or validation performed straight at the dataclass initialization, no?

lezardo76 commented 1 year ago

Looking at the code .. I see that we can pass validate=True within to_dict() parameters (default False). So, it avoids deserialization in my trick above.

So temporary, in my default Command class, I include this to make the validation more obvious.

class BaseCommand(JsonSchemaMixin):

has_errors = False
errors = []

def isValid(self):
    is_valid = False
    self.has_errors = False
    self.errors = []
    try:
        is_valid = self.to_dict(validate=True) != {}
    except Exception as e:
        is_valid = False
        self.has_errors = True
        self.errors.append(str(e))
    return is_valid