|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +"""A :class:`~pcapkit.corekit.fields.misc.SchemaField`'s unread octets survive a rebuild. |
| 3 | +
|
| 4 | +GitHub issue #1380: a nested schema may read less than its |
| 5 | +:class:`~pcapkit.corekit.fields.misc.SchemaField`'s declared span. Parsing then |
| 6 | +packing kept the octets it left unread (#1292), but a schema rebuilt through |
| 7 | +:meth:`~pcapkit.protocols.schema.schema.Schema.from_dict`, or a protocol rebuilt |
| 8 | +through :meth:`~pcapkit.protocols.protocol.ProtocolBase.from_data`, had never |
| 9 | +been unpacked and zero-filled them. They now travel with the nested value as its |
| 10 | +``__remainder__``. |
| 11 | +
|
| 12 | +No shipped schema declares a :class:`~pcapkit.corekit.fields.misc.SchemaField` |
| 13 | +directly, so the schemas and the protocol here are built in the test. Everything |
| 14 | +from :mod:`pcapkit` is imported inside each test, after |
| 15 | +:func:`~tests._support.reimport_once_per_class`, not at module load. |
| 16 | +
|
| 17 | +""" |
| 18 | + |
| 19 | +import unittest |
| 20 | +import warnings |
| 21 | + |
| 22 | +from tests._support import reimport_once_per_class |
| 23 | + |
| 24 | +#: ``n`` = 3, a 3-octet span whose nested schema reads only ``02``, then ``tail``. |
| 25 | +RAW = bytes.fromhex('0302eeee04') |
| 26 | + |
| 27 | + |
| 28 | +def _nested_schemas(): # type: ignore[no-untyped-def] |
| 29 | + """An outer schema whose nested schema reads less than its span.""" |
| 30 | + from pcapkit.corekit.fields.misc import SchemaField |
| 31 | + from pcapkit.corekit.fields.numbers import UInt8Field |
| 32 | + from pcapkit.protocols.schema.schema import Schema, schema_final |
| 33 | + |
| 34 | + @schema_final |
| 35 | + class Inner(Schema): |
| 36 | + x: int = UInt8Field() |
| 37 | + |
| 38 | + @schema_final |
| 39 | + class Outer(Schema): |
| 40 | + n: int = UInt8Field() |
| 41 | + inner: Inner = SchemaField(length=lambda pkt: pkt['n'], schema=Inner) |
| 42 | + tail: int = UInt8Field() |
| 43 | + |
| 44 | + return Inner, Outer |
| 45 | + |
| 46 | + |
| 47 | +#: A 6-octet span whose nested schema reads ``k`` = 2 and ``aabb``, then ``tail``. |
| 48 | +SIZED_RAW = bytes.fromhex('02aabbccddee04') |
| 49 | + |
| 50 | + |
| 51 | +def _sized_schemas(): # type: ignore[no-untyped-def] |
| 52 | + """An outer schema whose nested schema's own width depends on its values.""" |
| 53 | + from pcapkit.corekit.fields.misc import SchemaField |
| 54 | + from pcapkit.corekit.fields.numbers import UInt8Field |
| 55 | + from pcapkit.corekit.fields.strings import BytesField |
| 56 | + from pcapkit.protocols.schema.schema import Schema, schema_final |
| 57 | + |
| 58 | + @schema_final |
| 59 | + class Inner(Schema): |
| 60 | + k: int = UInt8Field() |
| 61 | + body: bytes = BytesField(length=lambda pkt: pkt['k']) |
| 62 | + |
| 63 | + @schema_final |
| 64 | + class Outer(Schema): |
| 65 | + inner: Inner = SchemaField(length=6, schema=Inner) |
| 66 | + tail: int = UInt8Field() |
| 67 | + |
| 68 | + return Inner, Outer |
| 69 | + |
| 70 | + |
| 71 | +def _protocol(outer): # type: ignore[no-untyped-def] |
| 72 | + """A protocol over ``outer`` whose data model holds the nested schema's mapping.""" |
| 73 | + from pcapkit.corekit.infoclass import info_final |
| 74 | + from pcapkit.corekit.protochain import ProtoChain |
| 75 | + from pcapkit.protocols.data.data import Data |
| 76 | + from pcapkit.protocols.protocol import ProtocolBase |
| 77 | + |
| 78 | + @info_final |
| 79 | + class OuterData(Data): |
| 80 | + n: int |
| 81 | + inner: dict |
| 82 | + tail: int |
| 83 | + |
| 84 | + class OuterProtocol(ProtocolBase, schema=outer, data=OuterData): # type: ignore[call-arg,misc] |
| 85 | + __layer__ = 'Internet' |
| 86 | + |
| 87 | + @property |
| 88 | + def name(self): # type: ignore[no-untyped-def] |
| 89 | + return 'Outer' |
| 90 | + |
| 91 | + @property |
| 92 | + def length(self): # type: ignore[no-untyped-def] |
| 93 | + return len(self.__header__) |
| 94 | + |
| 95 | + def read(self, length=None, **kwargs): # type: ignore[no-untyped-def] |
| 96 | + from pcapkit.protocols.misc.null import NoPayload |
| 97 | + |
| 98 | + schema = self.__header__ |
| 99 | + self._next = NoPayload() |
| 100 | + self._protos = ProtoChain(type(self), self.alias, basis=self._next.protochain) |
| 101 | + # NOTE: A made header still holds the mapping ``make`` was given. |
| 102 | + inner = schema.inner if isinstance(schema.inner, dict) else schema.inner.to_dict() |
| 103 | + return OuterData(n=schema.n, inner=inner, tail=schema.tail) |
| 104 | + |
| 105 | + def make(self, n=0, inner=None, tail=0, **kwargs): # type: ignore[no-untyped-def] |
| 106 | + return outer(n=n, inner=inner, tail=tail) |
| 107 | + |
| 108 | + @classmethod |
| 109 | + def __index__(cls): # type: ignore[no-untyped-def,override] |
| 110 | + return 250 |
| 111 | + |
| 112 | + return OuterProtocol |
| 113 | + |
| 114 | + |
| 115 | +class TestSchemaFieldRemainder(unittest.TestCase): |
| 116 | + """Pin the unread octets of a nested schema through every rebuild.""" |
| 117 | + |
| 118 | + def setUp(self) -> None: |
| 119 | + reimport_once_per_class(self) |
| 120 | + |
| 121 | + def test_to_dict_carries_the_remainder(self) -> None: |
| 122 | + _, outer = _nested_schemas() |
| 123 | + |
| 124 | + parsed = outer.unpack(RAW, len(RAW), None) |
| 125 | + self.assertEqual(parsed.to_dict(), { |
| 126 | + 'n': 3, 'inner': {'x': 2, '__remainder__': b'\xee\xee', '__remainder_offset__': 1}, 'tail': 4, |
| 127 | + }) |
| 128 | + |
| 129 | + def test_from_dict_rebuilds_byte_exactly(self) -> None: |
| 130 | + _, outer = _nested_schemas() |
| 131 | + |
| 132 | + parsed = outer.unpack(RAW, len(RAW), None) |
| 133 | + with warnings.catch_warnings(): |
| 134 | + warnings.simplefilter('error') |
| 135 | + rebuilt = outer.from_dict(parsed.to_dict()) |
| 136 | + packed = rebuilt.pack() |
| 137 | + self.assertEqual(packed, RAW) |
| 138 | + |
| 139 | + def test_parsed_nested_schema_keeps_its_remainder(self) -> None: |
| 140 | + _, outer = _nested_schemas() |
| 141 | + |
| 142 | + parsed = outer.unpack(RAW, len(RAW), None) |
| 143 | + self.assertEqual(outer(n=3, inner=parsed.inner, tail=4).pack(), RAW) |
| 144 | + |
| 145 | + def test_remainder_is_not_a_field(self) -> None: |
| 146 | + _, outer = _nested_schemas() |
| 147 | + |
| 148 | + inner = outer.unpack(RAW, len(RAW), None).inner |
| 149 | + self.assertEqual(dict(inner), {'x': 2}) |
| 150 | + self.assertEqual(bytes(inner), b'\x02') |
| 151 | + with self.assertRaises(KeyError): |
| 152 | + inner['__remainder__'] # pylint: disable=pointless-statement,unsubscriptable-object |
| 153 | + |
| 154 | + def test_remainder_that_no_longer_fits_is_dropped(self) -> None: |
| 155 | + _, outer = _nested_schemas() |
| 156 | + |
| 157 | + data = outer.unpack(RAW, len(RAW), None).to_dict() |
| 158 | + data['n'] = 2 |
| 159 | + self.assertEqual(outer.from_dict(data).pack(), bytes.fromhex('02020004')) |
| 160 | + |
| 161 | + def test_shrunk_in_place_is_zero_filled(self) -> None: |
| 162 | + _, outer = _sized_schemas() |
| 163 | + |
| 164 | + parsed = outer.unpack(SIZED_RAW, len(SIZED_RAW), None) |
| 165 | + parsed.inner.body = b'\xaa' |
| 166 | + parsed.inner.k = 1 |
| 167 | + self.assertEqual(parsed.pack(), bytes.fromhex('01aa0000000004')) |
| 168 | + |
| 169 | + def test_shrunk_through_from_dict_is_zero_filled(self) -> None: |
| 170 | + _, outer = _sized_schemas() |
| 171 | + |
| 172 | + data = outer.unpack(SIZED_RAW, len(SIZED_RAW), None).to_dict() |
| 173 | + data['inner'].update(k=1, body=b'\xaa') |
| 174 | + self.assertEqual(outer.from_dict(data).pack(), bytes.fromhex('01aa0000000004')) |
| 175 | + |
| 176 | + def test_grown_through_from_dict_is_zero_filled(self) -> None: |
| 177 | + _, outer = _sized_schemas() |
| 178 | + |
| 179 | + data = outer.unpack(SIZED_RAW, len(SIZED_RAW), None).to_dict() |
| 180 | + data['inner'].update(k=4, body=b'\xaa\xbb\xcc\xdd') |
| 181 | + self.assertEqual(outer.from_dict(data).pack(), bytes.fromhex('04aabbccdd0004')) |
| 182 | + |
| 183 | + def test_sized_round_trips_byte_exactly(self) -> None: |
| 184 | + _, outer = _sized_schemas() |
| 185 | + |
| 186 | + parsed = outer.unpack(SIZED_RAW, len(SIZED_RAW), None) |
| 187 | + self.assertEqual(parsed.pack(), SIZED_RAW) |
| 188 | + self.assertEqual(outer.from_dict(parsed.to_dict()).pack(), SIZED_RAW) |
| 189 | + |
| 190 | + def test_no_remainder_without_unread_octets(self) -> None: |
| 191 | + _, outer = _nested_schemas() |
| 192 | + |
| 193 | + raw = bytes.fromhex('010204') |
| 194 | + parsed = outer.unpack(raw, len(raw), None) |
| 195 | + self.assertNotIn('__remainder__', parsed.to_dict()['inner']) |
| 196 | + self.assertEqual(outer.from_dict(parsed.to_dict()).pack(), raw) |
| 197 | + |
| 198 | + def test_protocol_from_data_rebuilds_byte_exactly(self) -> None: |
| 199 | + _, outer = _nested_schemas() |
| 200 | + protocol = _protocol(outer) |
| 201 | + |
| 202 | + parsed = protocol(RAW, len(RAW)) |
| 203 | + self.assertEqual(bytes(protocol.from_data(parsed.info)), RAW) |
| 204 | + self.assertEqual(bytes(protocol.from_data(parsed.info.to_dict())), RAW) |
| 205 | + |
| 206 | + |
| 207 | +if __name__ == '__main__': |
| 208 | + unittest.main() |
0 commit comments