Skip to content
This repository has been archived by the owner on Aug 19, 2023. It is now read-only.

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

Open
lezardo76 opened this issue Dec 14, 2022 · 1 comment
Open

Comments

@lezardo76
Copy link

lezardo76 commented Dec 14, 2022

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
Copy link
Author

lezardo76 commented Dec 15, 2022

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

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant