From cee1fb2758ef5be75f1985b65457b151b369a28e Mon Sep 17 00:00:00 2001 From: Jakob Scheid Date: Thu, 2 Apr 2026 13:38:59 +0200 Subject: [PATCH] Add tests for jeb_utils.utils.int_to_bytes --- src/jeb_utils/utils.py | 3 +- tests/unit/utils/test_int_to_bytes.py | 44 +++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 tests/unit/utils/test_int_to_bytes.py diff --git a/src/jeb_utils/utils.py b/src/jeb_utils/utils.py index 6903c1d..f35d3a2 100644 --- a/src/jeb_utils/utils.py +++ b/src/jeb_utils/utils.py @@ -64,7 +64,8 @@ def int_to_bytes(n: int, signed: bool = False) -> bytes: :rtype: bytes ''' n = int(n) - length = (n.bit_length() + 7) // 8 + signed_term = 1 if signed else 0 + length = (n.bit_length() + 7 + signed_term) // 8 if length == 0: length = 1 return n.to_bytes(length, signed=signed) diff --git a/tests/unit/utils/test_int_to_bytes.py b/tests/unit/utils/test_int_to_bytes.py new file mode 100644 index 0000000..7ad976c --- /dev/null +++ b/tests/unit/utils/test_int_to_bytes.py @@ -0,0 +1,44 @@ +from src.jeb_utils.utils import int_to_bytes +import pytest + +@pytest.mark.parametrize('n,signed,expected', [ + (0, False, b'\x00'), + (1, False, b'\x01'), + (2, False, b'\x02'), + (3, False, b'\x03'), + (42, False, b'\x2a'), + (254, False, b'\xfe'), + (255, False, b'\xff'), + (256, False, b'\x01\x00'), + (512, False, b'\x02\x00'), + (513, False, b'\x02\x01'), + + (0, True, b'\x00'), + (1, True, b'\x01'), + (2, True, b'\x02'), + (3, True, b'\x03'), + (42, True, b'\x2a'), + (127, True, b'\x7f'), + (128, True, b'\x00\x80'), + (254, True, b'\x00\xfe'), + (255, True, b'\x00\xff'), + (256, True, b'\x01\x00'), + (512, True, b'\x02\x00'), + (513, True, b'\x02\x01'), + + (-1, True, b'\xff'), + (-2, True, b'\xfe'), + (-3, True, b'\xfd'), + (-42, True, b'\xd6'), + (-127, True, b'\x81'), + (-128, True, b'\xff\x80'), + (-254, True, b'\xff\x02'), + (-255, True, b'\xff\x01'), + (-256, True, b'\xff\x00'), + (-510, True, b'\xfe\x02'), + (-511, True, b'\xfe\x01'), + (-512, True, b'\xfe\x00'), + (-513, True, b'\xfd\xff'), +]) +def test_int_to_bytes(n, signed, expected): + assert int_to_bytes(n, signed) == expected \ No newline at end of file