»Core Development>Code coverage>Lib/test/test_pprint.py

Python code coverage for Lib/test/test_pprint.py

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