Skip to content

Commit 29e82b0

Browse files
authored
fix(corekit): pass the copy to ListField callbacks and size SchemaField templates from it (#2173) (#2190)
1 parent 0d0783a commit 29e82b0

3 files changed

Lines changed: 77 additions & 2 deletions

File tree

‎pcapkit/corekit/fields/collections.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ def __call__(self, packet: 'dict[str, Any]') -> 'Self':
122122
123123
"""
124124
new_self = self.__copy__()
125-
new_self._callback(self, packet)
125+
new_self._callback(new_self, packet)
126126
if new_self._length_callback is not None:
127127
new_self._length = new_self._length_callback(packet)
128128
new_self._template = f'{new_self._length}s'

‎pcapkit/corekit/fields/misc.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -696,7 +696,7 @@ def __call__(self, packet: 'dict[str, Any]') -> 'Self':
696696
new_self._callback(new_self, packet)
697697
if new_self._length_callback is not None:
698698
new_self._length = new_self._length_callback(packet)
699-
new_self._template = f'{new_self._length}s' if self._length >= 0 else '1024s' # use a reasonable default
699+
new_self._template = f'{new_self._length}s' if new_self._length >= 0 else '1024s' # use a reasonable default
700700
return new_self
701701

702702
def pack(self, value: 'Optional[_TS | bytes]', packet: 'dict[str, Any]') -> 'bytes':
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# -*- coding: utf-8 -*-
2+
"""``ListField`` and ``SchemaField`` calls work on the copy, not the template.
3+
4+
GitHub issue #2173. Calling a field with a packet returns a fresh copy, which is
5+
what the schema then reads with. :meth:`ListField.__call__
6+
<pcapkit.corekit.fields.collections.ListField.__call__>` handed its ``callback``
7+
the template instead of that copy, so a callback adjusting its field mutated the
8+
template shared by every later packet and missed the copy actually in use.
9+
:meth:`SchemaField.__call__ <pcapkit.corekit.fields.misc.SchemaField.__call__>`
10+
sized the copy's ``template`` from the template's ``-1`` length rather than the
11+
copy's resolved one, so it stayed ``'1024s'``. Both read the copy.
12+
"""
13+
14+
import unittest
15+
from typing import TYPE_CHECKING
16+
17+
from pcapkit.corekit.fields.collections import ListField
18+
from pcapkit.corekit.fields.misc import SchemaField
19+
from pcapkit.corekit.fields.numbers import UInt8Field, UInt16Field
20+
from pcapkit.protocols.schema.schema import Schema
21+
22+
if TYPE_CHECKING:
23+
from typing import Any
24+
25+
26+
class Pair(Schema):
27+
"""Four-octet schema for :class:`SchemaField`."""
28+
29+
a: 'int' = UInt16Field()
30+
b: 'int' = UInt16Field()
31+
32+
33+
def tag_field(field: 'Any', packet: 'dict[str, Any]') -> 'None':
34+
"""Callback that adjusts the field it is given, as a byte-order one would."""
35+
field.tag = packet['n']
36+
37+
38+
class ListFieldCallbackTests(unittest.TestCase):
39+
"""``ListField.__call__`` passes its callback the copy."""
40+
41+
def test_callback_receives_the_copy(self) -> None:
42+
seen = [] # type: list[ListField]
43+
template = ListField(length=lambda pkt: pkt['n'], item_type=UInt8Field(),
44+
callback=lambda field, _: seen.append(field))
45+
copy = template({'n': 2})
46+
self.assertEqual(len(seen), 1)
47+
self.assertIs(seen[0], copy)
48+
self.assertIsNot(seen[0], template)
49+
50+
def test_template_is_untouched_across_calls(self) -> None:
51+
template = ListField(length=lambda pkt: pkt['n'], item_type=UInt8Field(), callback=tag_field)
52+
first = template({'n': 2})
53+
second = template({'n': 3})
54+
self.assertFalse(hasattr(template, 'tag'))
55+
self.assertEqual((first.tag, second.tag), (2, 3)) # type: ignore[attr-defined]
56+
self.assertEqual((first.length, second.length), (2, 3))
57+
58+
59+
class SchemaFieldTemplateTests(unittest.TestCase):
60+
"""``SchemaField.__call__`` sizes the copy's template from the copy's length."""
61+
62+
def test_callable_length_sizes_the_template(self) -> None:
63+
template = SchemaField(length=lambda pkt: pkt['n'], schema=Pair)
64+
copy = template({'n': 24})
65+
self.assertEqual(copy.length, 24)
66+
self.assertEqual(copy.template, '24s')
67+
self.assertEqual(template.template, '1024s')
68+
69+
def test_negative_resolved_length_keeps_the_default(self) -> None:
70+
copy = SchemaField(length=lambda pkt: pkt['n'], schema=Pair)({'n': -1})
71+
self.assertEqual(copy.template, '1024s')
72+
73+
74+
if __name__ == '__main__':
75+
unittest.main()

0 commit comments

Comments
 (0)