예제 #1
0
def test_unknown_codec_raises():
    class UnknownType:
        pass

    t = Transcoder()
    with pytest.raises(MissingCodecError):
        t.encode(None, UnknownType)
예제 #2
0
def test_encode_optional():
    t = Transcoder()

    r = t.encode('text', typing.Optional[str])
    assert r == 'text'

    r = t.encode(None, typing.Optional[str])
    assert r == None
예제 #3
0
def test_add_new_codec():
    NewType = type('NewType', (), {})

    class NewTypeCodec(ICodec):
        def can_handle(self, field_type: typing.Type) -> bool:
            return field_type is NewType

        def encode(self, obj: typing.Any,
                   field_type: typing.Type) -> typing.Any:
            return True

        def decode(self, data: dict, field_type: typing.Type) -> typing.Any:
            return True

    t = Transcoder()
    t.add_codec(NewTypeCodec())

    assert t.encode(NewType(), NewType)
    assert t.decode({}, NewType)
예제 #4
0
def test_decode_primitive():
    t = Transcoder()

    m = t.encode('x', str)
    assert m == 'x'

    m = t.encode(1, int)
    assert m == 1

    m = t.encode(1.0, int)
    assert m == 1

    m = t.encode(1.1, float)
    assert m == 1.1

    m = t.encode(1, float)
    assert m == 1.0

    m = t.encode(True, bool)
    assert m == True
예제 #5
0
def test_encode_single_type_sequence_builtin():
    t = Transcoder()
    r = t.encode(tuple(['x']), tuple[str, ...])
    assert r == [
        'x',
    ]
예제 #6
0
def test_encode_dict():
    t = Transcoder()

    r = t.encode({'0': 'True'}, typing.Dict[int, bool])
    assert r == {0: True}
예제 #7
0
def test_encode_none():
    t = Transcoder()
    assert t.encode(None, type(None)) is None