|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +"""``make()`` resolves an enum member name given as :obj:`str`. |
| 3 | +
|
| 4 | +GitHub issue #1210: the ``make()`` signatures declare enum arguments as |
| 5 | +``Enum | StdlibEnum | AenumEnum | str | int``, but |
| 6 | +:meth:`~pcapkit.protocols.protocol.ProtocolBase._make_index` raised |
| 7 | +:exc:`~pcapkit.utilities.exceptions.ProtocolNotImplemented` for a :obj:`str` |
| 8 | +unless a ``*_namespace`` was passed. A member name now resolves against the |
| 9 | +enumeration class of the argument's default value, and builds the same bytes |
| 10 | +as the member itself and as its integer value. |
| 11 | +
|
| 12 | +Every case builds its own packet in memory and reads no capture. Classes are |
| 13 | +imported inside each test, after |
| 14 | +:func:`~tests._support.reimport_once_per_class`, so they belong to the live |
| 15 | +:mod:`pcapkit` import. |
| 16 | +
|
| 17 | +""" |
| 18 | + |
| 19 | +import importlib |
| 20 | +import unittest |
| 21 | +from typing import TYPE_CHECKING |
| 22 | + |
| 23 | +from tests._support import reimport_once_per_class |
| 24 | + |
| 25 | +if TYPE_CHECKING: |
| 26 | + from typing import Any |
| 27 | + |
| 28 | + |
| 29 | +def _attr(path: 'str') -> 'Any': |
| 30 | + module, _, name = path.rpartition('.') |
| 31 | + return getattr(importlib.import_module(module), name) |
| 32 | + |
| 33 | + |
| 34 | +def _tcp_alternate_checksum(**kwargs: 'Any') -> 'Any': |
| 35 | + option = _attr('pcapkit.const.tcp.option.Option') |
| 36 | + return _attr('pcapkit.protocols.transport.tcp.TCP')( |
| 37 | + options=[(option.TCP_Alternate_Checksum_Request, kwargs)], |
| 38 | + ) |
| 39 | + |
| 40 | + |
| 41 | +#: One ``make()`` per protocol family: |
| 42 | +#: (protocol class or builder, argument, enum class, non-default member). |
| 43 | +CASES = { |
| 44 | + 'link/ethernet': ('pcapkit.protocols.link.ethernet.Ethernet', 'type', |
| 45 | + 'pcapkit.const.reg.ethertype.EtherType', 'Internet_Protocol_version_6'), |
| 46 | + 'link/l2tpv2': ('pcapkit.protocols.link.l2tpv2.L2TPv2', 'type', |
| 47 | + 'pcapkit.const.l2tp.type.Type', 'Control'), |
| 48 | + 'internet/ipv4': ('pcapkit.protocols.internet.ipv4.IPv4', 'protocol', |
| 49 | + 'pcapkit.const.reg.transtype.TransType', 'TCP'), |
| 50 | + 'transport/tcp': (_tcp_alternate_checksum, 'algorithm', |
| 51 | + 'pcapkit.const.tcp.checksum.Checksum', 'Checksum_16_bit_Fletcher_s_algorithm'), |
| 52 | + 'application/ospf': ('pcapkit.protocols.application.ospf.OSPF', 'type', |
| 53 | + 'pcapkit.const.ospf.packet.Packet', 'Database_Description'), |
| 54 | + 'misc/pcap': ('pcapkit.protocols.misc.pcap.header.Header', 'network', |
| 55 | + 'pcapkit.const.reg.linktype.LinkType', 'RAW'), |
| 56 | +} |
| 57 | + |
| 58 | + |
| 59 | +class TestMakeIndexStr(unittest.TestCase): |
| 60 | + """Pin member-name resolution in ``_make_index`` across families.""" |
| 61 | + |
| 62 | + def setUp(self) -> None: |
| 63 | + reimport_once_per_class(self) |
| 64 | + |
| 65 | + def test_member_name_matches_member_and_int(self) -> None: |
| 66 | + for case, (maker, arg, enum_path, member) in CASES.items(): |
| 67 | + with self.subTest(case=case): |
| 68 | + build = _attr(maker) if isinstance(maker, str) else maker |
| 69 | + value = getattr(_attr(enum_path), member) |
| 70 | + |
| 71 | + expected = build(**{arg: value}).data |
| 72 | + self.assertEqual(build(**{arg: member}).data, expected) |
| 73 | + self.assertEqual(build(**{arg: int(value)}).data, expected) |
| 74 | + # the member is not the default, so the name was not ignored |
| 75 | + self.assertNotEqual(build().data, expected) |
| 76 | + |
| 77 | + def test_unknown_name_still_raises(self) -> None: |
| 78 | + exc = _attr('pcapkit.utilities.exceptions.ProtocolNotImplemented') |
| 79 | + ethernet = _attr('pcapkit.protocols.link.ethernet.Ethernet') |
| 80 | + with self.assertRaises(exc): |
| 81 | + ethernet(type='No_Such_EtherType') |
| 82 | + |
| 83 | + def test_unknown_name_falls_back_to_default(self) -> None: |
| 84 | + ethernet = _attr('pcapkit.protocols.link.ethernet.Ethernet') |
| 85 | + proto = ethernet(type='No_Such_EtherType', type_default=0x1234) |
| 86 | + self.assertEqual(proto.data[12:14], b'\x12\x34') |
| 87 | + |
| 88 | + def test_explicit_namespace_wins(self) -> None: |
| 89 | + ethernet = _attr('pcapkit.protocols.link.ethernet.Ethernet') |
| 90 | + # the name is also an EtherType member, but the namespace decides |
| 91 | + proto = ethernet(type='Internet_Protocol_version_6', |
| 92 | + type_namespace={'Internet_Protocol_version_6': 0x1234}, |
| 93 | + type_reversed=True) |
| 94 | + self.assertEqual(proto.data[12:14], b'\x12\x34') |
| 95 | + |
| 96 | + def test_shared_name_with_one_meaning_resolves(self) -> None: |
| 97 | + ipv4 = _attr('pcapkit.protocols.internet.ipv4.IPv4') |
| 98 | + tos_del = _attr('pcapkit.const.ipv4.tos_del.ToSDelay') |
| 99 | + tos_thr = _attr('pcapkit.const.ipv4.tos_thr.ToSThroughput') |
| 100 | + tos_rel = _attr('pcapkit.const.ipv4.tos_rel.ToSReliability') |
| 101 | + |
| 102 | + expected = ipv4(tos_del=tos_del.NORMAL, tos_thr=tos_thr.NORMAL).data |
| 103 | + self.assertEqual(ipv4(tos_del='NORMAL', tos_thr='NORMAL').data, expected) |
| 104 | + # an equal but distinct string object, so the match is not by identity |
| 105 | + self.assertEqual(ipv4(tos_del='NORMAL', tos_thr=''.join(['NOR', 'MAL'])).data, expected) |
| 106 | + |
| 107 | + expected = ipv4(tos_thr=tos_thr.HIGH, tos_rel=tos_rel.HIGH).data |
| 108 | + self.assertEqual(ipv4(tos_thr='HIGH', tos_rel='HIGH').data, expected) |
| 109 | + self.assertNotEqual(ipv4().data, expected) |
| 110 | + |
| 111 | + def test_shared_name_with_two_meanings_raises(self) -> None: |
| 112 | + enum = importlib.import_module('enum') |
| 113 | + exc = _attr('pcapkit.utilities.exceptions.ProtocolNotImplemented') |
| 114 | + protocol = _attr('pcapkit.protocols.protocol.ProtocolBase') |
| 115 | + |
| 116 | + left = enum.IntEnum('Left', {'Shared': 1}) |
| 117 | + right = enum.IntEnum('Right', {'Shared': 2}) |
| 118 | + |
| 119 | + class Pair(protocol): # type: ignore[misc,valid-type] |
| 120 | + def make_pair(self, a: 'Any' = left.Shared, a_namespace: 'Any' = None, |
| 121 | + b: 'Any' = right.Shared, b_namespace: 'Any' = None) -> 'int': |
| 122 | + return self._make_index(a, namespace=a_namespace) |
| 123 | + |
| 124 | + with self.assertRaisesRegex(exc, r"ambiguous member name 'Shared'.*" |
| 125 | + r"pass a_namespace= or b_namespace= explicitly"): |
| 126 | + Pair.make_pair(Pair, a='Shared', b='Shared') |
| 127 | + # an explicit namespace on the other argument removes the ambiguity |
| 128 | + self.assertEqual(Pair.make_pair(Pair, a='Shared', b='Shared', b_namespace=right), 1) |
| 129 | + |
| 130 | + # a real make(): ``LOW`` is a ToSDelay member but not a ToSThroughput one |
| 131 | + ipv4 = _attr('pcapkit.protocols.internet.ipv4.IPv4') |
| 132 | + with self.assertRaisesRegex(exc, r"ambiguous member name 'LOW'.*" |
| 133 | + r"pass tos_del_namespace= or tos_thr_namespace= explicitly"): |
| 134 | + ipv4(tos_del='LOW', tos_thr='LOW') |
| 135 | + |
| 136 | + def test_without_inferable_enum_still_raises(self) -> None: |
| 137 | + exc = _attr('pcapkit.utilities.exceptions.ProtocolNotImplemented') |
| 138 | + protocol = _attr('pcapkit.protocols.protocol.ProtocolBase') |
| 139 | + # called outside any ``make()``, so there is no argument to infer from |
| 140 | + with self.assertRaises(exc): |
| 141 | + protocol._make_index('Internet_Protocol_version_6') |
| 142 | + |
| 143 | + # ``status`` defaults to ``None``, so its enum cannot be inferred |
| 144 | + http = _attr('pcapkit.protocols.application.httpv1.HTTP') |
| 145 | + with self.assertRaises(exc): |
| 146 | + http(status='OK') |
| 147 | + |
| 148 | + |
| 149 | +if __name__ == '__main__': |
| 150 | + unittest.main() |
0 commit comments