Exemple #1
0
def test_field_serialize_override_class_serializer():
    def serializer(cls, o):
        if cls is datetime:
            return o.strftime('%d/%m/%y')
        else:
            raise SerdeSkip()

    def deserializer(cls, o):
        if cls is datetime:
            return datetime.strptime(o, '%d/%m/%y')
        else:
            raise SerdeSkip()

    @serde(serializer=serializer, deserializer=deserializer)
    class Foo:
        i: int
        dt1: datetime
        dt2: datetime = field(
            serializer=lambda x: x.strftime('%y.%m.%d'),
            deserializer=lambda x: datetime.strptime(x, '%y.%m.%d'))

    dt = datetime(2021, 1, 1, 0, 0, 0)
    f = Foo(10, dt, dt)

    assert to_json(f) == '{"i": 10, "dt1": "01/01/21", "dt2": "21.01.01"}'
    assert f == from_json(Foo, to_json(f))

    assert to_tuple(f) == (10, '01/01/21', '21.01.01')
    assert f == from_tuple(Foo, to_tuple(f))
Exemple #2
0
def test_override_by_default_serializer():
    def serializer(cls, o):
        if cls is datetime:
            return o.strftime('%d/%m/%y')
        else:
            raise SerdeSkip()

    def deserializer(cls, o):
        if cls is datetime:
            return datetime.strptime(o, '%d/%m/%y')
        else:
            raise SerdeSkip()

    @serde(serializer=serializer, deserializer=deserializer)
    class Foo:
        i: int
        dt1: datetime
        dt2: datetime = field(serializer=default_serializer,
                              deserializer=default_deserializer)

    dt = datetime(2021, 1, 1, 0, 0, 0)
    f = Foo(10, dt, dt)

    assert to_json(
        f) == '{"i": 10, "dt1": "01/01/21", "dt2": "2021-01-01T00:00:00"}'
    assert f == from_json(Foo, to_json(f))

    assert to_tuple(f) == (10, '01/01/21', datetime(2021, 1, 1, 0, 0))
    assert f == from_tuple(Foo, to_tuple(f))
Exemple #3
0
def test_custom_class_serializer():
    def serializer(cls, o):
        if cls is datetime:
            return o.strftime('%d/%m/%y')
        else:
            raise SerdeSkip()

    def deserializer(cls, o):
        if cls is datetime:
            return datetime.strptime(o, '%d/%m/%y')
        else:
            raise SerdeSkip()

    @serde(serializer=serializer, deserializer=deserializer)
    class Foo:
        i: int
        dt1: datetime
        dt2: datetime
        s: Optional[str] = None
        u: Union[str, int] = 10

    dt = datetime(2021, 1, 1, 0, 0, 0)
    f = Foo(10, dt, dt)

    assert to_json(
        f
    ) == '{"i": 10, "dt1": "01/01/21", "dt2": "01/01/21", "s": null, "u": 10}'
    assert f == from_json(Foo, to_json(f))

    assert to_tuple(f) == (10, '01/01/21', '01/01/21', None, 10)
    assert f == from_tuple(Foo, to_tuple(f))
Exemple #4
0
def test_astuple():
    assert data.PRI_TUPLE == to_tuple(data.PRI)
    assert data.PRI_TUPLE == astuple(data.PRI)
    assert data.PRILIST == to_tuple(PriList(*data.PRILIST))
    assert data.PRILIST == astuple(PriList(*data.PRILIST))
    assert data.NESTED_PRILIST_TUPLE == to_tuple(NestedPriList(*data.NESTED_PRILIST))
    assert data.NESTED_PRILIST_TUPLE == astuple(NestedPriList(*data.NESTED_PRILIST))
Exemple #5
0
def test_custom_class_serializer():
    def serializer(cls, o):
        if cls is datetime:
            return o.strftime('%d/%m/%y')
        else:
            raise SerdeSkip()

    def deserializer(cls, o):
        if cls is datetime:
            return datetime.strptime(o, '%d/%m/%y')
        else:
            raise SerdeSkip()

    @deserialize(deserializer=deserializer)
    @serialize(serializer=serializer)
    @dataclass
    class Foo:
        i: int
        dt1: datetime
        dt2: datetime

    dt = datetime(2021, 1, 1, 0, 0, 0)
    f = Foo(10, dt, dt)

    assert to_json(f) == '{"i": 10, "dt1": "01/01/21", "dt2": "01/01/21"}'
    assert f == from_json(Foo, to_json(f))

    assert to_tuple(f) == (10, '01/01/21', '01/01/21')
    assert f == from_tuple(Foo, to_tuple(f))
Exemple #6
0
def test_custom_field_serializer():
    @deserialize
    @serialize
    @dataclass
    class Foo:
        dt1: datetime
        dt2: datetime = field(
            metadata={
                'serde_serializer': lambda x: x.strftime('%d/%m/%y'),
                'serde_deserializer':
                lambda x: datetime.strptime(x, '%d/%m/%y'),
            })
        dt3: Optional[datetime] = field(
            metadata={
                'serde_serializer':
                lambda x: x.strftime('%d/%m/%y') if x else None,
                'serde_deserializer':
                lambda x: datetime.strptime(x, '%d/%m/%y') if x else None,
            })

    dt = datetime(2021, 1, 1, 0, 0, 0)
    f = Foo(dt, dt, None)

    assert to_json(
        f) == '{"dt1": "2021-01-01T00:00:00", "dt2": "01/01/21", "dt3": null}'
    assert f == from_json(Foo, to_json(f))

    assert to_tuple(f) == (datetime(2021, 1, 1, 0, 0), '01/01/21', None)
    assert f == from_tuple(Foo, to_tuple(f))
Exemple #7
0
def astuple(data):
    return serde.to_tuple(data)
Exemple #8
0
def test_se_func_iter():
    # Primitives
    assert (10,) == to_tuple(Int(10))
    assert (10.0,) == to_tuple(Float(10.0))
    assert ("10",) == to_tuple(Str("10"))
    assert (False,) == to_tuple(Bool(False))

    assert (10, '10', 10.0, False) == to_tuple(Pri(10, "10", 10.0, False))
    assert ((10,),) == to_tuple(NestedInt(Int(10)))
    assert ((10,), ('10',), (10.0,), (True,)) == to_tuple(NestedPri(Int(10), Str("10"), Float(10.0), Bool(True)))

    # List
    assert ([10], ['10'], [10.0], [False]) == to_tuple(PriList([10], ["10"], [10.0], [False]))
    assert ([(10,)], [('10',)], [(10.0,)], [(False,)]) == to_tuple(
        NestedPriList([Int(10)], [Str("10")], [Float(10.0)], [Bool(False)])
    )

    # Dict
    assert ({'i': 10}, {'s': '10'}, {'f': 10.0}, {'b': False}) == to_tuple(
        PriDict({'i': 10}, {'s': "10"}, {'f': 10.0}, {'b': False})
    )
    assert ({'i': 10}, {'s': '10'}, {'f': 10.0}, {'b': False}) == to_tuple(
        PriDict({'i': 10}, {'s': "10"}, {'f': 10.0}, {'b': False})
    )
    assert ({('i',): (10,)}, {('i',): ('10',)}, {('i',): (10.0,)}, {('i',): (True,)}) == to_tuple(
        NestedPriDict({Str('i'): Int(10)}, {Str('i'): Str('10')}, {Str('i'): Float(10.0)}, {Str('i'): Bool(True)})
    )

    # Tuple
    exp = (
        (10, 10, 10),
        ('10', '10', '10', '10'),
        (10.0, 10.0, 10.0, 10.0, 10.0),
        (False, False, False, False, False, False),
    )
    act = to_tuple(
        PriTuple(
            (10, 10, 10),
            ("10", "10", "10", "10"),
            (10.0, 10.0, 10.0, 10.0, 10.0),
            (False, False, False, False, False, False),
        )
    )
    assert exp == act

    exp = (
        ((10,), (10,), (10,)),
        (('10',), ('10',), ('10',), ('10',)),
        ((10.0,), (10.0,), (10.0,), (10.0,), (10.0,)),
        ((False,), (False,), (False,), (False,), (False,), (False,)),
    )
    act = to_tuple(
        NestedPriTuple(
            (Int(10), Int(10), Int(10)),
            (Str("10"), Str("10"), Str("10"), Str("10")),
            (Float(10.0), Float(10.0), Float(10.0), Float(10.0), Float(10.0)),
            (Bool(False), Bool(False), Bool(False), Bool(False), Bool(False), Bool(False)),
        )
    )
    assert exp == act

    # Optional
    assert (10, '10', 10.0, False) == to_tuple(PriOpt(10, "10", 10.0, False))