bits/tests/test_bytes.py

178 lines
8.0 KiB
Python

from unittest import TestCase
from .context import Bytes
from .context import Bits, Bit
class TestBytes(TestCase):
def setUp(self):
from random import randint
from math import ceil
test_ints = [0]
test_str = ["0"]
test_bytes = [b'']
test_bytearray = []
test_list_of_Bits = []
test_list_of_Bit = []
test_list_of_bool = []
test_list_of_bytes = []
test_list_of_ints = []
test_list_of_str = []
for i in range(0, 100):
# Generate 100 random test cases, each with max_value between
# 9 and 9,999,999,999,999,999,999,999,999 (25 9's)
max_value = int("9" * randint(1, 25))
test_value = randint(1, max_value)
bitesize = ceil(test_value.bit_length() / 8)
pad_bits = "0" * ((bitesize * 8) - test_value.bit_length())
test_ints.append(test_value)
test_str.append(pad_bits + bin(test_value)[2:])
test_bytes.append(test_value.to_bytes(bitesize, "big"))
for bites in test_bytes:
list_of_Bits = []
list_of_Bit = []
list_of_bool = []
list_of_bytes = []
list_of_ints = []
list_of_str = []
for bite in bites:
list_of_Bits.append(Bits(bite))
list_of_bytes.append(bytes([bite]))
list_of_ints.append(bite)
list_of_str.append(Bits(bite).bin())
for bit in Bits(bite).bin():
list_of_Bit.append(Bit(bit))
list_of_bool.append(bool(Bit(bit)))
test_bytearray.append(bytearray(bites))
test_list_of_bytes.append(list_of_bytes)
test_list_of_Bits.append(list_of_Bits)
test_list_of_Bit.append(list_of_Bit)
test_list_of_ints.append(list_of_ints)
test_list_of_str.append(list_of_str)
self.testcases = {"int": test_ints,
"str": test_str,
"bytes": test_bytes,
"bytearray": test_bytearray,
"list of Bits": test_list_of_Bits,
"list of Bit": test_list_of_Bit,
"list of bool": test_list_of_bool,
"list of bytes": test_list_of_bytes,
"list of ints": test_list_of_ints,
"list of str": test_list_of_str}
def test_init(self):
"""
Test creation of Bytes object
"""
for title, tests in self.testcases.items():
with self.subTest(f"Create from {title}"):
# print("\tCreate Bytes from " + title)
for testcase in tests:
test = "Bytes(testcase)"
compare = f"Bytes"
#if not isinstance(testcase, int) and len(testcase) > 8:
# print(f"\t\t{testcase[0:9]}...")
#else:
# print(f"\t\t{testcase}")
try:
self.assertIsInstance(eval(test), eval(compare),
"{test} is instance of {compare}"
)
except:
import pdb
pdb.set_trace()
with self.subTest(f"Create from bits.Bytes"):
#print("\tCreate from Bytes object")
for testcase in self.testcases["int"]:
#print(f"\t\tBytes(Bytes({testcase}))")
test = "Bytes(Bytes(testcase))"
compare = f"Bytes"
self.assertIsInstance(eval(test), eval(compare),
f"{test} is instance of {compare}")
def test_errors(self):
with self.assertRaises(TypeError, msg="Bytes(\"1234\")"):
Bytes("1234")
def test_hex(self):
"""
Test conversion to hex string
"""
with self.subTest("Test Bytes.hex() using random values"):
for testcase in self.testcases["bytes"]:
self.assertEqual(Bytes(testcase).hex(), testcase.hex(),
f"Bytes({testcase}).hex() == {testcase}.hex()"
)
with self.subTest("Test hex() function with known values"):
self.assertEqual(Bytes(1234).hex(), "04d2",
f"Bytes(1234).hex() == '04d2'")
self.assertEqual(Bytes(1234).hex(":"), "04:d2",
f"Bytes(1234).hex(':') == '04:d2'")
self.assertEqual(Bytes(1234).hex(":", 1), "04:d2",
f"Bytes(1234).hex(':', 1) == '04:d2'")
with self.subTest("Advanced hex() test"):
testcase = b'UUDDLRLRAB'
self.assertEqual(Bytes(testcase).hex(), testcase.hex(),
f"Bytes({testcase}).hex() == {testcase}.hex()")
tests = [['55:55:44:44:4c:52:4c:52:41:42', ":", 1],
['55:55:44:44:4c:52:4c:52:41:42', ":", -1],
['5555:44444c52:4c524142', ":", 4],
['55554444:4c524c52:4142', ":", -4],
['55 - 55 - 44 - 44 - 4c - 52 - 4c - 52 - 41 - 42', " - ",
1],
['55, 55, 44, 44, 4c, 52, 4c, 52, 41, 42', ", ", 1],
['5555, 44444c52, 4c524142', ", ", 4],
['55554444, 4c524c52, 4142', ", ", -4]
]
for subt in tests:
self.assertEqual(Bytes(testcase).hex(sep=subt[1],
bytes_per_sep=subt[2]),
subt[0],
f"Bytes({testcase}).hex(sep='{subt[1]}', " +
f"bytes_per_sep={subt[2]}) == {subt[0]}")
def test_comparison_operators(self):
"""
Test the comparison operators with Bytes objects
"""
with self.subTest("Bytes Type"):
for i in range(0, len(self.testcases["int"])):
self.assertEqual(Bytes(self.testcases["int"][i]),
Bytes(self.testcases["bytes"][i]),
(f"Bytes({self.testcases['int'][i]}) == "
f"Bytes({self.testcases['bytes'][i]})"))
with self.subTest("int Type"):
self.assertEqual(Bytes(1234), 1234,
"Bytes(1234) == 1234")
self.assertNotEqual(Bytes(1234), 4321,
"Bytes(1234) != 4321")
self.assertEqual(5678, Bytes(5678),
"5678 == Bytes(5678)")
self.assertNotEqual(8765, Bytes(5678),
"8765 != Bytes(5678)")
self.assertLess(Bytes(123), 128,
"Bytes(123) < 128")
self.assertLessEqual(Bytes(124), 125,
"Bytes(124) <= 125")
self.assertLessEqual(Bytes(125), 125,
"Bytes(125) <= 125")
self.assertGreater(Bytes(255), 128,
"Bytes(255) > 128")
self.assertGreaterEqual(Bytes(256), 255,
"Bytes(256) >= 255")
self.assertGreaterEqual(Bytes(512), 512,
"Bytes(512) >= 512")
self.assertLess(123, Bytes(125),
"123 < Bytes(125)")
self.assertLessEqual(1024, Bytes(2048),
"1024 <= Bytes(2048)")
self.assertLessEqual(4092, Bytes(4092),
"4092 <= Bytes(4092)")
self.assertGreater(499, Bytes(200),
"499 > Bytes(200)")
self.assertGreaterEqual(322, Bytes(122),
"322 >= Bytes(122)")
self.assertGreaterEqual(510, Bytes(510),
"510 >= Bytes(510)")