Skip to content

Commit c7a9a0e

Browse files
authored
Fix TaggedFields value encoding; add test coverage (#2725)
1 parent 9a8af08 commit c7a9a0e

2 files changed

Lines changed: 19 additions & 1 deletion

File tree

kafka/protocol/types.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -335,8 +335,9 @@ def encode(cls, value):
335335
for k, v in value.items():
336336
# do we allow for other data types ?? It could get complicated really fast
337337
assert isinstance(v, bytes), 'Value {} is not a byte array'.format(v)
338-
assert isinstance(k, int) and k > 0, 'Key {} is not a positive integer'.format(k)
338+
assert isinstance(k, int) and k >= 0, 'Key {} is not a non-negative integer'.format(k)
339339
ret += UnsignedVarInt32.encode(k)
340+
ret += UnsignedVarInt32.encode(len(v))
340341
ret += v
341342
return ret
342343

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import io
2+
3+
import pytest
4+
5+
from kafka.protocol.types import TaggedFields, UnsignedVarInt32
6+
7+
8+
def test_tagged_fields():
9+
val = {0: b'fizz', 1: b'foobar'}
10+
encoded = TaggedFields.encode(val)
11+
# length(2), tag(0), size(4), 'fizz', tag(2), size(6), 'foobar'
12+
expected = (UnsignedVarInt32.encode(2) +
13+
UnsignedVarInt32.encode(0) + UnsignedVarInt32.encode(4) + b'fizz' +
14+
UnsignedVarInt32.encode(1) + UnsignedVarInt32.encode(6) + b'foobar')
15+
assert encoded == expected
16+
decoded = TaggedFields.decode(io.BytesIO(encoded))
17+
assert decoded == val

0 commit comments

Comments
 (0)