Skip to content

Commit 73ae662

Browse files
authored
Merge pull request #1147 from JarryShaw/fix/1126-frame-from-data
2 parents 4a43043 + f39c145 commit 73ae662

4 files changed

Lines changed: 115 additions & 20 deletions

File tree

‎pcapkit/protocols/misc/pcap/frame.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,12 @@ def _make_data(cls, data: 'Data_Frame') -> 'dict[str, Any]': # type: ignore[ove
463463
Returns:
464464
Key-value pairs for protocol construction.
465465
466+
Notes:
467+
The frame index and the global header are context of the PCAP file
468+
rather than fields of the frame, so they are not returned here: pass
469+
them to :meth:`~pcapkit.protocols.protocol.ProtocolBase.from_data` as
470+
``num`` and ``header``.
471+
466472
"""
467473
return {
468474
'ts_sec': data.frame_info.ts_sec,

‎pcapkit/protocols/protocol.py‎

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -246,10 +246,9 @@ def _check_construction_keywords(cls: 'type', kwargs: 'dict[str, Any]',
246246
# NOTE: A warning rather than an error, because nobody typed these: they are
247247
# whatever ``_make_data`` returned, so the defect is a key of that mapping
248248
# disagreeing with the signature it is spread into, and the person who meets
249-
# it cannot fix it. Raising would turn every such mismatch -- e.g. ``Frame``
250-
# returns ``ts_src`` for ``ts_sec`` and ``L2TPv2`` ``prio`` for ``priority``
251-
# -- into a broken ``from_data``, where the field is merely dropped; the
252-
# warning makes that audible instead.
249+
# it cannot fix it. Raising would turn every such mismatch into a broken
250+
# ``from_data``, where the field is merely dropped; the warning makes that
251+
# audible instead.
253252
#
254253
# No explicit ``stacklevel``: the default blames the innermost frame outside
255254
# :mod:`pcapkit`, which is the ``from_data`` call the reader wants to be
@@ -796,24 +795,42 @@ def from_schema(cls, schema: '_ST | dict[str, Any]') -> 'Self':
796795
return self
797796

798797
@classmethod
799-
def from_data(cls, data: '_PT | dict[str, Any]') -> 'Self':
798+
def from_data(cls, data: '_PT | dict[str, Any]', **kwargs: 'Any') -> 'Self':
800799
"""Create protocol instance from data.
801800
802801
Args:
803802
data: Protocol data.
803+
**kwargs: Construction keywords that ``data`` does not carry, such as
804+
the ``num`` and ``header`` of
805+
:class:`~pcapkit.protocols.misc.pcap.frame.Frame`, or the
806+
``num``, ``sct`` and ``ctx`` of
807+
:class:`~pcapkit.protocols.misc.pcapng.PCAPNG`. They take
808+
precedence over the keywords :meth:`_make_data` returns.
804809
805810
Returns:
806811
Protocol instance.
807812
813+
Raises:
814+
UnsupportedCall: If any of ``kwargs`` matches no parameter of the
815+
protocol, as for a direct construction.
816+
808817
"""
809818
if not isinstance(data, Data):
810819
data = cast('_PT', cls.__data__.from_dict(data))
811820

821+
# NOTE: The caller typed these, so they are checked strictly here, as a
822+
# direct construction would check them. The out-of-band keywords
823+
# ``__init__`` consumes are left out of it.
824+
_check_construction_keywords(cls, {
825+
key: val for key, val in kwargs.items()
826+
if key not in ('_layer', '_protocol', '__context__')
827+
})
828+
812829
self = cls.__new__(cls)
813-
kwargs = self._make_data(data)
830+
kwargs = {**self._make_data(data), **kwargs}
814831

815-
# NOTE: These keywords came out of ``_make_data``, not out of a caller, so
816-
# the construction keyword check of ``__init__`` warns here instead of
832+
# NOTE: The rest came out of ``_make_data``, not out of a caller, so the
833+
# construction keyword check of ``__init__`` warns here instead of
817834
# raising: a key of that mapping which disagrees with the signature it is
818835
# spread into is a defect in this protocol, and the caller of
819836
# ``from_data`` can do nothing about it. Set for the duration of the call
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
# -*- coding: utf-8 -*-
2+
"""``Frame.from_data`` rebuilds a captured frame.
3+
4+
GitHub issue #1126: :meth:`~pcapkit.protocols.protocol.ProtocolBase.from_data`
5+
took nothing but the data, so the ``num`` and ``header`` that
6+
:class:`~pcapkit.protocols.misc.pcap.frame.Frame` requires could not reach it,
7+
and every call raised :exc:`TypeError`. ``from_data`` now forwards extra
8+
keywords to the construction, so the caller passes both alongside the data.
9+
10+
The frames are read from :file:`examples/captures/in.pcap`, so this belongs to
11+
the runtime tier.
12+
13+
"""
14+
from __future__ import annotations
15+
16+
import importlib.util
17+
import os
18+
import unittest
19+
20+
from tests._support import reimport_once_per_class, sample_path
21+
22+
RUNTIME_DEPS = ('tbtrim', 'aenum', 'chardet', 'dictdumper')
23+
HAS_RUNTIME = all(importlib.util.find_spec(name) is not None for name in RUNTIME_DEPS)
24+
25+
26+
@unittest.skipUnless(HAS_RUNTIME, 'runtime dependencies not installed')
27+
class FrameFromDataRuntimeTests(unittest.TestCase):
28+
def setUp(self) -> None:
29+
reimport_once_per_class(self)
30+
31+
def test_from_data_round_trips_every_frame_byte_for_byte(self) -> None:
32+
from pcapkit.protocols.misc.pcap.frame import Frame
33+
from pcapkit.protocols.misc.pcap.header import Header
34+
35+
path = sample_path('in.pcap')
36+
size = os.path.getsize(path)
37+
with open(path, 'rb') as file:
38+
header = Header(file)
39+
num = 0
40+
while file.tell() < size:
41+
num += 1
42+
start = file.tell()
43+
frame = Frame(file, num=num, header=header.info)
44+
end = start + 16 + frame.info.frame_info.incl_len
45+
file.seek(start)
46+
octets = file.read(end - start)
47+
48+
with self.subTest(frame=num):
49+
rebuilt = Frame.from_data(frame.info, num=num, header=header.info)
50+
self.assertEqual(bytes(rebuilt), octets)
51+
self.assertEqual(rebuilt.info.number, num)
52+
53+
self.assertEqual(num, 6)
54+
55+
def test_from_data_keyword_overrides_make_data(self) -> None:
56+
from pcapkit.protocols.misc.pcap.frame import Frame
57+
from pcapkit.protocols.misc.pcap.header import Header
58+
59+
with open(sample_path('in.pcap'), 'rb') as file:
60+
header = Header(file)
61+
frame = Frame(file, num=1, header=header.info)
62+
63+
rebuilt = Frame.from_data(frame.info, num=1, header=header.info, ts_sec=42)
64+
self.assertEqual(rebuilt.info.frame_info.ts_sec, 42)
65+
66+
def test_from_data_rejects_a_misspelled_keyword(self) -> None:
67+
from pcapkit.protocols.misc.pcap.frame import Frame
68+
from pcapkit.protocols.misc.pcap.header import Header
69+
from pcapkit.utilities.exceptions import UnsupportedCall
70+
71+
with open(sample_path('in.pcap'), 'rb') as file:
72+
header = Header(file)
73+
frame = Frame(file, num=1, header=header.info)
74+
75+
with self.assertRaisesRegex(UnsupportedCall, "'heaedr'"):
76+
Frame.from_data(frame.info, num=1, heaedr=header.info)
77+
78+
79+
if __name__ == '__main__':
80+
unittest.main()

‎tests/protocols/test_make_data_keys_unit.py‎

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222
import io
2323
import unittest
2424
import warnings
25-
from unittest import mock
2625

2726
RUNTIME_DEPS = ('tbtrim', 'aenum', 'chardet', 'dictdumper')
2827
HAS_RUNTIME = all(importlib.util.find_spec(name) is not None for name in RUNTIME_DEPS)
@@ -62,18 +61,11 @@ def test_frame_ts_sec_survives_from_data(self) -> None:
6261
frame = Frame(num=1, header=header.info, ts_sec=1234, ts_usec=5,
6362
packet=b'\x00' * 14)
6463

65-
# NOTE: ``Frame`` also needs ``num`` and ``header``, which are not part
66-
# of its data, so wrap ``_make_data`` to supply them and still go
67-
# through the real :meth:`from_data` and the real keys.
68-
make_data = Frame._make_data
69-
70-
def with_context(cls: 'type', data: 'object') -> 'dict[str, object]':
71-
return {**make_data(data), 'num': 1, 'header': header.info}
72-
73-
with mock.patch.object(Frame, '_make_data', classmethod(with_context)), \
74-
warnings.catch_warnings(record=True) as caught:
64+
# NOTE: The frame index and the global header are not part of the
65+
# frame's data, so they are passed to :meth:`from_data` alongside it.
66+
with warnings.catch_warnings(record=True) as caught:
7567
warnings.simplefilter('always')
76-
rebuilt = Frame.from_data(frame.info)
68+
rebuilt = Frame.from_data(frame.info, num=1, header=header.info)
7769

7870
self.assertNoUnknownField(caught)
7971
self.assertEqual(rebuilt.info.frame_info.ts_sec, 1234)

0 commit comments

Comments
 (0)