s-knibbs / dataclasses-jsonschema

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

Unrecognized enum values not handled correctly if the field is optional #134

Closed s-knibbs closed 4 years ago

s-knibbs commented 4 years ago

The following will raise a ValueError when it shouldn't:

    class PetType(Enum):
        CAT = "cat"
        DOG = "dog"

    @dataclass
    class Pet(JsonSchemaMixin):
        name: str
        type: Optional[PetType] = None

    p = Pet.from_dict({'name': 'snakey', 'type': 'python'}, validate_enums=False)

This happens because we don't check if the field is optional here:

                try:
                    values[f.field.name] = cls._decode_field(f.field.name, f.field.type, data.get(f.mapped_name))
                except ValueError:
                    if is_enum(f.field.type):
                        values[f.field.name] = data.get(f.mapped_name)
                    else:
                        raise