import importlib.util
from pathlib import Path
import struct
import unittest
import uuid

source = Path(__file__).with_name('prepare_uuid_probe.py')
spec = importlib.util.spec_from_file_location('uuid_probe', source)
probe = importlib.util.module_from_spec(spec)
spec.loader.exec_module(probe)


class ProbeParsingTests(unittest.TestCase):
    def test_entry_checksums_and_bounds(self):
        entry = bytearray(24)
        entry[:5] = b'_SM3_'
        entry[6:9] = bytes((24, 3, 6))
        struct.pack_into('<IQ', entry, 12, 4096, 0x12345000)
        entry[5] = -sum(entry) & 255
        self.assertEqual(probe.entry_info(entry, True), (0x12345000, 4096, (3, 6)))
        bad = bytearray(entry)
        bad[5] ^= 1
        with self.assertRaises(RuntimeError):
            probe.entry_info(bad, True)
        struct.pack_into('<I', entry, 12, 0x9001)
        entry[5] = 0
        entry[5] = -sum(entry) & 255
        with self.assertRaises(RuntimeError):
            probe.entry_info(entry, True)

    def test_uuid_table_and_malformed_structures(self):
        expected = uuid.UUID('03000200-0400-0500-0006-000700080009')
        bios = bytes((0, 4, 0, 0, 0, 0))
        system = bytes((1, 24, 1, 0, 0, 0, 0, 0)) + expected.bytes_le + b'\0\0'
        end = bytes((127, 4, 2, 0, 0, 0))
        self.assertEqual(probe.inspect_table(bios + system + end), (str(expected), 3))
        for bad in (bios + system, bios + system + system + end,
                    bios + system[:-1], bytes((1, 255, 0, 0))):
            with self.subTest(data=bad.hex()), self.assertRaises(RuntimeError):
                probe.inspect_table(bad)


if __name__ == '__main__':
    unittest.main()
