summaryrefslogtreecommitdiff
path: root/test/test_extension.py
blob: 0a9c14f5cdf075547bbe7a9f4f639ce004c44812 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import array
import msgpack

def test_extension_type():
    class MyPacker(msgpack.Packer):
        def handle_extended_type(self, obj):
            if isinstance(obj, array.array):
                fmt = "ext 32"
                typecode = 123 # application specific typecode
                data = obj.tostring()
                return fmt, typecode, data

    class MyUnpacker(msgpack.Unpacker):
        def handle_extended_type(self, typecode, data):
            assert typecode == 123
            obj = array.array('d')
            obj.fromstring(data)
            return obj

    obj = [42, 'hello', array.array('d', [1.1, 2.2, 3.3])]
    packer = MyPacker()
    unpacker = MyUnpacker(None)
    s = packer.pack(obj)
    unpacker.feed(s)
    obj2 = unpacker.unpack_one()
    assert obj == obj2