Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions msgpack/fallback.py
Original file line number Diff line number Diff line change
Expand Up @@ -501,10 +501,13 @@ def _unpack(self, execute=EX_CONSTRUCT):

if execute == EX_READ_ARRAY_HEADER:
if typ != TYPE_ARRAY:
# Leave the object unread, as the C extension does.
self._buff_i = self._buf_checkpoint
raise ValueError("Expected array")
return n
if execute == EX_READ_MAP_HEADER:
if typ != TYPE_MAP:
self._buff_i = self._buf_checkpoint
raise ValueError("Expected map")
return n
# TODO should we eliminate the recursion?
Expand Down
32 changes: 32 additions & 0 deletions test/test_read_size.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
"""Test Unpacker's read_array_header and read_map_header methods"""

from io import BytesIO

from pytest import raises

from msgpack import OutOfData, Unpacker, packb

UnexpectedTypeException = ValueError
Expand Down Expand Up @@ -70,3 +74,31 @@ def test_incorrect_type_nested_map():
assert 0, "should raise exception"
except UnexpectedTypeException:
assert 1, "okay"


def test_incorrect_type_does_not_consume_object():
packed = packb(1) + packb("abc") + packb({"a": 1}) + packb([2])
unpackers = [Unpacker(), Unpacker(BytesIO(packed))]
unpackers[0].feed(packed)
for unpacker in unpackers:
with raises(UnexpectedTypeException):
unpacker.read_array_header()
assert unpacker.tell() == 0
assert unpacker.unpack() == 1

with raises(UnexpectedTypeException):
unpacker.read_map_header()
assert unpacker.unpack() == "abc"

# A map is not an array: the stream must stay in sync.
with raises(UnexpectedTypeException):
unpacker.read_array_header()
assert unpacker.read_map_header() == 1
assert unpacker.unpack() == "a"
assert unpacker.unpack() == 1

with raises(UnexpectedTypeException):
unpacker.read_map_header()
assert unpacker.read_array_header() == 1
assert unpacker.unpack() == 2
assert unpacker.tell() == len(packed)
Loading