blob: e5d2ac52d12836e679a080eeb0806618a95b9646 [file] [log] [blame]
Antoine Pitrou64c16c32013-03-23 20:30:39 +01001# -*- coding: utf-8 -*-
2
Raymond Hettingerbad3c882010-09-09 12:31:00 +00003import collections
Serhiy Storchakaf3fa3082015-03-26 08:43:21 +02004import io
Raymond Hettingerbad3c882010-09-09 12:31:00 +00005import itertools
Serhiy Storchakaf3fa3082015-03-26 08:43:21 +02006import pprint
7import random
8import test.support
9import test.test_set
Serhiy Storchaka87eb4822015-03-24 19:31:50 +020010import types
Serhiy Storchakaf3fa3082015-03-26 08:43:21 +020011import unittest
Tim Petersa814db52001-05-14 07:05:58 +000012
Walter Dörwald7a7ede52003-12-03 20:15:28 +000013# list, tuple and dict subclasses that do or don't overwrite __repr__
14class list2(list):
15 pass
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000016
Walter Dörwald7a7ede52003-12-03 20:15:28 +000017class list3(list):
18 def __repr__(self):
19 return list.__repr__(self)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000020
Irit Katriel582f1372020-08-30 18:29:53 +010021class list_custom_repr(list):
22 def __repr__(self):
23 return '*'*len(list.__repr__(self))
24
Walter Dörwald7a7ede52003-12-03 20:15:28 +000025class tuple2(tuple):
26 pass
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000027
Walter Dörwald7a7ede52003-12-03 20:15:28 +000028class tuple3(tuple):
29 def __repr__(self):
30 return tuple.__repr__(self)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000031
Irit Katriel582f1372020-08-30 18:29:53 +010032class tuple_custom_repr(tuple):
33 def __repr__(self):
34 return '*'*len(tuple.__repr__(self))
35
Serhiy Storchaka51844382013-10-02 11:40:49 +030036class set2(set):
37 pass
38
39class set3(set):
40 def __repr__(self):
41 return set.__repr__(self)
42
Irit Katriel582f1372020-08-30 18:29:53 +010043class set_custom_repr(set):
44 def __repr__(self):
45 return '*'*len(set.__repr__(self))
46
Serhiy Storchaka51844382013-10-02 11:40:49 +030047class frozenset2(frozenset):
48 pass
49
50class frozenset3(frozenset):
51 def __repr__(self):
52 return frozenset.__repr__(self)
53
Irit Katriel582f1372020-08-30 18:29:53 +010054class frozenset_custom_repr(frozenset):
55 def __repr__(self):
56 return '*'*len(frozenset.__repr__(self))
57
Walter Dörwald7a7ede52003-12-03 20:15:28 +000058class dict2(dict):
59 pass
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000060
Walter Dörwald7a7ede52003-12-03 20:15:28 +000061class dict3(dict):
62 def __repr__(self):
63 return dict.__repr__(self)
Tim Petersa814db52001-05-14 07:05:58 +000064
Irit Katriel582f1372020-08-30 18:29:53 +010065class dict_custom_repr(dict):
66 def __repr__(self):
67 return '*'*len(dict.__repr__(self))
68
Raymond Hettingera7da1662009-11-19 01:07:05 +000069class Unorderable:
70 def __repr__(self):
71 return str(id(self))
72
Serhiy Storchaka62aa7dc2015-04-06 22:52:44 +030073# Class Orderable is orderable with any type
74class Orderable:
75 def __init__(self, hash):
76 self._hash = hash
77 def __lt__(self, other):
78 return False
79 def __gt__(self, other):
80 return self != other
81 def __le__(self, other):
82 return self == other
83 def __ge__(self, other):
84 return True
85 def __eq__(self, other):
86 return self is other
87 def __ne__(self, other):
88 return self is not other
89 def __hash__(self):
90 return self._hash
91
Fred Drake43913dd2001-05-14 17:41:20 +000092class QueryTestCase(unittest.TestCase):
Tim Petersa814db52001-05-14 07:05:58 +000093
Fred Drake43913dd2001-05-14 17:41:20 +000094 def setUp(self):
Guido van Rossum805365e2007-05-07 22:24:25 +000095 self.a = list(range(100))
96 self.b = list(range(200))
Fred Drake43913dd2001-05-14 17:41:20 +000097 self.a[-12] = self.b
Tim Petersa814db52001-05-14 07:05:58 +000098
Serhiy Storchakaf3fa3082015-03-26 08:43:21 +020099 def test_init(self):
100 pp = pprint.PrettyPrinter()
101 pp = pprint.PrettyPrinter(indent=4, width=40, depth=5,
102 stream=io.StringIO(), compact=True)
103 pp = pprint.PrettyPrinter(4, 40, 5, io.StringIO())
Rémi Lapeyre96831c72019-03-22 18:22:20 +0100104 pp = pprint.PrettyPrinter(sort_dicts=False)
Serhiy Storchakaf3fa3082015-03-26 08:43:21 +0200105 with self.assertRaises(TypeError):
106 pp = pprint.PrettyPrinter(4, 40, 5, io.StringIO(), True)
107 self.assertRaises(ValueError, pprint.PrettyPrinter, indent=-1)
108 self.assertRaises(ValueError, pprint.PrettyPrinter, depth=0)
109 self.assertRaises(ValueError, pprint.PrettyPrinter, depth=-1)
110 self.assertRaises(ValueError, pprint.PrettyPrinter, width=0)
111
Fred Drake43913dd2001-05-14 17:41:20 +0000112 def test_basic(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000113 # Verify .isrecursive() and .isreadable() w/o recursion
Fred Drakeb456e4f2002-12-31 07:16:16 +0000114 pp = pprint.PrettyPrinter()
Serhiy Storchakacbfe07e2015-05-20 19:37:10 +0300115 for safe in (2, 2.0, 2j, "abc", [3], (2,2), {3: 3}, b"def",
116 bytearray(b"ghi"), True, False, None, ...,
Fred Drake43913dd2001-05-14 17:41:20 +0000117 self.a, self.b):
Fred Drakeb456e4f2002-12-31 07:16:16 +0000118 # module-level convenience functions
Ezio Melottib19f43d2010-01-24 20:59:24 +0000119 self.assertFalse(pprint.isrecursive(safe),
120 "expected not isrecursive for %r" % (safe,))
121 self.assertTrue(pprint.isreadable(safe),
122 "expected isreadable for %r" % (safe,))
Fred Drakeb456e4f2002-12-31 07:16:16 +0000123 # PrettyPrinter methods
Ezio Melottib19f43d2010-01-24 20:59:24 +0000124 self.assertFalse(pp.isrecursive(safe),
125 "expected not isrecursive for %r" % (safe,))
126 self.assertTrue(pp.isreadable(safe),
127 "expected isreadable for %r" % (safe,))
Tim Petersa814db52001-05-14 07:05:58 +0000128
Fred Drake43913dd2001-05-14 17:41:20 +0000129 def test_knotted(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000130 # Verify .isrecursive() and .isreadable() w/ recursion
Fred Drake43913dd2001-05-14 17:41:20 +0000131 # Tie a knot.
132 self.b[67] = self.a
133 # Messy dict.
134 self.d = {}
135 self.d[0] = self.d[1] = self.d[2] = self.d
Tim Petersa814db52001-05-14 07:05:58 +0000136
Fred Drakeb456e4f2002-12-31 07:16:16 +0000137 pp = pprint.PrettyPrinter()
Tim Petersa814db52001-05-14 07:05:58 +0000138
Fred Drake43913dd2001-05-14 17:41:20 +0000139 for icky in self.a, self.b, self.d, (self.d, self.d):
Ezio Melottib19f43d2010-01-24 20:59:24 +0000140 self.assertTrue(pprint.isrecursive(icky), "expected isrecursive")
141 self.assertFalse(pprint.isreadable(icky), "expected not isreadable")
142 self.assertTrue(pp.isrecursive(icky), "expected isrecursive")
143 self.assertFalse(pp.isreadable(icky), "expected not isreadable")
Fred Drake43913dd2001-05-14 17:41:20 +0000144
145 # Break the cycles.
146 self.d.clear()
147 del self.a[:]
148 del self.b[:]
149
150 for safe in self.a, self.b, self.d, (self.d, self.d):
Fred Drakeb456e4f2002-12-31 07:16:16 +0000151 # module-level convenience functions
Ezio Melottib19f43d2010-01-24 20:59:24 +0000152 self.assertFalse(pprint.isrecursive(safe),
153 "expected not isrecursive for %r" % (safe,))
154 self.assertTrue(pprint.isreadable(safe),
155 "expected isreadable for %r" % (safe,))
Fred Drakeb456e4f2002-12-31 07:16:16 +0000156 # PrettyPrinter methods
Ezio Melottib19f43d2010-01-24 20:59:24 +0000157 self.assertFalse(pp.isrecursive(safe),
158 "expected not isrecursive for %r" % (safe,))
159 self.assertTrue(pp.isreadable(safe),
160 "expected isreadable for %r" % (safe,))
Fred Drake43913dd2001-05-14 17:41:20 +0000161
162 def test_unreadable(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000163 # Not recursive but not readable anyway
Fred Drakeb456e4f2002-12-31 07:16:16 +0000164 pp = pprint.PrettyPrinter()
Fred Drake43913dd2001-05-14 17:41:20 +0000165 for unreadable in type(3), pprint, pprint.isrecursive:
Fred Drakeb456e4f2002-12-31 07:16:16 +0000166 # module-level convenience functions
Ezio Melottib19f43d2010-01-24 20:59:24 +0000167 self.assertFalse(pprint.isrecursive(unreadable),
168 "expected not isrecursive for %r" % (unreadable,))
169 self.assertFalse(pprint.isreadable(unreadable),
170 "expected not isreadable for %r" % (unreadable,))
Fred Drakeb456e4f2002-12-31 07:16:16 +0000171 # PrettyPrinter methods
Ezio Melottib19f43d2010-01-24 20:59:24 +0000172 self.assertFalse(pp.isrecursive(unreadable),
173 "expected not isrecursive for %r" % (unreadable,))
174 self.assertFalse(pp.isreadable(unreadable),
175 "expected not isreadable for %r" % (unreadable,))
Fred Drake43913dd2001-05-14 17:41:20 +0000176
Tim Peters95b3f782001-05-14 18:39:41 +0000177 def test_same_as_repr(self):
Irit Katriel582f1372020-08-30 18:29:53 +0100178 # Simple objects, small containers and classes that override __repr__
179 # to directly call super's __repr__.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000180 # For those the result should be the same as repr().
181 # Ahem. The docs don't say anything about that -- this appears to
182 # be testing an implementation quirk. Starting in Python 2.5, it's
183 # not true for dicts: pprint always sorts dicts by key now; before,
184 # it sorted a dict display if and only if the display required
185 # multiple lines. For that reason, dicts with more than one element
186 # aren't tested here.
Serhiy Storchakacbfe07e2015-05-20 19:37:10 +0300187 for simple in (0, 0, 0+0j, 0.0, "", b"", bytearray(),
Walter Dörwald7a7ede52003-12-03 20:15:28 +0000188 (), tuple2(), tuple3(),
189 [], list2(), list3(),
Serhiy Storchaka51844382013-10-02 11:40:49 +0300190 set(), set2(), set3(),
191 frozenset(), frozenset2(), frozenset3(),
Walter Dörwald7a7ede52003-12-03 20:15:28 +0000192 {}, dict2(), dict3(),
Ezio Melottib19f43d2010-01-24 20:59:24 +0000193 self.assertTrue, pprint,
Serhiy Storchakacbfe07e2015-05-20 19:37:10 +0300194 -6, -6, -6-6j, -1.5, "x", b"x", bytearray(b"x"),
195 (3,), [3], {3: 6},
Benjamin Petersond23f8222009-04-05 19:13:16 +0000196 (1,2), [3,4], {5: 6},
Walter Dörwald7a7ede52003-12-03 20:15:28 +0000197 tuple2((1,2)), tuple3((1,2)), tuple3(range(100)),
198 [3,4], list2([3,4]), list3([3,4]), list3(range(100)),
Serhiy Storchaka51844382013-10-02 11:40:49 +0300199 set({7}), set2({7}), set3({7}),
200 frozenset({8}), frozenset2({8}), frozenset3({8}),
Benjamin Petersond23f8222009-04-05 19:13:16 +0000201 dict2({5: 6}), dict3({5: 6}),
Serhiy Storchakacbfe07e2015-05-20 19:37:10 +0300202 range(10, -11, -1),
203 True, False, None, ...,
Tim Peters95b3f782001-05-14 18:39:41 +0000204 ):
205 native = repr(simple)
Serhiy Storchaka51844382013-10-02 11:40:49 +0300206 self.assertEqual(pprint.pformat(simple), native)
207 self.assertEqual(pprint.pformat(simple, width=1, indent=0)
208 .replace('\n', ' '), native)
sblondon3ba3d512021-03-24 09:23:20 +0100209 self.assertEqual(pprint.pformat(simple, underscore_numbers=True), native)
Serhiy Storchaka51844382013-10-02 11:40:49 +0300210 self.assertEqual(pprint.saferepr(simple), native)
Fred Drake43913dd2001-05-14 17:41:20 +0000211
Irit Katriel582f1372020-08-30 18:29:53 +0100212 def test_container_repr_override_called(self):
213 N = 1000
214 # Ensure that __repr__ override is called for subclasses of containers
215
216 for cont in (list_custom_repr(),
217 list_custom_repr([1,2,3]),
218 list_custom_repr(range(N)),
219 tuple_custom_repr(),
220 tuple_custom_repr([1,2,3]),
221 tuple_custom_repr(range(N)),
222 set_custom_repr(),
223 set_custom_repr([1,2,3]),
224 set_custom_repr(range(N)),
225 frozenset_custom_repr(),
226 frozenset_custom_repr([1,2,3]),
227 frozenset_custom_repr(range(N)),
228 dict_custom_repr(),
229 dict_custom_repr({5: 6}),
230 dict_custom_repr(zip(range(N),range(N))),
231 ):
232 native = repr(cont)
233 expected = '*' * len(native)
234 self.assertEqual(pprint.pformat(cont), expected)
235 self.assertEqual(pprint.pformat(cont, width=1, indent=0), expected)
236 self.assertEqual(pprint.saferepr(cont), expected)
237
Barry Warsaw00859c02001-11-28 05:49:39 +0000238 def test_basic_line_wrap(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000239 # verify basic line-wrapping operation
Barry Warsaw00859c02001-11-28 05:49:39 +0000240 o = {'RPM_cal': 0,
241 'RPM_cal2': 48059,
242 'Speed_cal': 0,
243 'controldesk_runtime_us': 0,
244 'main_code_runtime_us': 0,
245 'read_io_runtime_us': 0,
246 'write_io_runtime_us': 43690}
247 exp = """\
248{'RPM_cal': 0,
249 'RPM_cal2': 48059,
250 'Speed_cal': 0,
251 'controldesk_runtime_us': 0,
252 'main_code_runtime_us': 0,
253 'read_io_runtime_us': 0,
254 'write_io_runtime_us': 43690}"""
Walter Dörwald7a7ede52003-12-03 20:15:28 +0000255 for type in [dict, dict2]:
256 self.assertEqual(pprint.pformat(type(o)), exp)
257
258 o = range(100)
259 exp = '[%s]' % ',\n '.join(map(str, o))
260 for type in [list, list2]:
261 self.assertEqual(pprint.pformat(type(o)), exp)
262
263 o = tuple(range(100))
264 exp = '(%s)' % ',\n '.join(map(str, o))
265 for type in [tuple, tuple2]:
266 self.assertEqual(pprint.pformat(type(o)), exp)
Barry Warsaw00859c02001-11-28 05:49:39 +0000267
Walter Dörwaldc8de4582003-12-03 20:26:05 +0000268 # indent parameter
269 o = range(100)
270 exp = '[ %s]' % ',\n '.join(map(str, o))
271 for type in [list, list2]:
272 self.assertEqual(pprint.pformat(type(o), indent=4), exp)
273
Georg Brandl3ccb7872008-07-16 03:00:45 +0000274 def test_nested_indentations(self):
275 o1 = list(range(10))
276 o2 = dict(first=1, second=2, third=3)
277 o = [o1, o2]
278 expected = """\
279[ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200280 {'first': 1, 'second': 2, 'third': 3}]"""
281 self.assertEqual(pprint.pformat(o, indent=4, width=42), expected)
282 expected = """\
283[ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
Georg Brandl3ccb7872008-07-16 03:00:45 +0000284 { 'first': 1,
285 'second': 2,
286 'third': 3}]"""
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200287 self.assertEqual(pprint.pformat(o, indent=4, width=41), expected)
288
289 def test_width(self):
290 expected = """\
291[[[[[[1, 2, 3],
292 '1 2']]]],
293 {1: [1, 2, 3],
294 2: [12, 34]},
295 'abc def ghi',
296 ('ab cd ef',),
297 set2({1, 23}),
298 [[[[[1, 2, 3],
299 '1 2']]]]]"""
300 o = eval(expected)
301 self.assertEqual(pprint.pformat(o, width=15), expected)
302 self.assertEqual(pprint.pformat(o, width=16), expected)
303 self.assertEqual(pprint.pformat(o, width=25), expected)
304 self.assertEqual(pprint.pformat(o, width=14), """\
305[[[[[[1,
306 2,
307 3],
308 '1 '
309 '2']]]],
310 {1: [1,
311 2,
312 3],
313 2: [12,
314 34]},
315 'abc def '
316 'ghi',
317 ('ab cd '
318 'ef',),
319 set2({1,
320 23}),
321 [[[[[1,
322 2,
323 3],
324 '1 '
325 '2']]]]]""")
Georg Brandl3ccb7872008-07-16 03:00:45 +0000326
sblondon3ba3d512021-03-24 09:23:20 +0100327 def test_integer(self):
328 self.assertEqual(pprint.pformat(1234567), '1234567')
329 self.assertEqual(pprint.pformat(1234567, underscore_numbers=True), '1_234_567')
330
331 class Temperature(int):
332 def __new__(cls, celsius_degrees):
333 return super().__new__(Temperature, celsius_degrees)
334 def __repr__(self):
335 kelvin_degrees = self + 273.15
336 return f"{kelvin_degrees}°K"
337 self.assertEqual(pprint.pformat(Temperature(1000)), '1273.15°K')
338
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000339 def test_sorted_dict(self):
340 # Starting in Python 2.5, pprint sorts dict displays by key regardless
341 # of how small the dictionary may be.
342 # Before the change, on 32-bit Windows pformat() gave order
343 # 'a', 'c', 'b' here, so this test failed.
344 d = {'a': 1, 'b': 1, 'c': 1}
345 self.assertEqual(pprint.pformat(d), "{'a': 1, 'b': 1, 'c': 1}")
346 self.assertEqual(pprint.pformat([d, d]),
347 "[{'a': 1, 'b': 1, 'c': 1}, {'a': 1, 'b': 1, 'c': 1}]")
348
349 # The next one is kind of goofy. The sorted order depends on the
350 # alphabetic order of type names: "int" < "str" < "tuple". Before
351 # Python 2.5, this was in the test_same_as_repr() test. It's worth
352 # keeping around for now because it's one of few tests of pprint
353 # against a crazy mix of types.
354 self.assertEqual(pprint.pformat({"xy\tab\n": (3,), 5: [[]], (): {}}),
355 r"{5: [[]], 'xy\tab\n': (3,), (): {}}")
356
Rémi Lapeyre96831c72019-03-22 18:22:20 +0100357 def test_sort_dict(self):
358 d = dict.fromkeys('cba')
359 self.assertEqual(pprint.pformat(d, sort_dicts=False), "{'c': None, 'b': None, 'a': None}")
360 self.assertEqual(pprint.pformat([d, d], sort_dicts=False),
361 "[{'c': None, 'b': None, 'a': None}, {'c': None, 'b': None, 'a': None}]")
362
Raymond Hettingerbad3c882010-09-09 12:31:00 +0000363 def test_ordered_dict(self):
Serhiy Storchakaaa4c36f2015-03-26 08:51:33 +0200364 d = collections.OrderedDict()
365 self.assertEqual(pprint.pformat(d, width=1), 'OrderedDict()')
366 d = collections.OrderedDict([])
367 self.assertEqual(pprint.pformat(d, width=1), 'OrderedDict()')
Raymond Hettingerbad3c882010-09-09 12:31:00 +0000368 words = 'the quick brown fox jumped over a lazy dog'.split()
369 d = collections.OrderedDict(zip(words, itertools.count()))
370 self.assertEqual(pprint.pformat(d),
371"""\
Serhiy Storchakaaa4c36f2015-03-26 08:51:33 +0200372OrderedDict([('the', 0),
373 ('quick', 1),
374 ('brown', 2),
375 ('fox', 3),
376 ('jumped', 4),
377 ('over', 5),
378 ('a', 6),
379 ('lazy', 7),
380 ('dog', 8)])""")
Serhiy Storchaka87eb4822015-03-24 19:31:50 +0200381
382 def test_mapping_proxy(self):
383 words = 'the quick brown fox jumped over a lazy dog'.split()
384 d = dict(zip(words, itertools.count()))
385 m = types.MappingProxyType(d)
386 self.assertEqual(pprint.pformat(m), """\
387mappingproxy({'a': 6,
388 'brown': 2,
389 'dog': 8,
390 'fox': 3,
391 'jumped': 4,
392 'lazy': 7,
393 'over': 5,
394 'quick': 1,
395 'the': 0})""")
396 d = collections.OrderedDict(zip(words, itertools.count()))
397 m = types.MappingProxyType(d)
398 self.assertEqual(pprint.pformat(m), """\
Serhiy Storchakaaa4c36f2015-03-26 08:51:33 +0200399mappingproxy(OrderedDict([('the', 0),
400 ('quick', 1),
401 ('brown', 2),
402 ('fox', 3),
403 ('jumped', 4),
404 ('over', 5),
405 ('a', 6),
406 ('lazy', 7),
407 ('dog', 8)]))""")
Serhiy Storchaka87eb4822015-03-24 19:31:50 +0200408
Carl Bordum Hansen06a89162019-06-27 01:13:18 +0200409 def test_empty_simple_namespace(self):
410 ns = types.SimpleNamespace()
411 formatted = pprint.pformat(ns)
412 self.assertEqual(formatted, "namespace()")
413
414 def test_small_simple_namespace(self):
415 ns = types.SimpleNamespace(a=1, b=2)
416 formatted = pprint.pformat(ns)
417 self.assertEqual(formatted, "namespace(a=1, b=2)")
418
419 def test_simple_namespace(self):
420 ns = types.SimpleNamespace(
421 the=0,
422 quick=1,
423 brown=2,
424 fox=3,
425 jumped=4,
426 over=5,
427 a=6,
428 lazy=7,
429 dog=8,
430 )
431 formatted = pprint.pformat(ns, width=60)
432 self.assertEqual(formatted, """\
433namespace(the=0,
434 quick=1,
435 brown=2,
436 fox=3,
437 jumped=4,
438 over=5,
439 a=6,
440 lazy=7,
441 dog=8)""")
442
443 def test_simple_namespace_subclass(self):
444 class AdvancedNamespace(types.SimpleNamespace): pass
445 ns = AdvancedNamespace(
446 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 formatted = pprint.pformat(ns, width=60)
457 self.assertEqual(formatted, """\
458AdvancedNamespace(the=0,
459 quick=1,
460 brown=2,
461 fox=3,
462 jumped=4,
463 over=5,
464 a=6,
465 lazy=7,
466 dog=8)""")
467
Fred Drakeaee113d2002-04-02 05:08:35 +0000468 def test_subclassing(self):
Irit Katrielff420f02020-11-23 13:31:31 +0000469 # length(repr(obj)) > width
Fred Drakeaee113d2002-04-02 05:08:35 +0000470 o = {'names with spaces': 'should be presented using repr()',
471 'others.should.not.be': 'like.this'}
472 exp = """\
473{'names with spaces': 'should be presented using repr()',
474 others.should.not.be: like.this}"""
Irit Katrielff420f02020-11-23 13:31:31 +0000475
476 dotted_printer = DottedPrettyPrinter()
477 self.assertEqual(dotted_printer.pformat(o), exp)
478
479 # length(repr(obj)) < width
480 o1 = ['with space']
481 exp1 = "['with space']"
482 self.assertEqual(dotted_printer.pformat(o1), exp1)
483 o2 = ['without.space']
484 exp2 = "[without.space]"
485 self.assertEqual(dotted_printer.pformat(o2), exp2)
Fred Drakeaee113d2002-04-02 05:08:35 +0000486
Serhiy Storchaka51844382013-10-02 11:40:49 +0300487 def test_set_reprs(self):
488 self.assertEqual(pprint.pformat(set()), 'set()')
489 self.assertEqual(pprint.pformat(set(range(3))), '{0, 1, 2}')
490 self.assertEqual(pprint.pformat(set(range(7)), width=20), '''\
491{0,
492 1,
493 2,
494 3,
495 4,
496 5,
497 6}''')
498 self.assertEqual(pprint.pformat(set2(range(7)), width=20), '''\
499set2({0,
500 1,
501 2,
502 3,
503 4,
504 5,
505 6})''')
506 self.assertEqual(pprint.pformat(set3(range(7)), width=20),
507 'set3({0, 1, 2, 3, 4, 5, 6})')
508
509 self.assertEqual(pprint.pformat(frozenset()), 'frozenset()')
510 self.assertEqual(pprint.pformat(frozenset(range(3))),
511 'frozenset({0, 1, 2})')
512 self.assertEqual(pprint.pformat(frozenset(range(7)), width=20), '''\
513frozenset({0,
514 1,
515 2,
516 3,
517 4,
518 5,
519 6})''')
520 self.assertEqual(pprint.pformat(frozenset2(range(7)), width=20), '''\
521frozenset2({0,
522 1,
523 2,
524 3,
525 4,
526 5,
527 6})''')
528 self.assertEqual(pprint.pformat(frozenset3(range(7)), width=20),
529 'frozenset3({0, 1, 2, 3, 4, 5, 6})')
530
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400531 @unittest.expectedFailure
532 #See http://bugs.python.org/issue13907
Daniel Stutzbachc944cfc2010-09-21 21:08:09 +0000533 @test.support.cpython_only
Serhiy Storchaka51844382013-10-02 11:40:49 +0300534 def test_set_of_sets_reprs(self):
Daniel Stutzbachc944cfc2010-09-21 21:08:09 +0000535 # This test creates a complex arrangement of frozensets and
536 # compares the pretty-printed repr against a string hard-coded in
537 # the test. The hard-coded repr depends on the sort order of
538 # frozensets.
539 #
540 # However, as the docs point out: "Since sets only define
541 # partial ordering (subset relationships), the output of the
542 # list.sort() method is undefined for lists of sets."
543 #
544 # In a nutshell, the test assumes frozenset({0}) will always
545 # sort before frozenset({1}), but:
546 #
547 # >>> frozenset({0}) < frozenset({1})
548 # False
549 # >>> frozenset({1}) < frozenset({0})
550 # False
551 #
552 # Consequently, this test is fragile and
553 # implementation-dependent. Small changes to Python's sort
554 # algorithm cause the test to fail when it should pass.
Min ho Kimc4cacc82019-07-31 08:16:13 +1000555 # XXX Or changes to the dictionary implementation...
Daniel Stutzbachc944cfc2010-09-21 21:08:09 +0000556
Christian Heimes969fe572008-01-25 11:23:10 +0000557 cube_repr_tgt = """\
558{frozenset(): frozenset({frozenset({2}), frozenset({0}), frozenset({1})}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000559 frozenset({0}): frozenset({frozenset(),
Christian Heimes969fe572008-01-25 11:23:10 +0000560 frozenset({0, 2}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000561 frozenset({0, 1})}),
562 frozenset({1}): frozenset({frozenset(),
Christian Heimes969fe572008-01-25 11:23:10 +0000563 frozenset({1, 2}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000564 frozenset({0, 1})}),
565 frozenset({2}): frozenset({frozenset(),
Christian Heimes969fe572008-01-25 11:23:10 +0000566 frozenset({1, 2}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000567 frozenset({0, 2})}),
568 frozenset({1, 2}): frozenset({frozenset({2}),
Christian Heimes969fe572008-01-25 11:23:10 +0000569 frozenset({1}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000570 frozenset({0, 1, 2})}),
571 frozenset({0, 2}): frozenset({frozenset({2}),
Christian Heimes969fe572008-01-25 11:23:10 +0000572 frozenset({0}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000573 frozenset({0, 1, 2})}),
574 frozenset({0, 1}): frozenset({frozenset({0}),
Christian Heimes969fe572008-01-25 11:23:10 +0000575 frozenset({1}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000576 frozenset({0, 1, 2})}),
577 frozenset({0, 1, 2}): frozenset({frozenset({1, 2}),
Christian Heimes969fe572008-01-25 11:23:10 +0000578 frozenset({0, 2}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000579 frozenset({0, 1})})}"""
Christian Heimes969fe572008-01-25 11:23:10 +0000580 cube = test.test_set.cube(3)
581 self.assertEqual(pprint.pformat(cube), cube_repr_tgt)
582 cubo_repr_tgt = """\
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000583{frozenset({frozenset({0, 2}), frozenset({0})}): frozenset({frozenset({frozenset({0,
584 2}),
585 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000586 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000587 2})}),
588 frozenset({frozenset({0}),
589 frozenset({0,
590 1})}),
591 frozenset({frozenset(),
592 frozenset({0})}),
593 frozenset({frozenset({2}),
594 frozenset({0,
595 2})})}),
596 frozenset({frozenset({0, 1}), frozenset({1})}): frozenset({frozenset({frozenset({0,
597 1}),
598 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000599 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000600 2})}),
601 frozenset({frozenset({0}),
602 frozenset({0,
603 1})}),
604 frozenset({frozenset({1}),
605 frozenset({1,
606 2})}),
607 frozenset({frozenset(),
608 frozenset({1})})}),
609 frozenset({frozenset({1, 2}), frozenset({1})}): frozenset({frozenset({frozenset({1,
610 2}),
611 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000612 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000613 2})}),
614 frozenset({frozenset({2}),
615 frozenset({1,
616 2})}),
617 frozenset({frozenset(),
618 frozenset({1})}),
619 frozenset({frozenset({1}),
620 frozenset({0,
621 1})})}),
622 frozenset({frozenset({1, 2}), frozenset({2})}): frozenset({frozenset({frozenset({1,
623 2}),
624 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000625 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000626 2})}),
627 frozenset({frozenset({1}),
628 frozenset({1,
629 2})}),
630 frozenset({frozenset({2}),
631 frozenset({0,
632 2})}),
633 frozenset({frozenset(),
634 frozenset({2})})}),
635 frozenset({frozenset(), frozenset({0})}): frozenset({frozenset({frozenset({0}),
636 frozenset({0,
637 1})}),
638 frozenset({frozenset({0}),
639 frozenset({0,
640 2})}),
641 frozenset({frozenset(),
642 frozenset({1})}),
643 frozenset({frozenset(),
644 frozenset({2})})}),
645 frozenset({frozenset(), frozenset({1})}): frozenset({frozenset({frozenset(),
646 frozenset({0})}),
647 frozenset({frozenset({1}),
648 frozenset({1,
649 2})}),
650 frozenset({frozenset(),
651 frozenset({2})}),
652 frozenset({frozenset({1}),
653 frozenset({0,
654 1})})}),
655 frozenset({frozenset({2}), frozenset()}): frozenset({frozenset({frozenset({2}),
656 frozenset({1,
657 2})}),
658 frozenset({frozenset(),
659 frozenset({0})}),
660 frozenset({frozenset(),
661 frozenset({1})}),
662 frozenset({frozenset({2}),
663 frozenset({0,
664 2})})}),
665 frozenset({frozenset({0, 1, 2}), frozenset({0, 1})}): frozenset({frozenset({frozenset({1,
666 2}),
667 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000668 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000669 2})}),
670 frozenset({frozenset({0,
671 2}),
672 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000673 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000674 2})}),
675 frozenset({frozenset({0}),
676 frozenset({0,
677 1})}),
678 frozenset({frozenset({1}),
679 frozenset({0,
680 1})})}),
681 frozenset({frozenset({0}), frozenset({0, 1})}): frozenset({frozenset({frozenset(),
682 frozenset({0})}),
683 frozenset({frozenset({0,
684 1}),
685 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000686 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000687 2})}),
688 frozenset({frozenset({0}),
689 frozenset({0,
690 2})}),
691 frozenset({frozenset({1}),
692 frozenset({0,
693 1})})}),
694 frozenset({frozenset({2}), frozenset({0, 2})}): frozenset({frozenset({frozenset({0,
695 2}),
696 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000697 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000698 2})}),
699 frozenset({frozenset({2}),
700 frozenset({1,
701 2})}),
702 frozenset({frozenset({0}),
703 frozenset({0,
704 2})}),
705 frozenset({frozenset(),
706 frozenset({2})})}),
707 frozenset({frozenset({0, 1, 2}), frozenset({0, 2})}): frozenset({frozenset({frozenset({1,
708 2}),
709 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000710 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000711 2})}),
712 frozenset({frozenset({0,
713 1}),
714 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000715 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000716 2})}),
717 frozenset({frozenset({0}),
718 frozenset({0,
719 2})}),
720 frozenset({frozenset({2}),
721 frozenset({0,
722 2})})}),
723 frozenset({frozenset({1, 2}), frozenset({0, 1, 2})}): frozenset({frozenset({frozenset({0,
724 2}),
725 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000726 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000727 2})}),
728 frozenset({frozenset({0,
729 1}),
730 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000731 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000732 2})}),
733 frozenset({frozenset({2}),
734 frozenset({1,
735 2})}),
736 frozenset({frozenset({1}),
737 frozenset({1,
738 2})})})}"""
Christian Heimes969fe572008-01-25 11:23:10 +0000739
740 cubo = test.test_set.linegraph(cube)
741 self.assertEqual(pprint.pformat(cubo), cubo_repr_tgt)
742
Alexandre Vassalottieca20b62008-05-16 02:54:33 +0000743 def test_depth(self):
744 nested_tuple = (1, (2, (3, (4, (5, 6)))))
745 nested_dict = {1: {2: {3: {4: {5: {6: 6}}}}}}
746 nested_list = [1, [2, [3, [4, [5, [6, []]]]]]]
747 self.assertEqual(pprint.pformat(nested_tuple), repr(nested_tuple))
748 self.assertEqual(pprint.pformat(nested_dict), repr(nested_dict))
749 self.assertEqual(pprint.pformat(nested_list), repr(nested_list))
750
751 lv1_tuple = '(1, (...))'
752 lv1_dict = '{1: {...}}'
753 lv1_list = '[1, [...]]'
754 self.assertEqual(pprint.pformat(nested_tuple, depth=1), lv1_tuple)
755 self.assertEqual(pprint.pformat(nested_dict, depth=1), lv1_dict)
756 self.assertEqual(pprint.pformat(nested_list, depth=1), lv1_list)
757
Raymond Hettingera7da1662009-11-19 01:07:05 +0000758 def test_sort_unorderable_values(self):
759 # Issue 3976: sorted pprints fail for unorderable values.
760 n = 20
761 keys = [Unorderable() for i in range(n)]
762 random.shuffle(keys)
763 skeys = sorted(keys, key=id)
764 clean = lambda s: s.replace(' ', '').replace('\n','')
765
766 self.assertEqual(clean(pprint.pformat(set(keys))),
767 '{' + ','.join(map(repr, skeys)) + '}')
768 self.assertEqual(clean(pprint.pformat(frozenset(keys))),
769 'frozenset({' + ','.join(map(repr, skeys)) + '})')
770 self.assertEqual(clean(pprint.pformat(dict.fromkeys(keys))),
771 '{' + ','.join('%r:None' % k for k in skeys) + '}')
Fred Drakeaee113d2002-04-02 05:08:35 +0000772
Florent Xiclunad6da90f2012-07-21 11:17:38 +0200773 # Issue 10017: TypeError on user-defined types as dict keys.
774 self.assertEqual(pprint.pformat({Unorderable: 0, 1: 0}),
775 '{1: 0, ' + repr(Unorderable) +': 0}')
776
777 # Issue 14998: TypeError on tuples with NoneTypes as dict keys.
Florent Xicluna6e571d62012-07-21 12:44:20 +0200778 keys = [(1,), (None,)]
779 self.assertEqual(pprint.pformat(dict.fromkeys(keys, 0)),
780 '{%r: 0, %r: 0}' % tuple(sorted(keys, key=id)))
Florent Xiclunad6da90f2012-07-21 11:17:38 +0200781
Serhiy Storchaka62aa7dc2015-04-06 22:52:44 +0300782 def test_sort_orderable_and_unorderable_values(self):
783 # Issue 22721: sorted pprints is not stable
784 a = Unorderable()
785 b = Orderable(hash(a)) # should have the same hash value
786 # self-test
787 self.assertLess(a, b)
788 self.assertLess(str(type(b)), str(type(a)))
789 self.assertEqual(sorted([b, a]), [a, b])
790 self.assertEqual(sorted([a, b]), [a, b])
791 # set
792 self.assertEqual(pprint.pformat(set([b, a]), width=1),
793 '{%r,\n %r}' % (a, b))
794 self.assertEqual(pprint.pformat(set([a, b]), width=1),
795 '{%r,\n %r}' % (a, b))
796 # dict
797 self.assertEqual(pprint.pformat(dict.fromkeys([b, a]), width=1),
798 '{%r: None,\n %r: None}' % (a, b))
799 self.assertEqual(pprint.pformat(dict.fromkeys([a, b]), width=1),
800 '{%r: None,\n %r: None}' % (a, b))
801
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100802 def test_str_wrap(self):
803 # pprint tries to wrap strings intelligently
804 fox = 'the quick brown fox jumped over a lazy dog'
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200805 self.assertEqual(pprint.pformat(fox, width=19), """\
806('the quick brown '
807 'fox jumped over '
808 'a lazy dog')""")
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100809 self.assertEqual(pprint.pformat({'a': 1, 'b': fox, 'c': 2},
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200810 width=25), """\
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100811{'a': 1,
812 'b': 'the quick brown '
813 'fox jumped over '
814 'a lazy dog',
815 'c': 2}""")
816 # With some special characters
817 # - \n always triggers a new line in the pprint
818 # - \t and \n are escaped
819 # - non-ASCII is allowed
820 # - an apostrophe doesn't disrupt the pprint
821 special = "Portons dix bons \"whiskys\"\nà l'avocat goujat\t qui fumait au zoo"
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200822 self.assertEqual(pprint.pformat(special, width=68), repr(special))
823 self.assertEqual(pprint.pformat(special, width=31), """\
824('Portons dix bons "whiskys"\\n'
825 "à l'avocat goujat\\t qui "
826 'fumait au zoo')""")
827 self.assertEqual(pprint.pformat(special, width=20), """\
828('Portons dix bons '
829 '"whiskys"\\n'
Serhiy Storchakafe3dc372014-12-20 20:57:15 +0200830 "à l'avocat "
831 'goujat\\t qui '
832 'fumait au zoo')""")
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200833 self.assertEqual(pprint.pformat([[[[[special]]]]], width=35), """\
834[[[[['Portons dix bons "whiskys"\\n'
835 "à l'avocat goujat\\t qui "
836 'fumait au zoo']]]]]""")
837 self.assertEqual(pprint.pformat([[[[[special]]]]], width=25), """\
838[[[[['Portons dix bons '
839 '"whiskys"\\n'
840 "à l'avocat "
841 'goujat\\t qui '
842 'fumait au zoo']]]]]""")
843 self.assertEqual(pprint.pformat([[[[[special]]]]], width=23), """\
844[[[[['Portons dix '
845 'bons "whiskys"\\n'
846 "à l'avocat "
847 'goujat\\t qui '
848 'fumait au '
849 'zoo']]]]]""")
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100850 # An unwrappable string is formatted as its repr
851 unwrappable = "x" * 100
852 self.assertEqual(pprint.pformat(unwrappable, width=80), repr(unwrappable))
853 self.assertEqual(pprint.pformat(''), "''")
854 # Check that the pprint is a usable repr
855 special *= 10
856 for width in range(3, 40):
857 formatted = pprint.pformat(special, width=width)
Serhiy Storchakafe3dc372014-12-20 20:57:15 +0200858 self.assertEqual(eval(formatted), special)
859 formatted = pprint.pformat([special] * 2, width=width)
860 self.assertEqual(eval(formatted), [special] * 2)
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100861
Serhiy Storchaka7c411a42013-10-02 11:56:18 +0300862 def test_compact(self):
863 o = ([list(range(i * i)) for i in range(5)] +
864 [list(range(i)) for i in range(6)])
865 expected = """\
866[[], [0], [0, 1, 2, 3],
867 [0, 1, 2, 3, 4, 5, 6, 7, 8],
868 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
869 14, 15],
870 [], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3],
871 [0, 1, 2, 3, 4]]"""
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200872 self.assertEqual(pprint.pformat(o, width=47, compact=True), expected)
873
874 def test_compact_width(self):
875 levels = 20
876 number = 10
877 o = [0] * number
878 for i in range(levels - 1):
879 o = [o]
880 for w in range(levels * 2 + 1, levels + 3 * number - 1):
881 lines = pprint.pformat(o, width=w, compact=True).splitlines()
882 maxwidth = max(map(len, lines))
883 self.assertLessEqual(maxwidth, w)
884 self.assertGreater(maxwidth, w - 3)
Serhiy Storchaka7c411a42013-10-02 11:56:18 +0300885
Serhiy Storchaka022f2032015-03-24 19:22:37 +0200886 def test_bytes_wrap(self):
887 self.assertEqual(pprint.pformat(b'', width=1), "b''")
888 self.assertEqual(pprint.pformat(b'abcd', width=1), "b'abcd'")
889 letters = b'abcdefghijklmnopqrstuvwxyz'
890 self.assertEqual(pprint.pformat(letters, width=29), repr(letters))
891 self.assertEqual(pprint.pformat(letters, width=19), """\
892(b'abcdefghijkl'
893 b'mnopqrstuvwxyz')""")
894 self.assertEqual(pprint.pformat(letters, width=18), """\
895(b'abcdefghijkl'
896 b'mnopqrstuvwx'
897 b'yz')""")
898 self.assertEqual(pprint.pformat(letters, width=16), """\
899(b'abcdefghijkl'
900 b'mnopqrstuvwx'
901 b'yz')""")
902 special = bytes(range(16))
903 self.assertEqual(pprint.pformat(special, width=61), repr(special))
904 self.assertEqual(pprint.pformat(special, width=48), """\
905(b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'
906 b'\\x0c\\r\\x0e\\x0f')""")
907 self.assertEqual(pprint.pformat(special, width=32), """\
908(b'\\x00\\x01\\x02\\x03'
909 b'\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'
910 b'\\x0c\\r\\x0e\\x0f')""")
911 self.assertEqual(pprint.pformat(special, width=1), """\
912(b'\\x00\\x01\\x02\\x03'
913 b'\\x04\\x05\\x06\\x07'
914 b'\\x08\\t\\n\\x0b'
915 b'\\x0c\\r\\x0e\\x0f')""")
916 self.assertEqual(pprint.pformat({'a': 1, 'b': letters, 'c': 2},
917 width=21), """\
918{'a': 1,
919 'b': b'abcdefghijkl'
920 b'mnopqrstuvwx'
921 b'yz',
922 'c': 2}""")
923 self.assertEqual(pprint.pformat({'a': 1, 'b': letters, 'c': 2},
924 width=20), """\
925{'a': 1,
926 'b': b'abcdefgh'
927 b'ijklmnop'
928 b'qrstuvwxyz',
929 'c': 2}""")
930 self.assertEqual(pprint.pformat([[[[[[letters]]]]]], width=25), """\
931[[[[[[b'abcdefghijklmnop'
932 b'qrstuvwxyz']]]]]]""")
933 self.assertEqual(pprint.pformat([[[[[[special]]]]]], width=41), """\
934[[[[[[b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07'
935 b'\\x08\\t\\n\\x0b\\x0c\\r\\x0e\\x0f']]]]]]""")
936 # Check that the pprint is a usable repr
937 for width in range(1, 64):
938 formatted = pprint.pformat(special, width=width)
939 self.assertEqual(eval(formatted), special)
940 formatted = pprint.pformat([special] * 2, width=width)
941 self.assertEqual(eval(formatted), [special] * 2)
942
943 def test_bytearray_wrap(self):
944 self.assertEqual(pprint.pformat(bytearray(), width=1), "bytearray(b'')")
945 letters = bytearray(b'abcdefghijklmnopqrstuvwxyz')
946 self.assertEqual(pprint.pformat(letters, width=40), repr(letters))
947 self.assertEqual(pprint.pformat(letters, width=28), """\
948bytearray(b'abcdefghijkl'
949 b'mnopqrstuvwxyz')""")
950 self.assertEqual(pprint.pformat(letters, width=27), """\
951bytearray(b'abcdefghijkl'
952 b'mnopqrstuvwx'
953 b'yz')""")
954 self.assertEqual(pprint.pformat(letters, width=25), """\
955bytearray(b'abcdefghijkl'
956 b'mnopqrstuvwx'
957 b'yz')""")
958 special = bytearray(range(16))
959 self.assertEqual(pprint.pformat(special, width=72), repr(special))
960 self.assertEqual(pprint.pformat(special, width=57), """\
961bytearray(b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'
962 b'\\x0c\\r\\x0e\\x0f')""")
963 self.assertEqual(pprint.pformat(special, width=41), """\
964bytearray(b'\\x00\\x01\\x02\\x03'
965 b'\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'
966 b'\\x0c\\r\\x0e\\x0f')""")
967 self.assertEqual(pprint.pformat(special, width=1), """\
968bytearray(b'\\x00\\x01\\x02\\x03'
969 b'\\x04\\x05\\x06\\x07'
970 b'\\x08\\t\\n\\x0b'
971 b'\\x0c\\r\\x0e\\x0f')""")
972 self.assertEqual(pprint.pformat({'a': 1, 'b': letters, 'c': 2},
973 width=31), """\
974{'a': 1,
975 'b': bytearray(b'abcdefghijkl'
976 b'mnopqrstuvwx'
977 b'yz'),
978 'c': 2}""")
979 self.assertEqual(pprint.pformat([[[[[letters]]]]], width=37), """\
980[[[[[bytearray(b'abcdefghijklmnop'
981 b'qrstuvwxyz')]]]]]""")
982 self.assertEqual(pprint.pformat([[[[[special]]]]], width=50), """\
983[[[[[bytearray(b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07'
984 b'\\x08\\t\\n\\x0b\\x0c\\r\\x0e\\x0f')]]]]]""")
985
Serhiy Storchakabedbf962015-05-12 13:35:48 +0300986 def test_default_dict(self):
987 d = collections.defaultdict(int)
Benjamin Petersonab078e92016-07-13 21:13:29 -0700988 self.assertEqual(pprint.pformat(d, width=1), "defaultdict(<class 'int'>, {})")
Serhiy Storchakabedbf962015-05-12 13:35:48 +0300989 words = 'the quick brown fox jumped over a lazy dog'.split()
990 d = collections.defaultdict(int, zip(words, itertools.count()))
Benjamin Petersonab078e92016-07-13 21:13:29 -0700991 self.assertEqual(pprint.pformat(d),
992"""\
993defaultdict(<class 'int'>,
Serhiy Storchakabedbf962015-05-12 13:35:48 +0300994 {'a': 6,
995 'brown': 2,
996 'dog': 8,
997 'fox': 3,
998 'jumped': 4,
999 'lazy': 7,
1000 'over': 5,
1001 'quick': 1,
Benjamin Petersonab078e92016-07-13 21:13:29 -07001002 'the': 0})""")
Serhiy Storchakabedbf962015-05-12 13:35:48 +03001003
1004 def test_counter(self):
1005 d = collections.Counter()
1006 self.assertEqual(pprint.pformat(d, width=1), "Counter()")
1007 d = collections.Counter('senselessness')
1008 self.assertEqual(pprint.pformat(d, width=40),
1009"""\
1010Counter({'s': 6,
1011 'e': 4,
1012 'n': 2,
1013 'l': 1})""")
1014
1015 def test_chainmap(self):
1016 d = collections.ChainMap()
1017 self.assertEqual(pprint.pformat(d, width=1), "ChainMap({})")
1018 words = 'the quick brown fox jumped over a lazy dog'.split()
1019 items = list(zip(words, itertools.count()))
1020 d = collections.ChainMap(dict(items))
1021 self.assertEqual(pprint.pformat(d),
1022"""\
1023ChainMap({'a': 6,
1024 'brown': 2,
1025 'dog': 8,
1026 'fox': 3,
1027 'jumped': 4,
1028 'lazy': 7,
1029 'over': 5,
1030 'quick': 1,
1031 'the': 0})""")
1032 d = collections.ChainMap(dict(items), collections.OrderedDict(items))
1033 self.assertEqual(pprint.pformat(d),
1034"""\
1035ChainMap({'a': 6,
1036 'brown': 2,
1037 'dog': 8,
1038 'fox': 3,
1039 'jumped': 4,
1040 'lazy': 7,
1041 'over': 5,
1042 'quick': 1,
1043 'the': 0},
1044 OrderedDict([('the', 0),
1045 ('quick', 1),
1046 ('brown', 2),
1047 ('fox', 3),
1048 ('jumped', 4),
1049 ('over', 5),
1050 ('a', 6),
1051 ('lazy', 7),
1052 ('dog', 8)]))""")
1053
1054 def test_deque(self):
1055 d = collections.deque()
1056 self.assertEqual(pprint.pformat(d, width=1), "deque([])")
1057 d = collections.deque(maxlen=7)
1058 self.assertEqual(pprint.pformat(d, width=1), "deque([], maxlen=7)")
1059 words = 'the quick brown fox jumped over a lazy dog'.split()
1060 d = collections.deque(zip(words, itertools.count()))
1061 self.assertEqual(pprint.pformat(d),
1062"""\
1063deque([('the', 0),
1064 ('quick', 1),
1065 ('brown', 2),
1066 ('fox', 3),
1067 ('jumped', 4),
1068 ('over', 5),
1069 ('a', 6),
1070 ('lazy', 7),
1071 ('dog', 8)])""")
1072 d = collections.deque(zip(words, itertools.count()), maxlen=7)
1073 self.assertEqual(pprint.pformat(d),
1074"""\
1075deque([('brown', 2),
1076 ('fox', 3),
1077 ('jumped', 4),
1078 ('over', 5),
1079 ('a', 6),
1080 ('lazy', 7),
1081 ('dog', 8)],
1082 maxlen=7)""")
1083
1084 def test_user_dict(self):
1085 d = collections.UserDict()
1086 self.assertEqual(pprint.pformat(d, width=1), "{}")
1087 words = 'the quick brown fox jumped over a lazy dog'.split()
1088 d = collections.UserDict(zip(words, itertools.count()))
1089 self.assertEqual(pprint.pformat(d),
1090"""\
1091{'a': 6,
1092 'brown': 2,
1093 'dog': 8,
1094 'fox': 3,
1095 'jumped': 4,
1096 'lazy': 7,
1097 'over': 5,
1098 'quick': 1,
1099 'the': 0}""")
1100
Serhiy Storchaka265cee02015-10-29 09:52:20 +02001101 def test_user_list(self):
Serhiy Storchakabedbf962015-05-12 13:35:48 +03001102 d = collections.UserList()
1103 self.assertEqual(pprint.pformat(d, width=1), "[]")
1104 words = 'the quick brown fox jumped over a lazy dog'.split()
1105 d = collections.UserList(zip(words, itertools.count()))
1106 self.assertEqual(pprint.pformat(d),
1107"""\
1108[('the', 0),
1109 ('quick', 1),
1110 ('brown', 2),
1111 ('fox', 3),
1112 ('jumped', 4),
1113 ('over', 5),
1114 ('a', 6),
1115 ('lazy', 7),
1116 ('dog', 8)]""")
1117
1118 def test_user_string(self):
1119 d = collections.UserString('')
1120 self.assertEqual(pprint.pformat(d, width=1), "''")
1121 d = collections.UserString('the quick brown fox jumped over a lazy dog')
1122 self.assertEqual(pprint.pformat(d, width=20),
1123"""\
1124('the quick brown '
1125 'fox jumped over '
1126 'a lazy dog')""")
1127 self.assertEqual(pprint.pformat({1: d}, width=20),
1128"""\
1129{1: 'the quick '
1130 'brown fox '
1131 'jumped over a '
1132 'lazy dog'}""")
1133
Florent Xiclunad6da90f2012-07-21 11:17:38 +02001134
Fred Drakeaee113d2002-04-02 05:08:35 +00001135class DottedPrettyPrinter(pprint.PrettyPrinter):
Guido van Rossum32c2ae72002-08-22 19:45:32 +00001136
Fred Drakeaee113d2002-04-02 05:08:35 +00001137 def format(self, object, context, maxlevels, level):
1138 if isinstance(object, str):
1139 if ' ' in object:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001140 return repr(object), 1, 0
Fred Drakeaee113d2002-04-02 05:08:35 +00001141 else:
1142 return object, 0, 0
1143 else:
1144 return pprint.PrettyPrinter.format(
1145 self, object, context, maxlevels, level)
1146
1147
Fred Drake2e2be372001-09-20 21:33:42 +00001148if __name__ == "__main__":
Serhiy Storchakacbfe07e2015-05-20 19:37:10 +03001149 unittest.main()