Debian Codegraph @

Lib/test/test_pprint.py

raw
1 # -*- coding: utf-8 -*-
2
3 import collections
4 import contextlib
5 import dataclasses
6 import io
7 import itertools
8 import pprint
9 import random
10 import re
11 import types
12 import unittest
13
14 from test.support import cpython_only
15 from test.support.import_helper import ensure_lazy_imports
16
17 # list, tuple and dict subclasses that do or don't overwrite __repr__
18 class list2(list):
19 pass
20
21 class list3(list):
22 def __repr__(self):
23 return list.__repr__(self)
24
25 class list_custom_repr(list):
26 def __repr__(self):
27 return '*'*len(list.__repr__(self))
28
29 class tuple2(tuple):
30 pass
31
32 class tuple3(tuple):
33 def __repr__(self):
34 return tuple.__repr__(self)
35
36 class tuple_custom_repr(tuple):
37 def __repr__(self):
38 return '*'*len(tuple.__repr__(self))
39
40 class set2(set):
41 pass
42
43 class set3(set):
44 def __repr__(self):
45 return set.__repr__(self)
46
47 class set_custom_repr(set):
48 def __repr__(self):
49 return '*'*len(set.__repr__(self))
50
51 class frozenset2(frozenset):
52 pass
53
54 class frozenset3(frozenset):
55 def __repr__(self):
56 return frozenset.__repr__(self)
57
58 class frozenset_custom_repr(frozenset):
59 def __repr__(self):
60 return '*'*len(frozenset.__repr__(self))
61
62 class dict2(dict):
63 pass
64
65 class dict3(dict):
66 def __repr__(self):
67 return dict.__repr__(self)
68
69 class dict_custom_repr(dict):
70 def __repr__(self):
71 return '*'*len(dict.__repr__(self))
72
73 @dataclasses.dataclass
74 class dataclass1:
75 field1: str
76 field2: int
77 field3: bool = False
78 field4: int = dataclasses.field(default=1, repr=False)
79
80 @dataclasses.dataclass
81 class dataclass2:
82 a: int = 1
83 def __repr__(self):
84 return "custom repr that doesn't fit within pprint width"
85
86 @dataclasses.dataclass(repr=False)
87 class dataclass3:
88 a: int = 1
89
90 @dataclasses.dataclass
91 class dataclass4:
92 a: "dataclass4"
93 b: int = 1
94
95 @dataclasses.dataclass
96 class dataclass5:
97 a: "dataclass6"
98 b: int = 1
99
100 @dataclasses.dataclass
101 class dataclass6:
102 c: "dataclass5"
103 d: int = 1
104
105 class Unorderable:
106 def __repr__(self):
107 return str(id(self))
108
109 # Class Orderable is orderable with any type
110 class Orderable:
111 def __init__(self, hash):
112 self._hash = hash
113 def __lt__(self, other):
114 return False
115 def __gt__(self, other):
116 return self != other
117 def __le__(self, other):
118 return self == other
119 def __ge__(self, other):
120 return True
121 def __eq__(self, other):
122 return self is other
123 def __ne__(self, other):
124 return self is not other
125 def __hash__(self):
126 return self._hash
127
128 class QueryTestCase(unittest.TestCase):
129
130 def setUp(self):
131 self.a = list(range(100))
132 self.b = list(range(200))
133 self.a[-12] = self.b
134
135 @cpython_only
136 def test_lazy_import(self):
137 ensure_lazy_imports("pprint", {"dataclasses", "re"})
138
139 def test_init(self):
140 pp = pprint.PrettyPrinter()
141 pp = pprint.PrettyPrinter(indent=4, width=40, depth=5,
142 stream=io.StringIO(), compact=True)
143 pp = pprint.PrettyPrinter(4, 40, 5, io.StringIO())
144 pp = pprint.PrettyPrinter(sort_dicts=False)
145 with self.assertRaises(TypeError):
146 pp = pprint.PrettyPrinter(4, 40, 5, io.StringIO(), True)
147 self.assertRaises(ValueError, pprint.PrettyPrinter, indent=-1)
148 self.assertRaises(ValueError, pprint.PrettyPrinter, depth=0)
149 self.assertRaises(ValueError, pprint.PrettyPrinter, depth=-1)
150 self.assertRaises(ValueError, pprint.PrettyPrinter, width=0)
151
152 def test_basic(self):
153 # Verify .isrecursive() and .isreadable() w/o recursion
154 pp = pprint.PrettyPrinter()
155 for safe in (2, 2.0, 2j, "abc", [3], (2,2), {3: 3}, b"def",
156 bytearray(b"ghi"), True, False, None, ...,
157 self.a, self.b):
158 # module-level convenience functions
159 self.assertFalse(pprint.isrecursive(safe),
160 "expected not isrecursive for %r" % (safe,))
161 self.assertTrue(pprint.isreadable(safe),
162 "expected isreadable for %r" % (safe,))
163 # PrettyPrinter methods
164 self.assertFalse(pp.isrecursive(safe),
165 "expected not isrecursive for %r" % (safe,))
166 self.assertTrue(pp.isreadable(safe),
167 "expected isreadable for %r" % (safe,))
168
169 def test_stdout_is_None(self):
170 with contextlib.redirect_stdout(None):
171 # smoke test - there is no output to check
172 value = 'this should not fail'
173 pprint.pprint(value)
174 pprint.PrettyPrinter().pprint(value)
175
176 def test_knotted(self):
177 # Verify .isrecursive() and .isreadable() w/ recursion
178 # Tie a knot.
179 self.b[67] = self.a
180 # Messy dict.
181 self.d = {}
182 self.d[0] = self.d[1] = self.d[2] = self.d
183
184 pp = pprint.PrettyPrinter()
185
186 for icky in self.a, self.b, self.d, (self.d, self.d):
187 self.assertTrue(pprint.isrecursive(icky), "expected isrecursive")
188 self.assertFalse(pprint.isreadable(icky), "expected not isreadable")
189 self.assertTrue(pp.isrecursive(icky), "expected isrecursive")
190 self.assertFalse(pp.isreadable(icky), "expected not isreadable")
191
192 # Break the cycles.
193 self.d.clear()
194 del self.a[:]
195 del self.b[:]
196
197 for safe in self.a, self.b, self.d, (self.d, self.d):
198 # module-level convenience functions
199 self.assertFalse(pprint.isrecursive(safe),
200 "expected not isrecursive for %r" % (safe,))
201 self.assertTrue(pprint.isreadable(safe),
202 "expected isreadable for %r" % (safe,))
203 # PrettyPrinter methods
204 self.assertFalse(pp.isrecursive(safe),
205 "expected not isrecursive for %r" % (safe,))
206 self.assertTrue(pp.isreadable(safe),
207 "expected isreadable for %r" % (safe,))
208
209 def test_unreadable(self):
210 # Not recursive but not readable anyway
211 pp = pprint.PrettyPrinter()
212 for unreadable in object(), int, pprint, pprint.isrecursive:
213 # module-level convenience functions
214 self.assertFalse(pprint.isrecursive(unreadable),
215 "expected not isrecursive for %r" % (unreadable,))
216 self.assertFalse(pprint.isreadable(unreadable),
217 "expected not isreadable for %r" % (unreadable,))
218 # PrettyPrinter methods
219 self.assertFalse(pp.isrecursive(unreadable),
220 "expected not isrecursive for %r" % (unreadable,))
221 self.assertFalse(pp.isreadable(unreadable),
222 "expected not isreadable for %r" % (unreadable,))
223
224 def test_same_as_repr(self):
225 # Simple objects, small containers and classes that override __repr__
226 # to directly call super's __repr__.
227 # For those the result should be the same as repr().
228 # Ahem. The docs don't say anything about that -- this appears to
229 # be testing an implementation quirk. Starting in Python 2.5, it's
230 # not true for dicts: pprint always sorts dicts by key now; before,
231 # it sorted a dict display if and only if the display required
232 # multiple lines. For that reason, dicts with more than one element
233 # aren't tested here.
234 for simple in (0, 0, 0+0j, 0.0, "", b"", bytearray(),
235 (), tuple2(), tuple3(),
236 [], list2(), list3(),
237 set(), set2(), set3(),
238 frozenset(), frozenset2(), frozenset3(),
239 {}, dict2(), dict3(),
240 self.assertTrue, pprint,
241 -6, -6, -6-6j, -1.5, "x", b"x", bytearray(b"x"),
242 (3,), [3], {3: 6},
243 (1,2), [3,4], {5: 6},
244 tuple2((1,2)), tuple3((1,2)), tuple3(range(100)),
245 [3,4], list2([3,4]), list3([3,4]), list3(range(100)),
246 set({7}), set2({7}), set3({7}),
247 frozenset({8}), frozenset2({8}), frozenset3({8}),
248 dict2({5: 6}), dict3({5: 6}),
249 range(10, -11, -1),
250 True, False, None, ...,
251 ):
252 native = repr(simple)
253 self.assertEqual(pprint.pformat(simple), native)
254 self.assertEqual(pprint.pformat(simple, width=1, indent=0)
255 .replace('\n', ' '), native)
256 self.assertEqual(pprint.pformat(simple, underscore_numbers=True), native)
257 self.assertEqual(pprint.saferepr(simple), native)
258
259 def test_container_repr_override_called(self):
260 N = 1000
261 # Ensure that __repr__ override is called for subclasses of containers
262
263 for cont in (list_custom_repr(),
264 list_custom_repr([1,2,3]),
265 list_custom_repr(range(N)),
266 tuple_custom_repr(),
267 tuple_custom_repr([1,2,3]),
268 tuple_custom_repr(range(N)),
269 set_custom_repr(),
270 set_custom_repr([1,2,3]),
271 set_custom_repr(range(N)),
272 frozenset_custom_repr(),
273 frozenset_custom_repr([1,2,3]),
274 frozenset_custom_repr(range(N)),
275 dict_custom_repr(),
276 dict_custom_repr({5: 6}),
277 dict_custom_repr(zip(range(N),range(N))),
278 ):
279 native = repr(cont)
280 expected = '*' * len(native)
281 self.assertEqual(pprint.pformat(cont), expected)
282 self.assertEqual(pprint.pformat(cont, width=1, indent=0), expected)
283 self.assertEqual(pprint.saferepr(cont), expected)
284
285 def test_basic_line_wrap(self):
286 # verify basic line-wrapping operation
287 o = {'RPM_cal': 0,
288 'RPM_cal2': 48059,
289 'Speed_cal': 0,
290 'controldesk_runtime_us': 0,
291 'main_code_runtime_us': 0,
292 'read_io_runtime_us': 0,
293 'write_io_runtime_us': 43690}
294 exp = """\
295 {'RPM_cal': 0,
296 'RPM_cal2': 48059,
297 'Speed_cal': 0,
298 'controldesk_runtime_us': 0,
299 'main_code_runtime_us': 0,
300 'read_io_runtime_us': 0,
301 'write_io_runtime_us': 43690}"""
302 for type in [dict, dict2]:
303 self.assertEqual(pprint.pformat(type(o)), exp)
304
305 o = range(100)
306 exp = '[%s]' % ',\n '.join(map(str, o))
307 for type in [list, list2]:
308 self.assertEqual(pprint.pformat(type(o)), exp)
309
310 o = tuple(range(100))
311 exp = '(%s)' % ',\n '.join(map(str, o))
312 for type in [tuple, tuple2]:
313 self.assertEqual(pprint.pformat(type(o)), exp)
314
315 # indent parameter
316 o = range(100)
317 exp = '[ %s]' % ',\n '.join(map(str, o))
318 for type in [list, list2]:
319 self.assertEqual(pprint.pformat(type(o), indent=4), exp)
320
321 def test_nested_indentations(self):
322 o1 = list(range(10))
323 o2 = dict(first=1, second=2, third=3)
324 o = [o1, o2]
325 expected = """\
326 [ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
327 {'first': 1, 'second': 2, 'third': 3}]"""
328 self.assertEqual(pprint.pformat(o, indent=4, width=42), expected)
329 expected = """\
330 [ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
331 { 'first': 1,
332 'second': 2,
333 'third': 3}]"""
334 self.assertEqual(pprint.pformat(o, indent=4, width=41), expected)
335
336 def test_width(self):
337 expected = """\
338 [[[[[[1, 2, 3],
339 '1 2']]]],
340 {1: [1, 2, 3],
341 2: [12, 34]},
342 'abc def ghi',
343 ('ab cd ef',),
344 set2({1, 23}),
345 [[[[[1, 2, 3],
346 '1 2']]]]]"""
347 o = eval(expected)
348 self.assertEqual(pprint.pformat(o, width=15), expected)
349 self.assertEqual(pprint.pformat(o, width=16), expected)
350 self.assertEqual(pprint.pformat(o, width=25), expected)
351 self.assertEqual(pprint.pformat(o, width=14), """\
352 [[[[[[1,
353 2,
354 3],
355 '1 '
356 '2']]]],
357 {1: [1,
358 2,
359 3],
360 2: [12,
361 34]},
362 'abc def '
363 'ghi',
364 ('ab cd '
365 'ef',),
366 set2({1,
367 23}),
368 [[[[[1,
369 2,
370 3],
371 '1 '
372 '2']]]]]""")
373
374 def test_integer(self):
375 self.assertEqual(pprint.pformat(1234567), '1234567')
376 self.assertEqual(pprint.pformat(1234567, underscore_numbers=True), '1_234_567')
377
378 class Temperature(int):
379 def __new__(cls, celsius_degrees):
380 return super().__new__(Temperature, celsius_degrees)
381 def __repr__(self):
382 kelvin_degrees = self + 273.15
383 return f"{kelvin_degrees:.2f}°K"
384 self.assertEqual(pprint.pformat(Temperature(1000)), '1273.15°K')
385
386 def test_sorted_dict(self):
387 # Starting in Python 2.5, pprint sorts dict displays by key regardless
388 # of how small the dictionary may be.
389 # Before the change, on 32-bit Windows pformat() gave order
390 # 'a', 'c', 'b' here, so this test failed.
391 d = {'a': 1, 'b': 1, 'c': 1}
392 self.assertEqual(pprint.pformat(d), "{'a': 1, 'b': 1, 'c': 1}")
393 self.assertEqual(pprint.pformat([d, d]),
394 "[{'a': 1, 'b': 1, 'c': 1}, {'a': 1, 'b': 1, 'c': 1}]")
395
396 # The next one is kind of goofy. The sorted order depends on the
397 # alphabetic order of type names: "int" < "str" < "tuple". Before
398 # Python 2.5, this was in the test_same_as_repr() test. It's worth
399 # keeping around for now because it's one of few tests of pprint
400 # against a crazy mix of types.
401 self.assertEqual(pprint.pformat({"xy\tab\n": (3,), 5: [[]], (): {}}),
402 r"{5: [[]], 'xy\tab\n': (3,), (): {}}")
403
404 def test_sort_dict(self):
405 d = dict.fromkeys('cba')
406 self.assertEqual(pprint.pformat(d, sort_dicts=False), "{'c': None, 'b': None, 'a': None}")
407 self.assertEqual(pprint.pformat([d, d], sort_dicts=False),
408 "[{'c': None, 'b': None, 'a': None}, {'c': None, 'b': None, 'a': None}]")
409
410 def test_ordered_dict(self):
411 d = collections.OrderedDict()
412 self.assertEqual(pprint.pformat(d, width=1), 'OrderedDict()')
413 d = collections.OrderedDict([])
414 self.assertEqual(pprint.pformat(d, width=1), 'OrderedDict()')
415 words = 'the quick brown fox jumped over a lazy dog'.split()
416 d = collections.OrderedDict(zip(words, itertools.count()))
417 self.assertEqual(pprint.pformat(d),
418 """\
419 OrderedDict([('the', 0),
420 ('quick', 1),
421 ('brown', 2),
422 ('fox', 3),
423 ('jumped', 4),
424 ('over', 5),
425 ('a', 6),
426 ('lazy', 7),
427 ('dog', 8)])""")
428
429 def test_mapping_proxy(self):
430 words = 'the quick brown fox jumped over a lazy dog'.split()
431 d = dict(zip(words, itertools.count()))
432 m = types.MappingProxyType(d)
433 self.assertEqual(pprint.pformat(m), """\
434 mappingproxy({'a': 6,
435 'brown': 2,
436 'dog': 8,
437 'fox': 3,
438 'jumped': 4,
439 'lazy': 7,
440 'over': 5,
441 'quick': 1,
442 'the': 0})""")
443 d = collections.OrderedDict(zip(words, itertools.count()))
444 m = types.MappingProxyType(d)
445 self.assertEqual(pprint.pformat(m), """\
446 mappingproxy(OrderedDict([('the', 0),
447 ('quick', 1),
448 ('brown', 2),
449 ('fox', 3),
450 ('jumped', 4),
451 ('over', 5),
452 ('a', 6),
453 ('lazy', 7),
454 ('dog', 8)]))""")
455
456 def test_empty_simple_namespace(self):
457 ns = types.SimpleNamespace()
458 formatted = pprint.pformat(ns)
459 self.assertEqual(formatted, "namespace()")
460
461 def test_small_simple_namespace(self):
462 ns = types.SimpleNamespace(a=1, b=2)
463 formatted = pprint.pformat(ns)
464 self.assertEqual(formatted, "namespace(a=1, b=2)")
465
466 def test_simple_namespace(self):
467 ns = types.SimpleNamespace(
468 the=0,
469 quick=1,
470 brown=2,
471 fox=3,
472 jumped=4,
473 over=5,
474 a=6,
475 lazy=7,
476 dog=8,
477 )
478 formatted = pprint.pformat(ns, width=60, indent=4)
479 self.assertEqual(formatted, """\
480 namespace(the=0,
481 quick=1,
482 brown=2,
483 fox=3,
484 jumped=4,
485 over=5,
486 a=6,
487 lazy=7,
488 dog=8)""")
489
490 def test_simple_namespace_subclass(self):
491 class AdvancedNamespace(types.SimpleNamespace): pass
492 ns = AdvancedNamespace(
493 the=0,
494 quick=1,
495 brown=2,
496 fox=3,
497 jumped=4,
498 over=5,
499 a=6,
500 lazy=7,
501 dog=8,
502 )
503 formatted = pprint.pformat(ns, width=60)
504 self.assertEqual(formatted, """\
505 AdvancedNamespace(the=0,
506 quick=1,
507 brown=2,
508 fox=3,
509 jumped=4,
510 over=5,
511 a=6,
512 lazy=7,
513 dog=8)""")
514
515 def test_empty_dataclass(self):
516 dc = dataclasses.make_dataclass("MyDataclass", ())()
517 formatted = pprint.pformat(dc)
518 self.assertEqual(formatted, "MyDataclass()")
519
520 def test_small_dataclass(self):
521 dc = dataclass1("text", 123)
522 formatted = pprint.pformat(dc)
523 self.assertEqual(formatted, "dataclass1(field1='text', field2=123, field3=False)")
524
525 def test_larger_dataclass(self):
526 dc = dataclass1("some fairly long text", int(1e10), True)
527 formatted = pprint.pformat([dc, dc], width=60, indent=4)
528 self.assertEqual(formatted, """\
529 [ dataclass1(field1='some fairly long text',
530 field2=10000000000,
531 field3=True),
532 dataclass1(field1='some fairly long text',
533 field2=10000000000,
534 field3=True)]""")
535
536 def test_dataclass_with_repr(self):
537 dc = dataclass2()
538 formatted = pprint.pformat(dc, width=20)
539 self.assertEqual(formatted, "custom repr that doesn't fit within pprint width")
540
541 def test_dataclass_no_repr(self):
542 dc = dataclass3()
543 formatted = pprint.pformat(dc, width=10)
544 self.assertRegex(
545 formatted,
546 fr"<{re.escape(__name__)}.dataclass3 object at \w+>",
547 )
548
549 def test_recursive_dataclass(self):
550 dc = dataclass4(None)
551 dc.a = dc
552 formatted = pprint.pformat(dc, width=10)
553 self.assertEqual(formatted, """\
554 dataclass4(a=...,
555 b=1)""")
556
557 def test_cyclic_dataclass(self):
558 dc5 = dataclass5(None)
559 dc6 = dataclass6(None)
560 dc5.a = dc6
561 dc6.c = dc5
562 formatted = pprint.pformat(dc5, width=10)
563 self.assertEqual(formatted, """\
564 dataclass5(a=dataclass6(c=...,
565 d=1),
566 b=1)""")
567
568 def test_subclassing(self):
569 # length(repr(obj)) > width
570 o = {'names with spaces': 'should be presented using repr()',
571 'others.should.not.be': 'like.this'}
572 exp = """\
573 {'names with spaces': 'should be presented using repr()',
574 others.should.not.be: like.this}"""
575
576 dotted_printer = DottedPrettyPrinter()
577 self.assertEqual(dotted_printer.pformat(o), exp)
578
579 # length(repr(obj)) < width
580 o1 = ['with space']
581 exp1 = "['with space']"
582 self.assertEqual(dotted_printer.pformat(o1), exp1)
583 o2 = ['without.space']
584 exp2 = "[without.space]"
585 self.assertEqual(dotted_printer.pformat(o2), exp2)
586
587 def test_set_reprs(self):
588 self.assertEqual(pprint.pformat(set()), 'set()')
589 self.assertEqual(pprint.pformat(set(range(3))), '{0, 1, 2}')
590 self.assertEqual(pprint.pformat(set(range(7)), width=20), '''\
591 {0,
592 1,
593 2,
594 3,
595 4,
596 5,
597 6}''')
598 self.assertEqual(pprint.pformat(set2(range(7)), width=20), '''\
599 set2({0,
600 1,
601 2,
602 3,
603 4,
604 5,
605 6})''')
606 self.assertEqual(pprint.pformat(set3(range(7)), width=20),
607 'set3({0, 1, 2, 3, 4, 5, 6})')
608
609 self.assertEqual(pprint.pformat(frozenset()), 'frozenset()')
610 self.assertEqual(pprint.pformat(frozenset(range(3))),
611 'frozenset({0, 1, 2})')
612 self.assertEqual(pprint.pformat(frozenset(range(7)), width=20), '''\
613 frozenset({0,
614 1,
615 2,
616 3,
617 4,
618 5,
619 6})''')
620 self.assertEqual(pprint.pformat(frozenset2(range(7)), width=20), '''\
621 frozenset2({0,
622 1,
623 2,
624 3,
625 4,
626 5,
627 6})''')
628 self.assertEqual(pprint.pformat(frozenset3(range(7)), width=20),
629 'frozenset3({0, 1, 2, 3, 4, 5, 6})')
630
631 def test_set_of_sets_reprs(self):
632 # This test creates a complex arrangement of frozensets and
633 # compares the pretty-printed repr against a string hard-coded in
634 # the test. The hard-coded repr depends on the sort order of
635 # frozensets.
636 #
637 # However, as the docs point out: "Since sets only define
638 # partial ordering (subset relationships), the output of the
639 # list.sort() method is undefined for lists of sets."
640 #
641 # >>> frozenset({0}) < frozenset({1})
642 # False
643 # >>> frozenset({1}) < frozenset({0})
644 # False
645 #
646 # In this test we list all possible invariants of the result
647 # for unordered frozensets.
648 #
649 # This test has a long history, see:
650 # - https://github.com/python/cpython/commit/969fe57baa0eb80332990f9cda936a33e13fabef
651 # - https://github.com/python/cpython/issues/58115
652 # - https://github.com/python/cpython/issues/111147
653
654 import textwrap
655
656 # Single-line, always ordered:
657 fs0 = frozenset()
658 fs1 = frozenset(('abc', 'xyz'))
659 data = frozenset((fs0, fs1))
660 self.assertEqual(pprint.pformat(data),
661 'frozenset({%r, %r})' % (fs0, fs1))
662 self.assertEqual(pprint.pformat(data), repr(data))
663
664 fs2 = frozenset(('one', 'two'))
665 data = {fs2: frozenset((fs0, fs1))}
666 self.assertEqual(pprint.pformat(data),
667 "{%r: frozenset({%r, %r})}" % (fs2, fs0, fs1))
668 self.assertEqual(pprint.pformat(data), repr(data))
669
670 # Single-line, unordered:
671 fs1 = frozenset(("xyz", "qwerty"))
672 fs2 = frozenset(("abcd", "spam"))
673 fs = frozenset((fs1, fs2))
674 self.assertEqual(pprint.pformat(fs), repr(fs))
675
676 # Multiline, unordered:
677 def check(res, invariants):
678 self.assertIn(res, [textwrap.dedent(i).strip() for i in invariants])
679
680 # Inner-most frozensets are singleline, result is multiline, unordered:
681 fs1 = frozenset(('regular string', 'other string'))
682 fs2 = frozenset(('third string', 'one more string'))
683 check(
684 pprint.pformat(frozenset((fs1, fs2))),
685 [
686 """
687 frozenset({%r,
688 %r})
689 """ % (fs1, fs2),
690 """
691 frozenset({%r,
692 %r})
693 """ % (fs2, fs1),
694 ],
695 )
696
697 # Everything is multiline, unordered:
698 check(
699 pprint.pformat(
700 frozenset((
701 frozenset((
702 "xyz very-very long string",
703 "qwerty is also absurdly long",
704 )),
705 frozenset((
706 "abcd is even longer that before",
707 "spam is not so long",
708 )),
709 )),
710 ),
711 [
712 """
713 frozenset({frozenset({'abcd is even longer that before',
714 'spam is not so long'}),
715 frozenset({'qwerty is also absurdly long',
716 'xyz very-very long string'})})
717 """,
718
719 """
720 frozenset({frozenset({'abcd is even longer that before',
721 'spam is not so long'}),
722 frozenset({'xyz very-very long string',
723 'qwerty is also absurdly long'})})
724 """,
725
726 """
727 frozenset({frozenset({'qwerty is also absurdly long',
728 'xyz very-very long string'}),
729 frozenset({'abcd is even longer that before',
730 'spam is not so long'})})
731 """,
732
733 """
734 frozenset({frozenset({'qwerty is also absurdly long',
735 'xyz very-very long string'}),
736 frozenset({'spam is not so long',
737 'abcd is even longer that before'})})
738 """,
739 ],
740 )
741
742 def test_depth(self):
743 nested_tuple = (1, (2, (3, (4, (5, 6)))))
744 nested_dict = {1: {2: {3: {4: {5: {6: 6}}}}}}
745 nested_list = [1, [2, [3, [4, [5, [6, []]]]]]]
746 self.assertEqual(pprint.pformat(nested_tuple), repr(nested_tuple))
747 self.assertEqual(pprint.pformat(nested_dict), repr(nested_dict))
748 self.assertEqual(pprint.pformat(nested_list), repr(nested_list))
749
750 lv1_tuple = '(1, (...))'
751 lv1_dict = '{1: {...}}'
752 lv1_list = '[1, [...]]'
753 self.assertEqual(pprint.pformat(nested_tuple, depth=1), lv1_tuple)
754 self.assertEqual(pprint.pformat(nested_dict, depth=1), lv1_dict)
755 self.assertEqual(pprint.pformat(nested_list, depth=1), lv1_list)
756
757 def test_sort_unorderable_values(self):
758 # Issue 3976: sorted pprints fail for unorderable values.
759 n = 20
760 keys = [Unorderable() for i in range(n)]
761 random.shuffle(keys)
762 skeys = sorted(keys, key=id)
763 clean = lambda s: s.replace(' ', '').replace('\n','')
764
765 self.assertEqual(clean(pprint.pformat(set(keys))),
766 '{' + ','.join(map(repr, skeys)) + '}')
767 self.assertEqual(clean(pprint.pformat(frozenset(keys))),
768 'frozenset({' + ','.join(map(repr, skeys)) + '})')
769 self.assertEqual(clean(pprint.pformat(dict.fromkeys(keys))),
770 '{' + ','.join('%r:None' % k for k in skeys) + '}')
771
772 # Issue 10017: TypeError on user-defined types as dict keys.
773 self.assertEqual(pprint.pformat({Unorderable: 0, 1: 0}),
774 '{1: 0, ' + repr(Unorderable) +': 0}')
775
776 # Issue 14998: TypeError on tuples with NoneTypes as dict keys.
777 keys = [(1,), (None,)]
778 self.assertEqual(pprint.pformat(dict.fromkeys(keys, 0)),
779 '{%r: 0, %r: 0}' % tuple(sorted(keys, key=id)))
780
781 def test_sort_orderable_and_unorderable_values(self):
782 # Issue 22721: sorted pprints is not stable
783 a = Unorderable()
784 b = Orderable(hash(a)) # should have the same hash value
785 # self-test
786 self.assertLess(a, b)
787 self.assertLess(str(type(b)), str(type(a)))
788 self.assertEqual(sorted([b, a]), [a, b])
789 self.assertEqual(sorted([a, b]), [a, b])
790 # set
791 self.assertEqual(pprint.pformat(set([b, a]), width=1),
792 '{%r,\n %r}' % (a, b))
793 self.assertEqual(pprint.pformat(set([a, b]), width=1),
794 '{%r,\n %r}' % (a, b))
795 # dict
796 self.assertEqual(pprint.pformat(dict.fromkeys([b, a]), width=1),
797 '{%r: None,\n %r: None}' % (a, b))
798 self.assertEqual(pprint.pformat(dict.fromkeys([a, b]), width=1),
799 '{%r: None,\n %r: None}' % (a, b))
800
801 def test_str_wrap(self):
802 # pprint tries to wrap strings intelligently
803 fox = 'the quick brown fox jumped over a lazy dog'
804 self.assertEqual(pprint.pformat(fox, width=19), """\
805 ('the quick brown '
806 'fox jumped over '
807 'a lazy dog')""")
808 self.assertEqual(pprint.pformat({'a': 1, 'b': fox, 'c': 2},
809 width=25), """\
810 {'a': 1,
811 'b': 'the quick brown '
812 'fox jumped over '
813 'a lazy dog',
814 'c': 2}""")
815 # With some special characters
816 # - \n always triggers a new line in the pprint
817 # - \t and \n are escaped
818 # - non-ASCII is allowed
819 # - an apostrophe doesn't disrupt the pprint
820 special = "Portons dix bons \"whiskys\"\nà l'avocat goujat\t qui fumait au zoo"
821 self.assertEqual(pprint.pformat(special, width=68), repr(special))
822 self.assertEqual(pprint.pformat(special, width=31), """\
823 ('Portons dix bons "whiskys"\\n'
824 "à l'avocat goujat\\t qui "
825 'fumait au zoo')""")
826 self.assertEqual(pprint.pformat(special, width=20), """\
827 ('Portons dix bons '
828 '"whiskys"\\n'
829 "à l'avocat "
830 'goujat\\t qui '
831 'fumait au zoo')""")
832 self.assertEqual(pprint.pformat([[[[[special]]]]], width=35), """\
833 [[[[['Portons dix bons "whiskys"\\n'
834 "à l'avocat goujat\\t qui "
835 'fumait au zoo']]]]]""")
836 self.assertEqual(pprint.pformat([[[[[special]]]]], width=25), """\
837 [[[[['Portons dix bons '
838 '"whiskys"\\n'
839 "à l'avocat "
840 'goujat\\t qui '
841 'fumait au zoo']]]]]""")
842 self.assertEqual(pprint.pformat([[[[[special]]]]], width=23), """\
843 [[[[['Portons dix '
844 'bons "whiskys"\\n'
845 "à l'avocat "
846 'goujat\\t qui '
847 'fumait au '
848 'zoo']]]]]""")
849 # An unwrappable string is formatted as its repr
850 unwrappable = "x" * 100
851 self.assertEqual(pprint.pformat(unwrappable, width=80), repr(unwrappable))
852 self.assertEqual(pprint.pformat(''), "''")
853 # Check that the pprint is a usable repr
854 special *= 10
855 for width in range(3, 40):
856 formatted = pprint.pformat(special, width=width)
857 self.assertEqual(eval(formatted), special)
858 formatted = pprint.pformat([special] * 2, width=width)
859 self.assertEqual(eval(formatted), [special] * 2)
860
861 def test_compact(self):
862 o = ([list(range(i * i)) for i in range(5)] +
863 [list(range(i)) for i in range(6)])
864 expected = """\
865 [[], [0], [0, 1, 2, 3],
866 [0, 1, 2, 3, 4, 5, 6, 7, 8],
867 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
868 14, 15],
869 [], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3],
870 [0, 1, 2, 3, 4]]"""
871 self.assertEqual(pprint.pformat(o, width=47, compact=True), expected)
872
873 def test_compact_width(self):
874 levels = 20
875 number = 10
876 o = [0] * number
877 for i in range(levels - 1):
878 o = [o]
879 for w in range(levels * 2 + 1, levels + 3 * number - 1):
880 lines = pprint.pformat(o, width=w, compact=True).splitlines()
881 maxwidth = max(map(len, lines))
882 self.assertLessEqual(maxwidth, w)
883 self.assertGreater(maxwidth, w - 3)
884
885 def test_bytes_wrap(self):
886 self.assertEqual(pprint.pformat(b'', width=1), "b''")
887 self.assertEqual(pprint.pformat(b'abcd', width=1), "b'abcd'")
888 letters = b'abcdefghijklmnopqrstuvwxyz'
889 self.assertEqual(pprint.pformat(letters, width=29), repr(letters))
890 self.assertEqual(pprint.pformat(letters, width=19), """\
891 (b'abcdefghijkl'
892 b'mnopqrstuvwxyz')""")
893 self.assertEqual(pprint.pformat(letters, width=18), """\
894 (b'abcdefghijkl'
895 b'mnopqrstuvwx'
896 b'yz')""")
897 self.assertEqual(pprint.pformat(letters, width=16), """\
898 (b'abcdefghijkl'
899 b'mnopqrstuvwx'
900 b'yz')""")
901 special = bytes(range(16))
902 self.assertEqual(pprint.pformat(special, width=61), repr(special))
903 self.assertEqual(pprint.pformat(special, width=48), """\
904 (b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'
905 b'\\x0c\\r\\x0e\\x0f')""")
906 self.assertEqual(pprint.pformat(special, width=32), """\
907 (b'\\x00\\x01\\x02\\x03'
908 b'\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'
909 b'\\x0c\\r\\x0e\\x0f')""")
910 self.assertEqual(pprint.pformat(special, width=1), """\
911 (b'\\x00\\x01\\x02\\x03'
912 b'\\x04\\x05\\x06\\x07'
913 b'\\x08\\t\\n\\x0b'
914 b'\\x0c\\r\\x0e\\x0f')""")
915 self.assertEqual(pprint.pformat({'a': 1, 'b': letters, 'c': 2},
916 width=21), """\
917 {'a': 1,
918 'b': b'abcdefghijkl'
919 b'mnopqrstuvwx'
920 b'yz',
921 'c': 2}""")
922 self.assertEqual(pprint.pformat({'a': 1, 'b': letters, 'c': 2},
923 width=20), """\
924 {'a': 1,
925 'b': b'abcdefgh'
926 b'ijklmnop'
927 b'qrstuvwxyz',
928 'c': 2}""")
929 self.assertEqual(pprint.pformat([[[[[[letters]]]]]], width=25), """\
930 [[[[[[b'abcdefghijklmnop'
931 b'qrstuvwxyz']]]]]]""")
932 self.assertEqual(pprint.pformat([[[[[[special]]]]]], width=41), """\
933 [[[[[[b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07'
934 b'\\x08\\t\\n\\x0b\\x0c\\r\\x0e\\x0f']]]]]]""")
935 # Check that the pprint is a usable repr
936 for width in range(1, 64):
937 formatted = pprint.pformat(special, width=width)
938 self.assertEqual(eval(formatted), special)
939 formatted = pprint.pformat([special] * 2, width=width)
940 self.assertEqual(eval(formatted), [special] * 2)
941
942 def test_bytearray_wrap(self):
943 self.assertEqual(pprint.pformat(bytearray(), width=1), "bytearray(b'')")
944 letters = bytearray(b'abcdefghijklmnopqrstuvwxyz')
945 self.assertEqual(pprint.pformat(letters, width=40), repr(letters))
946 self.assertEqual(pprint.pformat(letters, width=28), """\
947 bytearray(b'abcdefghijkl'
948 b'mnopqrstuvwxyz')""")
949 self.assertEqual(pprint.pformat(letters, width=27), """\
950 bytearray(b'abcdefghijkl'
951 b'mnopqrstuvwx'
952 b'yz')""")
953 self.assertEqual(pprint.pformat(letters, width=25), """\
954 bytearray(b'abcdefghijkl'
955 b'mnopqrstuvwx'
956 b'yz')""")
957 special = bytearray(range(16))
958 self.assertEqual(pprint.pformat(special, width=72), repr(special))
959 self.assertEqual(pprint.pformat(special, width=57), """\
960 bytearray(b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'
961 b'\\x0c\\r\\x0e\\x0f')""")
962 self.assertEqual(pprint.pformat(special, width=41), """\
963 bytearray(b'\\x00\\x01\\x02\\x03'
964 b'\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'
965 b'\\x0c\\r\\x0e\\x0f')""")
966 self.assertEqual(pprint.pformat(special, width=1), """\
967 bytearray(b'\\x00\\x01\\x02\\x03'
968 b'\\x04\\x05\\x06\\x07'
969 b'\\x08\\t\\n\\x0b'
970 b'\\x0c\\r\\x0e\\x0f')""")
971 self.assertEqual(pprint.pformat({'a': 1, 'b': letters, 'c': 2},
972 width=31), """\
973 {'a': 1,
974 'b': bytearray(b'abcdefghijkl'
975 b'mnopqrstuvwx'
976 b'yz'),
977 'c': 2}""")
978 self.assertEqual(pprint.pformat([[[[[letters]]]]], width=37), """\
979 [[[[[bytearray(b'abcdefghijklmnop'
980 b'qrstuvwxyz')]]]]]""")
981 self.assertEqual(pprint.pformat([[[[[special]]]]], width=50), """\
982 [[[[[bytearray(b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07'
983 b'\\x08\\t\\n\\x0b\\x0c\\r\\x0e\\x0f')]]]]]""")
984
985 def test_default_dict(self):
986 d = collections.defaultdict(int)
987 self.assertEqual(pprint.pformat(d, width=1), "defaultdict(<class 'int'>, {})")
988 words = 'the quick brown fox jumped over a lazy dog'.split()
989 d = collections.defaultdict(int, zip(words, itertools.count()))
990 self.assertEqual(pprint.pformat(d),
991 """\
992 defaultdict(<class 'int'>,
993 {'a': 6,
994 'brown': 2,
995 'dog': 8,
996 'fox': 3,
997 'jumped': 4,
998 'lazy': 7,
999 'over': 5,
1000 'quick': 1,
1001 'the': 0})""")
1002
1003 def test_counter(self):
1004 d = collections.Counter()
1005 self.assertEqual(pprint.pformat(d, width=1), "Counter()")
1006 d = collections.Counter('senselessness')
1007 self.assertEqual(pprint.pformat(d, width=40),
1008 """\
1009 Counter({'s': 6,
1010 'e': 4,
1011 'n': 2,
1012 'l': 1})""")
1013
1014 def test_chainmap(self):
1015 d = collections.ChainMap()
1016 self.assertEqual(pprint.pformat(d, width=1), "ChainMap({})")
1017 words = 'the quick brown fox jumped over a lazy dog'.split()
1018 items = list(zip(words, itertools.count()))
1019 d = collections.ChainMap(dict(items))
1020 self.assertEqual(pprint.pformat(d),
1021 """\
1022 ChainMap({'a': 6,
1023 'brown': 2,
1024 'dog': 8,
1025 'fox': 3,
1026 'jumped': 4,
1027 'lazy': 7,
1028 'over': 5,
1029 'quick': 1,
1030 'the': 0})""")
1031 d = collections.ChainMap(dict(items), collections.OrderedDict(items))
1032 self.assertEqual(pprint.pformat(d),
1033 """\
1034 ChainMap({'a': 6,
1035 'brown': 2,
1036 'dog': 8,
1037 'fox': 3,
1038 'jumped': 4,
1039 'lazy': 7,
1040 'over': 5,
1041 'quick': 1,
1042 'the': 0},
1043 OrderedDict([('the', 0),
1044 ('quick', 1),
1045 ('brown', 2),
1046 ('fox', 3),
1047 ('jumped', 4),
1048 ('over', 5),
1049 ('a', 6),
1050 ('lazy', 7),
1051 ('dog', 8)]))""")
1052
1053 def test_deque(self):
1054 d = collections.deque()
1055 self.assertEqual(pprint.pformat(d, width=1), "deque([])")
1056 d = collections.deque(maxlen=7)
1057 self.assertEqual(pprint.pformat(d, width=1), "deque([], maxlen=7)")
1058 words = 'the quick brown fox jumped over a lazy dog'.split()
1059 d = collections.deque(zip(words, itertools.count()))
1060 self.assertEqual(pprint.pformat(d),
1061 """\
1062 deque([('the', 0),
1063 ('quick', 1),
1064 ('brown', 2),
1065 ('fox', 3),
1066 ('jumped', 4),
1067 ('over', 5),
1068 ('a', 6),
1069 ('lazy', 7),
1070 ('dog', 8)])""")
1071 d = collections.deque(zip(words, itertools.count()), maxlen=7)
1072 self.assertEqual(pprint.pformat(d),
1073 """\
1074 deque([('brown', 2),
1075 ('fox', 3),
1076 ('jumped', 4),
1077 ('over', 5),
1078 ('a', 6),
1079 ('lazy', 7),
1080 ('dog', 8)],
1081 maxlen=7)""")
1082
1083 def test_user_dict(self):
1084 d = collections.UserDict()
1085 self.assertEqual(pprint.pformat(d, width=1), "{}")
1086 words = 'the quick brown fox jumped over a lazy dog'.split()
1087 d = collections.UserDict(zip(words, itertools.count()))
1088 self.assertEqual(pprint.pformat(d),
1089 """\
1090 {'a': 6,
1091 'brown': 2,
1092 'dog': 8,
1093 'fox': 3,
1094 'jumped': 4,
1095 'lazy': 7,
1096 'over': 5,
1097 'quick': 1,
1098 'the': 0}""")
1099
1100 def test_user_list(self):
1101 d = collections.UserList()
1102 self.assertEqual(pprint.pformat(d, width=1), "[]")
1103 words = 'the quick brown fox jumped over a lazy dog'.split()
1104 d = collections.UserList(zip(words, itertools.count()))
1105 self.assertEqual(pprint.pformat(d),
1106 """\
1107 [('the', 0),
1108 ('quick', 1),
1109 ('brown', 2),
1110 ('fox', 3),
1111 ('jumped', 4),
1112 ('over', 5),
1113 ('a', 6),
1114 ('lazy', 7),
1115 ('dog', 8)]""")
1116
1117 def test_user_string(self):
1118 d = collections.UserString('')
1119 self.assertEqual(pprint.pformat(d, width=1), "''")
1120 d = collections.UserString('the quick brown fox jumped over a lazy dog')
1121 self.assertEqual(pprint.pformat(d, width=20),
1122 """\
1123 ('the quick brown '
1124 'fox jumped over '
1125 'a lazy dog')""")
1126 self.assertEqual(pprint.pformat({1: d}, width=20),
1127 """\
1128 {1: 'the quick '
1129 'brown fox '
1130 'jumped over a '
1131 'lazy dog'}""")
1132
1133
1134 class DottedPrettyPrinter(pprint.PrettyPrinter):
1135
1136 def format(self, object, context, maxlevels, level):
1137 if isinstance(object, str):
1138 if ' ' in object:
1139 return repr(object), 1, 0
1140 else:
1141 return object, 0, 0
1142 else:
1143 return pprint.PrettyPrinter.format(
1144 self, object, context, maxlevels, level)
1145
1146
1147 if __name__ == "__main__":
1148 unittest.main()