|
1 | 1 | from io import BytesIO |
2 | 2 | import sys |
3 | | -from msgpack import Unpacker, packb, OutOfData |
| 3 | +from msgpack import Unpacker, packb, OutOfData, ExtType |
4 | 4 | from pytest import raises, mark |
5 | 5 |
|
6 | 6 |
|
@@ -42,6 +42,30 @@ def hook(x): |
42 | 42 | assert sys.getrefcount(hook) == basecnt |
43 | 43 |
|
44 | 44 |
|
| 45 | +def test_unpacker_ext_hook(): |
| 46 | + |
| 47 | + class MyUnpacker(Unpacker): |
| 48 | + |
| 49 | + def __init__(self): |
| 50 | + super(MyUnpacker, self).__init__(ext_hook=self._hook, |
| 51 | + encoding='utf-8') |
| 52 | + |
| 53 | + def _hook(self, code, data): |
| 54 | + if code == 1: |
| 55 | + return int(data) |
| 56 | + else: |
| 57 | + return ExtType(code, data) |
| 58 | + |
| 59 | + unpacker = MyUnpacker() |
| 60 | + unpacker.feed(packb({'a': 1}, encoding='utf-8')) |
| 61 | + assert unpacker.unpack() == {'a': 1} |
| 62 | + unpacker.feed(packb({'a': ExtType(1, b'123')}, encoding='utf-8')) |
| 63 | + assert unpacker.unpack() == {'a': 123} |
| 64 | + unpacker.feed(packb({'a': ExtType(2, b'321')}, encoding='utf-8')) |
| 65 | + assert unpacker.unpack() == {'a': ExtType(2, b'321')} |
| 66 | + |
| 67 | + |
45 | 68 | if __name__ == '__main__': |
46 | 69 | test_unpack_array_header_from_file() |
47 | 70 | test_unpacker_hook_refcnt() |
| 71 | + test_unpacker_ext_hook() |
0 commit comments