msgpack-python/test/test_obj.py

82 lines
2.1 KiB
Python
Raw Normal View History

#!/usr/bin/env python
2012-12-29 11:24:25 +09:00
from pytest import raises
2012-07-04 14:58:36 +09:00
from msgpack import packb, unpackb
2019-12-05 18:51:45 +09:00
def _decode_complex(obj):
2019-12-05 18:51:45 +09:00
if b"__complex__" in obj:
return complex(obj[b"real"], obj[b"imag"])
return obj
2019-12-05 18:51:45 +09:00
def _encode_complex(obj):
if isinstance(obj, complex):
2019-12-05 18:51:45 +09:00
return {b"__complex__": True, b"real": 1, b"imag": 2}
return obj
2019-12-05 18:51:45 +09:00
def test_encode_hook():
2019-12-05 18:51:45 +09:00
packed = packb([3, 1 + 2j], default=_encode_complex)
2012-09-24 02:20:53 +09:00
unpacked = unpackb(packed, use_list=1)
2019-12-05 18:51:45 +09:00
assert unpacked[1] == {b"__complex__": True, b"real": 1, b"imag": 2}
def test_decode_hook():
2019-12-05 18:51:45 +09:00
packed = packb([3, {b"__complex__": True, b"real": 1, b"imag": 2}])
2012-09-24 02:20:53 +09:00
unpacked = unpackb(packed, object_hook=_decode_complex, use_list=1)
2019-12-05 18:51:45 +09:00
assert unpacked[1] == 1 + 2j
2012-09-23 19:37:28 +10:00
def test_decode_pairs_hook():
packed = packb([3, {1: 2, 3: 4}])
prod_sum = 1 * 2 + 3 * 4
2019-12-05 18:51:45 +09:00
unpacked = unpackb(
packed,
object_pairs_hook=lambda lst: sum(k * v for k, v in lst),
use_list=1,
strict_map_key=False,
2019-12-05 18:51:45 +09:00
)
2012-12-29 11:24:25 +09:00
assert unpacked[1] == prod_sum
2012-09-23 19:37:28 +10:00
2019-12-05 18:51:45 +09:00
2012-09-23 19:37:28 +10:00
def test_only_one_obj_hook():
with raises(TypeError):
2019-12-05 18:51:45 +09:00
unpackb(b"", object_hook=lambda x: x, object_pairs_hook=lambda x: x)
2012-09-23 19:37:28 +10:00
def test_bad_hook():
2013-10-20 22:59:27 +09:00
with raises(TypeError):
2019-12-05 18:51:45 +09:00
packed = packb([3, 1 + 2j], default=lambda o: o)
unpackb(packed, use_list=1)
2019-12-05 18:51:45 +09:00
2010-10-26 02:09:52 +09:00
def _arr_to_str(arr):
2019-12-05 18:51:45 +09:00
return "".join(str(c) for c in arr)
2010-10-26 02:09:52 +09:00
def test_array_hook():
2019-12-05 18:51:45 +09:00
packed = packb([1, 2, 3])
2012-09-24 02:20:53 +09:00
unpacked = unpackb(packed, list_hook=_arr_to_str, use_list=1)
2019-12-05 18:51:45 +09:00
assert unpacked == "123"
2010-10-26 02:09:52 +09:00
class DecodeError(Exception):
pass
2019-12-05 18:51:45 +09:00
def bad_complex_decoder(o):
raise DecodeError("Ooops!")
def test_an_exception_in_objecthook1():
2012-12-29 11:24:25 +09:00
with raises(DecodeError):
2019-12-05 18:51:45 +09:00
packed = packb({1: {"__complex__": True, "real": 1, "imag": 2}})
unpackb(packed, object_hook=bad_complex_decoder, strict_map_key=False)
def test_an_exception_in_objecthook2():
2012-12-29 11:24:25 +09:00
with raises(DecodeError):
2019-12-05 18:51:45 +09:00
packed = packb({1: [{"__complex__": True, "real": 1, "imag": 2}]})
unpackb(packed, list_hook=bad_complex_decoder, use_list=1, strict_map_key=False)