| 1 |
from collections import namedtuple |
| 2 |
|
| 3 |
from msgpack import ExtType, packb, unpackb |
| 4 |
|
| 5 |
|
| 6 |
def test_namedtuple(): |
| 7 |
T = namedtuple("T", "foo bar") |
| 8 |
|
| 9 |
def default(o): |
| 10 |
if isinstance(o, T): |
| 11 |
return dict(o._asdict()) |
| 12 |
raise TypeError(f"Unsupported type {type(o)}") |
| 13 |
|
| 14 |
packed = packb(T(1, 42), strict_types=True, use_bin_type=True, default=default) |
| 15 |
unpacked = unpackb(packed, raw=False) |
| 16 |
assert unpacked == {"foo": 1, "bar": 42} |
| 17 |
|
| 18 |
|
| 19 |
def test_tuple(): |
| 20 |
t = ("one", 2, b"three", (4,)) |
| 21 |
|
| 22 |
def default(o): |
| 23 |
if isinstance(o, tuple): |
| 24 |
return {"__type__": "tuple", "value": list(o)} |
| 25 |
raise TypeError(f"Unsupported type {type(o)}") |
| 26 |
|
| 27 |
def convert(o): |
| 28 |
if o.get("__type__") == "tuple": |
| 29 |
return tuple(o["value"]) |
| 30 |
return o |
| 31 |
|
| 32 |
data = packb(t, strict_types=True, use_bin_type=True, default=default) |
| 33 |
expected = unpackb(data, raw=False, object_hook=convert) |
| 34 |
|
| 35 |
assert expected == t |
| 36 |
|
| 37 |
|
| 38 |
def test_tuple_ext(): |
| 39 |
t = ("one", 2, b"three", (4,)) |
| 40 |
|
| 41 |
MSGPACK_EXT_TYPE_TUPLE = 0 |
| 42 |
|
| 43 |
def default(o): |
| 44 |
if isinstance(o, tuple): |
| 45 |
# Convert to list and pack |
| 46 |
payload = packb(list(o), strict_types=True, use_bin_type=True, default=default) |
| 47 |
return ExtType(MSGPACK_EXT_TYPE_TUPLE, payload) |
| 48 |
raise TypeError(repr(o)) |
| 49 |
|
| 50 |
def convert(code, payload): |
| 51 |
if code == MSGPACK_EXT_TYPE_TUPLE: |
| 52 |
# Unpack and convert to tuple |
| 53 |
return tuple(unpackb(payload, raw=False, ext_hook=convert)) |
| 54 |
raise ValueError(f"Unknown Ext code {code}") |
| 55 |
|
| 56 |
data = packb(t, strict_types=True, use_bin_type=True, default=default) |
| 57 |
expected = unpackb(data, raw=False, ext_hook=convert) |
| 58 |
|
| 59 |
assert expected == t |