Skip to content

Commit a251f67

Browse files
authored
fix(dumpkit): tree output raises on complex and is undocumented as lossy (#1266) (#1366)
- make_dumper() overrides Tree._append_number to write a complex value as "-> (1+2j)", spelling NaN/Infinity as the writer does for a float; upstream math.isnan() raised TypeError on it. JSON and PLIST unchanged. - docs/source/pcapkit/dumpkit/index.rst: state that tree is a lossy, human-readable view and that json and plist are the round-trip formats. - tests/dumpkit/test_tree_lossy_unit.py pins both.
1 parent 75d28cd commit a251f67

3 files changed

Lines changed: 137 additions & 0 deletions

File tree

‎docs/source/pcapkit/dumpkit/index.rst‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,11 @@ hierarchy:
4848
click Dumper "/pcapkit/dumpkit/common.html#pcapkit.dumpkit.common.Dumper"
4949
click PCAPIO "/pcapkit/dumpkit/pcap.html#pcapkit.dumpkit.pcap.PCAPIO"
5050
click NotImplementedIO "/pcapkit/dumpkit/null.html#pcapkit.dumpkit.null.NotImplementedIO"
51+
52+
.. note::
53+
54+
The ``tree`` output (also selected as ``text`` and ``txt``) is a lossy,
55+
human-readable view, and nothing reads it back. It renders ``''``, ``b''``,
56+
:data:`None` and ``{}`` all as ``NIL``, and writes a newline inside a string
57+
as is, breaking the layout. Use ``json`` or ``plist`` (also selected as
58+
``xml``) where the report has to round-trip.

‎pcapkit/dumpkit/common.py‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import dictdumper.dumper
2626
import dictdumper.json
2727
import dictdumper.plist
28+
import dictdumper.tree
2829

2930
from pcapkit.corekit.infoclass import Info
3031
from pcapkit.corekit.multidict import MultiDict, OrderedMultiDict
@@ -306,6 +307,12 @@ def make_dumper(output: 'Type[ABCDumper]') -> 'Type[ABCDumper]':
306307
# report has (GitHub issue #1257). The defect is :mod:`dictdumper`'s, so it
307308
# is worked around here.
308309
keep_none = issubclass(output, dictdumper.plist.PLIST)
310+
# NOTE: :meth:`~dictdumper.tree.Tree._append_number` hands every number to
311+
# :func:`math.isnan`, which raises :exc:`TypeError` for a :class:`complex`
312+
# one, although :class:`~dictdumper.tree.Tree` routes :class:`complex` there
313+
# (GitHub issue #1266). The defect is :mod:`dictdumper`'s, so it is worked
314+
# around here.
315+
tree_numbers = issubclass(output, dictdumper.tree.Tree)
309316

310317
def escape_key(key: 'Any') -> 'Any':
311318
"""Escape a mapping key on its way to the writer.
@@ -510,6 +517,29 @@ def _append_string(self, value: 'str', file: 'TextIO') -> 'None':
510517
text.append(json.dumps(char)[1:-1] if ord(char) > 0xFFFF else f'\\u{ord(char):04x}')
511518
file.write('"' + ''.join(text) + '"')
512519

520+
if tree_numbers:
521+
def _append_number(self, value: 'int | float | complex', file: 'TextIO') -> 'None':
522+
"""Call this function to write number contents.
523+
524+
Args:
525+
self: Dumper instance.
526+
value: Content to be dumped.
527+
file: Output file.
528+
529+
Notes:
530+
A :class:`complex` value is written as ``-> (1+2j)``, with
531+
``NaN`` and ``Infinity`` spelt in either part as
532+
:meth:`dictdumper.tree.Tree._append_number` spells them for a
533+
:class:`float`; every other number is written by the
534+
upstream writer.
535+
536+
"""
537+
if not isinstance(value, complex):
538+
return super()._append_number(value, file)
539+
text = str(value).replace('nan', 'NaN').replace('inf', 'Infinity')
540+
file.write(f'-> {text}')
541+
return None
542+
513543
def default(self, o: 'Any') -> 'Literal["fallback"]': # pylint: disable=unused-argument
514544
"""Check content type for function call.
515545
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
# -*- coding: utf-8 -*-
2+
"""The ``tree`` dumper writes a :class:`complex` number instead of raising.
3+
4+
GitHub issue #1266: :meth:`dictdumper.tree.Tree._append_number` hands every
5+
number to :func:`math.isnan`, which raises ``TypeError: must be real number, not
6+
complex`` for the :class:`complex` values :class:`~dictdumper.tree.Tree` routes
7+
there. :func:`~pcapkit.dumpkit.common.make_dumper` now writes those itself, in
8+
the writer's own ``-> <number>`` style. ``json`` and ``plist`` are untouched:
9+
they already write a :class:`complex` as the string ``(1+2j)``.
10+
11+
:mod:`pcapkit` is imported inside each test, after
12+
:func:`~tests._support.reimport_once_per_class`, not at module load, so that the
13+
dumper is built from the import that is live for this class.
14+
15+
"""
16+
17+
import json
18+
import os
19+
import plistlib
20+
import tempfile
21+
import unittest
22+
23+
from tests._support import reimport_once_per_class
24+
25+
#: Name passed to every dumper call.
26+
NAME = 'x'
27+
28+
29+
class TestTreeComplexNumbers(unittest.TestCase):
30+
"""Pin how each writer renders a :class:`complex` value."""
31+
32+
def setUp(self) -> None:
33+
reimport_once_per_class(self)
34+
tmp = tempfile.TemporaryDirectory()
35+
self.addCleanup(tmp.cleanup)
36+
self.tmp = tmp.name
37+
38+
def dump(self, writer: str, value: object) -> str:
39+
"""Write ``value`` through ``make_dumper(dictdumper.<writer>)``."""
40+
import importlib
41+
42+
dictdumper = importlib.import_module('dictdumper')
43+
common = importlib.import_module('pcapkit.dumpkit.common')
44+
45+
path = os.path.join(self.tmp, f'{writer}.out')
46+
dumper = common.make_dumper(getattr(dictdumper, writer))(path)
47+
dumper(value, name=NAME)
48+
with open(path, encoding='utf-8') as file:
49+
return file.read()
50+
51+
def test_tree_writes_top_level_complex(self) -> None:
52+
self.assertEqual(self.dump('Tree', {'c': 1 + 2j}),
53+
f'{NAME}\n |-- c -> (1+2j)\n')
54+
55+
def test_tree_writes_nested_complex(self) -> None:
56+
text = self.dump('Tree', {'outer': {'inner': -0.5 - 3j}})
57+
self.assertIn('|-- inner -> (-0.5-3j)', text)
58+
59+
def test_tree_writes_complex_in_list(self) -> None:
60+
text = self.dump('Tree', {'items': [1, 2j, 1.5]})
61+
self.assertIn('-> 2j', text)
62+
self.assertIn('-> 1', text)
63+
self.assertIn('-> 1.5', text)
64+
65+
def test_tree_spells_non_finite_parts_as_for_float(self) -> None:
66+
text = self.dump('Tree', {'c': complex(float('inf'), float('nan')),
67+
'f': float('inf')})
68+
self.assertIn('|-- c -> (Infinity+NaNj)', text)
69+
self.assertIn('|-- f -> Infinity', text)
70+
71+
def test_tree_writes_real_numbers_as_upstream(self) -> None:
72+
self.assertEqual(self.dump('Tree', {'i': 1, 'f': 1.5, 'n': float('nan')}),
73+
f'{NAME}\n |-- i -> 1\n |-- f -> 1.5\n |-- n -> NaN\n')
74+
75+
def test_json_and_plist_keep_complex_as_string(self) -> None:
76+
value = {'c': 1 + 2j, 'outer': {'inner': 2j}, 'items': [2j]}
77+
expected = {NAME: {'c': '(1+2j)', 'outer': {'inner': '2j'}, 'items': ['2j']}}
78+
self.assertEqual(
79+
self.dump('JSON', value),
80+
'{\n\t"x": {\n\t\t"c": "(1+2j)",\n\t\t"outer": {\n\t\t\t"inner": "2j"\n'
81+
'\t\t},\n\t\t"items": [ "2j" ]\n\t}\n}',
82+
)
83+
self.assertEqual(json.loads(self.dump('JSON', value)), expected)
84+
self.assertEqual(plistlib.loads(self.dump('PLIST', value).encode('utf-8')), expected)
85+
86+
def test_only_tree_overrides_append_number(self) -> None:
87+
import importlib
88+
89+
dictdumper = importlib.import_module('dictdumper')
90+
common = importlib.import_module('pcapkit.dumpkit.common')
91+
92+
for writer in ('JSON', 'PLIST'):
93+
with self.subTest(writer=writer):
94+
upstream = getattr(dictdumper, writer)
95+
self.assertNotIn('_append_number', vars(common.make_dumper(upstream)))
96+
97+
98+
if __name__ == '__main__':
99+
unittest.main()

0 commit comments

Comments
 (0)