読者です 読者をやめる 読者になる 読者になる

Python | python コードのテスト

unittest を使う

# utils.py
def to_hex(integer, length, byteorder, *, signed=False):
    b = integer.to_bytes(length, byteorder, signed=signed)
    lst = ['{:02X}'.format(x) for x in b]
    return ''.join(lst)


# test_to_hex.py
from unittest import TestCase, main
from utils import to_hex


class UtilsTestCase(TestCase):
    def test_to_hex_1byte(self):
        self.assertEqual('9C', to_hex(-100, 1, 'big', signed=True))

    def test_to_hex_2byte_little(self):
        self.assertEqual('18FC', to_hex(-1000, 2, 'little', signed=True))

    def test_to_hex_2byte_big(self):
        self.assertEqual('FC18', to_hex(-1000, 2, 'big', signed=True))

    def test_to_hex_1byte_unsigned(self):
        self.assertEqual('64', to_hex(100, 1, 'little'))

    def test_to_hex_2byte_unsigned_little(self):
        self.assertEqual('E803', to_hex(1000, 2, 'little'))

    def test_to_hex_2byte_unsigned_big(self):
        self.assertEqual('03E8', to_hex(1000, 2, 'big'))

    def test_to_hex_not_int(self):
        self.assertRaises(AttributeError,
                          to_hex, object(), 2, 'big', signed=True)

    def test_to_hex_overflow(self):
        self.assertRaises(OverflowError,
                          to_hex, -1000, 1, 'big', signed=True)

    def test_to_hex_overflow2(self):
        self.assertRaises(OverflowError,
                          to_hex, -1000, 2, 'big', signed=False)


if __name__ == '__main__':
    main()