|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import importlib.util |
| 4 | +import io |
| 5 | +import unittest |
| 6 | + |
| 7 | +from tests._support import reimport_once_per_class |
| 8 | + |
| 9 | +RUNTIME_DEPS = ('tbtrim', 'aenum', 'chardet', 'dictdumper') |
| 10 | +HAS_RUNTIME = all(importlib.util.find_spec(name) is not None for name in RUNTIME_DEPS) |
| 11 | + |
| 12 | + |
| 13 | +@unittest.skipUnless(HAS_RUNTIME, 'runtime dependencies not installed') |
| 14 | +class PCAPHeaderMagicProtosUnitTests(unittest.TestCase): |
| 15 | + """``Header._make_magic`` and ``Header._read_protos`` (GH-1096).""" |
| 16 | + |
| 17 | + def setUp(self) -> None: |
| 18 | + reimport_once_per_class(self) |
| 19 | + |
| 20 | + def test_make_magic_endian_flags_honour_nanosecond(self) -> None: |
| 21 | + from pcapkit.protocols.misc.pcap.header import Header |
| 22 | + |
| 23 | + header = object.__new__(Header) |
| 24 | + cases = [ |
| 25 | + ((True, False, False), (b'\xd4\xc3\xb2\xa1', True)), |
| 26 | + ((True, False, True), (b'\x4d\x3c\xb2\xa1', True)), |
| 27 | + ((False, True, False), (b'\xa1\xb2\xc3\xd4', False)), |
| 28 | + ((False, True, True), (b'\xa1\xb2\x3c\x4d', False)), |
| 29 | + ] |
| 30 | + for (lilendian, bigendian, nanosecond), expected in cases: |
| 31 | + with self.subTest(lilendian=lilendian, bigendian=bigendian, nanosecond=nanosecond): |
| 32 | + self.assertEqual(header._make_magic(lilendian=lilendian, bigendian=bigendian, |
| 33 | + nanosecond=nanosecond), expected) |
| 34 | + |
| 35 | + def test_make_magic_byteorder_matches_endian_flags(self) -> None: |
| 36 | + from pcapkit.protocols.misc.pcap.header import Header |
| 37 | + |
| 38 | + header = object.__new__(Header) |
| 39 | + for byteorder in ('little', 'big'): |
| 40 | + for nanosecond in (False, True): |
| 41 | + with self.subTest(byteorder=byteorder, nanosecond=nanosecond): |
| 42 | + self.assertEqual( |
| 43 | + header._make_magic(byteorder, nanosecond=nanosecond), |
| 44 | + header._make_magic(lilendian=byteorder == 'little', |
| 45 | + bigendian=byteorder == 'big', nanosecond=nanosecond), |
| 46 | + ) |
| 47 | + |
| 48 | + def test_read_protos_reads_size_bytes(self) -> None: |
| 49 | + from pcapkit.const.reg.linktype import LinkType |
| 50 | + from pcapkit.protocols.misc.pcap.header import Header |
| 51 | + |
| 52 | + header = object.__new__(Header) |
| 53 | + for size in (1, 2, 4): |
| 54 | + with self.subTest(size=size): |
| 55 | + header._file = io.BytesIO(int(LinkType.ETHERNET).to_bytes(size, 'little') + b'\xff' * 4) |
| 56 | + self.assertEqual(header._read_protos(size), LinkType.ETHERNET) |
| 57 | + self.assertEqual(header._file.tell(), size) |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == '__main__': |
| 61 | + unittest.main() |
0 commit comments