Skip to content

Commit 0258167

Browse files
authored
Reject non-callable ext_hook consistently in C extension (#763)
fix #762
1 parent 35bef09 commit 0258167

2 files changed

Lines changed: 32 additions & 5 deletions

File tree

‎msgpack/_unpacker.pyx‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ cdef inline init_ctx(unpack_context *ctx,
7171
ctx.user.use_list = use_list
7272
ctx.user.raw = raw
7373
ctx.user.strict_map_key = strict_map_key
74-
ctx.user.object_hook = ctx.user.list_hook = <PyObject*>NULL
74+
ctx.user.object_hook = ctx.user.list_hook = ctx.user.ext_hook = <PyObject*>NULL
7575
ctx.user.max_str_len = max_str_len
7676
ctx.user.max_bin_len = max_bin_len
7777
ctx.user.max_array_len = max_array_len
@@ -99,10 +99,9 @@ cdef inline init_ctx(unpack_context *ctx,
9999
raise TypeError("list_hook must be a callable.")
100100
ctx.user.list_hook = <PyObject*>list_hook
101101

102-
if ext_hook is not None:
103-
if not PyCallable_Check(ext_hook):
104-
raise TypeError("ext_hook must be a callable.")
105-
ctx.user.ext_hook = <PyObject*>ext_hook
102+
if not PyCallable_Check(ext_hook):
103+
raise TypeError("ext_hook must be a callable.")
104+
ctx.user.ext_hook = <PyObject*>ext_hook
106105

107106
if timestamp < 0 or 3 < timestamp:
108107
raise ValueError("timestamp must be 0..3")

‎test/test_extension.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,37 @@
11
import array
22

3+
import pytest
4+
35
import msgpack
46
from msgpack import ExtType
57

68

9+
@pytest.mark.parametrize("ext_hook", [None, 0, "hook", []])
10+
def test_unpackb_invalid_ext_hook(ext_hook):
11+
with pytest.raises(TypeError, match="ext_hook.*callable"):
12+
msgpack.unpackb(b"\xc0", ext_hook=ext_hook)
13+
14+
15+
@pytest.mark.parametrize("ext_hook", [None, 0, "hook", []])
16+
def test_unpacker_invalid_ext_hook(ext_hook):
17+
with pytest.raises(TypeError, match="ext_hook.*callable"):
18+
msgpack.Unpacker(ext_hook=ext_hook)
19+
20+
21+
@pytest.mark.parametrize("ext_hook", [None, 0, "hook", []])
22+
def test_unpacker_reinit_invalid_ext_hook(ext_hook):
23+
unpacker = msgpack.Unpacker(ext_hook=lambda code, data: (code, data))
24+
unpacker.feed(b"\xd4\x42A")
25+
assert unpacker.unpack() == (0x42, b"A")
26+
27+
with pytest.raises(TypeError, match="ext_hook.*callable"):
28+
unpacker.__init__(ext_hook=ext_hook)
29+
30+
unpacker.__init__()
31+
unpacker.feed(b"\xd4\x42A")
32+
assert unpacker.unpack() == ExtType(0x42, b"A")
33+
34+
735
def test_pack_ext_type():
836
def p(s):
937
packer = msgpack.Packer(autoreset=False)

0 commit comments

Comments
 (0)