s-knibbs / dataclasses-jsonschema

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

Custom FieldEncoder is not called with NewType #131

Closed OlgaPaw closed 4 years ago

OlgaPaw commented 4 years ago

Hi, I have a custom field type added to JsonSchemaMixin

StringBoolean = NewType('StringBoolean', bool)

class StringBooleanField(FieldEncoder):
    @property
    def json_schema(self):
        return {'type': 'string'}

    def to_wire(self, value: bool) -> JsonEncodable:
        return str(value)

    def to_python(self, value: JsonEncodable) -> bool:
        return True if str(value).lower() == "true" else False

JsonSchemaMixin.register_field_encoders({StringBoolean: StringBooleanField()})

And a dataclass

@dataclass
class Foo(JsonSchemaMixin):
    name: str
    enabled: StringBoolean

A goal

f = Foo.from_dict({'name': 'test', 'enabled': 'true'})
assert f.enabled is True, f'{type(f.enabled)}: {f.enabled}'

f = Foo.from_dict({'name': 'test', 'enabled': 'false'})
assert f.enabled is False, f'{type(f.enabled)}: {f.enabled}'

I debugged it and it seems that instead of my custom StringBooleanField decoder it calls superclass decoder.

image

I think it should check for custom decoder before superclass decoder.

OlgaPaw commented 4 years ago

I was using old version