def test_unknown_codec_raises(): class UnknownType: pass t = Transcoder() with pytest.raises(MissingCodecError): t.encode(None, UnknownType)
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
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)
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
def test_encode_single_type_sequence_builtin(): t = Transcoder() r = t.encode(tuple(['x']), tuple[str, ...]) assert r == [ 'x', ]
def test_encode_dict(): t = Transcoder() r = t.encode({'0': 'True'}, typing.Dict[int, bool]) assert r == {0: True}
def test_encode_none(): t = Transcoder() assert t.encode(None, type(None)) is None