Add tests for int unpacker

This commit is contained in:
ChillerDragon 2023-03-19 14:24:44 +01:00
parent bf28581b44
commit 1a0e195060
2 changed files with 67 additions and 11 deletions

View file

@ -43,3 +43,70 @@ def test_pack_too_big_positive_and_negative():
assert pack_int(-98866996963) == b'\xe2\x9b\xf5\xce\xe0\x05'
assert pack_int(98866996963) == b'\xa3\x9b\xf5\xce\xe0\x05'
def test_unpack_small_positive_ints():
assert unpack_int(b'\x01') == 1
assert unpack_int(b'\x02') == 2
assert unpack_int(b'\x03') == 3
def test_unpack_multi_byte_positive_ints():
assert unpack_int(b'\x3F') == 63
assert unpack_int(b'\x80\x01') == 64
assert unpack_int(b'\x81\x01') == 65
def test_unpack_only_first_int():
assert unpack_int(b'\x01\x01') == 1
# ^
# should only read this byte
assert unpack_int(bytes([0b00000001])) == 1
# ESDDDDDD
assert unpack_int(bytes([0b00000001, 0b00000001])) == 1
# ESDDDDDD ESDDDDDD
# ^
# not extended
# ignore next byte
assert unpack_int(bytes([0b01000010, 0b11111111])) == -3
# ESDDDDDD ESDDDDDD
# ^^ ^ ^
# || \______/
# || |
# || should all be ignored by the unpacker
# ||
# ||
# |sign bit -> negative
# |
# not extended
# ignore next byte
def test_repacked_ints_should_match():
for i in range(-127, 128):
assert i == unpack_int(pack_int(i))
for i in range(512, 1024):
assert i == unpack_int(pack_int(i))
for i in range(-512, -1024):
assert i == unpack_int(pack_int(i))
def test_multi_byte_repacked_ints_should_match():
for i in range(8_000, 8_500):
assert i == unpack_int(pack_int(i))
for i in range(-8_000, 8_500):
assert i == unpack_int(pack_int(i))
for i in range(-9_900, 10_100):
assert i == unpack_int(pack_int(i))
def test_big_repacked_ints_should_match():
for i in [
99_000,
-99_000,
500_000,
-500_000,
900_000,
-900_000,
99_999_999,
-99_999_999,
999_999_999_999_999
-999_999_999_999_999]:
assert i == unpack_int(pack_int(i))

View file

@ -21,10 +21,7 @@ def pack_int(num: int) -> bytes:
# TODO: optimize performance and benchmark in tests
def unpack_int(data: bytes) -> int:
sign = (data[0] >> 6) & 1
print(f"sign={sign}")
res = data[0] & 0x3F
i = 0
# fake loop should only loop once
# its the poor mans goto hack
@ -52,11 +49,3 @@ def unpack_int(data: bytes) -> int:
res ^= -sign
return res
print(unpack_int(pack_int(1)))
print(unpack_int(pack_int(2)))
print(unpack_int(pack_int(3)))
print(unpack_int(pack_int(-1)))
print(unpack_int(pack_int(-2)))
print(unpack_int(pack_int(-3)))