blob: 8ee18e8fef84f7893f222a712a0b2696c4b93d9b [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)
209 self.assertEqual(pprint.saferepr(simple), native)
Fred Drake43913dd2001-05-14 17:41:20 +0000210
Irit Katriel582f1372020-08-30 18:29:53 +0100211 def test_container_repr_override_called(self):
212 N = 1000
213 # Ensure that __repr__ override is called for subclasses of containers
214
215 for cont in (list_custom_repr(),
216 list_custom_repr([1,2,3]),
217 list_custom_repr(range(N)),
218 tuple_custom_repr(),
219 tuple_custom_repr([1,2,3]),
220 tuple_custom_repr(range(N)),
221 set_custom_repr(),
222 set_custom_repr([1,2,3]),
223 set_custom_repr(range(N)),
224 frozenset_custom_repr(),
225 frozenset_custom_repr([1,2,3]),
226 frozenset_custom_repr(range(N)),
227 dict_custom_repr(),
228 dict_custom_repr({5: 6}),
229 dict_custom_repr(zip(range(N),range(N))),
230 ):
231 native = repr(cont)
232 expected = '*' * len(native)
233 self.assertEqual(pprint.pformat(cont), expected)
234 self.assertEqual(pprint.pformat(cont, width=1, indent=0), expected)
235 self.assertEqual(pprint.saferepr(cont), expected)
236
Barry Warsaw00859c02001-11-28 05:49:39 +0000237 def test_basic_line_wrap(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000238 # verify basic line-wrapping operation
Barry Warsaw00859c02001-11-28 05:49:39 +0000239 o = {'RPM_cal': 0,
240 'RPM_cal2': 48059,
241 'Speed_cal': 0,
242 'controldesk_runtime_us': 0,
243 'main_code_runtime_us': 0,
244 'read_io_runtime_us': 0,
245 'write_io_runtime_us': 43690}
246 exp = """\
247{'RPM_cal': 0,
248 'RPM_cal2': 48059,
249 'Speed_cal': 0,
250 'controldesk_runtime_us': 0,
251 'main_code_runtime_us': 0,
252 'read_io_runtime_us': 0,
253 'write_io_runtime_us': 43690}"""
Walter Dörwald7a7ede52003-12-03 20:15:28 +0000254 for type in [dict, dict2]:
255 self.assertEqual(pprint.pformat(type(o)), exp)
256
257 o = range(100)
258 exp = '[%s]' % ',\n '.join(map(str, o))
259 for type in [list, list2]:
260 self.assertEqual(pprint.pformat(type(o)), exp)
261
262 o = tuple(range(100))
263 exp = '(%s)' % ',\n '.join(map(str, o))
264 for type in [tuple, tuple2]:
265 self.assertEqual(pprint.pformat(type(o)), exp)
Barry Warsaw00859c02001-11-28 05:49:39 +0000266
Walter Dörwaldc8de4582003-12-03 20:26:05 +0000267 # indent parameter
268 o = range(100)
269 exp = '[ %s]' % ',\n '.join(map(str, o))
270 for type in [list, list2]:
271 self.assertEqual(pprint.pformat(type(o), indent=4), exp)
272
Georg Brandl3ccb7872008-07-16 03:00:45 +0000273 def test_nested_indentations(self):
274 o1 = list(range(10))
275 o2 = dict(first=1, second=2, third=3)
276 o = [o1, o2]
277 expected = """\
278[ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200279 {'first': 1, 'second': 2, 'third': 3}]"""
280 self.assertEqual(pprint.pformat(o, indent=4, width=42), expected)
281 expected = """\
282[ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
Georg Brandl3ccb7872008-07-16 03:00:45 +0000283 { 'first': 1,
284 'second': 2,
285 'third': 3}]"""
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200286 self.assertEqual(pprint.pformat(o, indent=4, width=41), expected)
287
288 def test_width(self):
289 expected = """\
290[[[[[[1, 2, 3],
291 '1 2']]]],
292 {1: [1, 2, 3],
293 2: [12, 34]},
294 'abc def ghi',
295 ('ab cd ef',),
296 set2({1, 23}),
297 [[[[[1, 2, 3],
298 '1 2']]]]]"""
299 o = eval(expected)
300 self.assertEqual(pprint.pformat(o, width=15), expected)
301 self.assertEqual(pprint.pformat(o, width=16), expected)
302 self.assertEqual(pprint.pformat(o, width=25), expected)
303 self.assertEqual(pprint.pformat(o, width=14), """\
304[[[[[[1,
305 2,
306 3],
307 '1 '
308 '2']]]],
309 {1: [1,
310 2,
311 3],
312 2: [12,
313 34]},
314 'abc def '
315 'ghi',
316 ('ab cd '
317 'ef',),
318 set2({1,
319 23}),
320 [[[[[1,
321 2,
322 3],
323 '1 '
324 '2']]]]]""")
Georg Brandl3ccb7872008-07-16 03:00:45 +0000325
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000326 def test_sorted_dict(self):
327 # Starting in Python 2.5, pprint sorts dict displays by key regardless
328 # of how small the dictionary may be.
329 # Before the change, on 32-bit Windows pformat() gave order
330 # 'a', 'c', 'b' here, so this test failed.
331 d = {'a': 1, 'b': 1, 'c': 1}
332 self.assertEqual(pprint.pformat(d), "{'a': 1, 'b': 1, 'c': 1}")
333 self.assertEqual(pprint.pformat([d, d]),
334 "[{'a': 1, 'b': 1, 'c': 1}, {'a': 1, 'b': 1, 'c': 1}]")
335
336 # The next one is kind of goofy. The sorted order depends on the
337 # alphabetic order of type names: "int" < "str" < "tuple". Before
338 # Python 2.5, this was in the test_same_as_repr() test. It's worth
339 # keeping around for now because it's one of few tests of pprint
340 # against a crazy mix of types.
341 self.assertEqual(pprint.pformat({"xy\tab\n": (3,), 5: [[]], (): {}}),
342 r"{5: [[]], 'xy\tab\n': (3,), (): {}}")
343
Rémi Lapeyre96831c72019-03-22 18:22:20 +0100344 def test_sort_dict(self):
345 d = dict.fromkeys('cba')
346 self.assertEqual(pprint.pformat(d, sort_dicts=False), "{'c': None, 'b': None, 'a': None}")
347 self.assertEqual(pprint.pformat([d, d], sort_dicts=False),
348 "[{'c': None, 'b': None, 'a': None}, {'c': None, 'b': None, 'a': None}]")
349
Raymond Hettingerbad3c882010-09-09 12:31:00 +0000350 def test_ordered_dict(self):
Serhiy Storchakaaa4c36f2015-03-26 08:51:33 +0200351 d = collections.OrderedDict()
352 self.assertEqual(pprint.pformat(d, width=1), 'OrderedDict()')
353 d = collections.OrderedDict([])
354 self.assertEqual(pprint.pformat(d, width=1), 'OrderedDict()')
Raymond Hettingerbad3c882010-09-09 12:31:00 +0000355 words = 'the quick brown fox jumped over a lazy dog'.split()
356 d = collections.OrderedDict(zip(words, itertools.count()))
357 self.assertEqual(pprint.pformat(d),
358"""\
Serhiy Storchakaaa4c36f2015-03-26 08:51:33 +0200359OrderedDict([('the', 0),
360 ('quick', 1),
361 ('brown', 2),
362 ('fox', 3),
363 ('jumped', 4),
364 ('over', 5),
365 ('a', 6),
366 ('lazy', 7),
367 ('dog', 8)])""")
Serhiy Storchaka87eb4822015-03-24 19:31:50 +0200368
369 def test_mapping_proxy(self):
370 words = 'the quick brown fox jumped over a lazy dog'.split()
371 d = dict(zip(words, itertools.count()))
372 m = types.MappingProxyType(d)
373 self.assertEqual(pprint.pformat(m), """\
374mappingproxy({'a': 6,
375 'brown': 2,
376 'dog': 8,
377 'fox': 3,
378 'jumped': 4,
379 'lazy': 7,
380 'over': 5,
381 'quick': 1,
382 'the': 0})""")
383 d = collections.OrderedDict(zip(words, itertools.count()))
384 m = types.MappingProxyType(d)
385 self.assertEqual(pprint.pformat(m), """\
Serhiy Storchakaaa4c36f2015-03-26 08:51:33 +0200386mappingproxy(OrderedDict([('the', 0),
387 ('quick', 1),
388 ('brown', 2),
389 ('fox', 3),
390 ('jumped', 4),
391 ('over', 5),
392 ('a', 6),
393 ('lazy', 7),
394 ('dog', 8)]))""")
Serhiy Storchaka87eb4822015-03-24 19:31:50 +0200395
Carl Bordum Hansen06a89162019-06-27 01:13:18 +0200396 def test_empty_simple_namespace(self):
397 ns = types.SimpleNamespace()
398 formatted = pprint.pformat(ns)
399 self.assertEqual(formatted, "namespace()")
400
401 def test_small_simple_namespace(self):
402 ns = types.SimpleNamespace(a=1, b=2)
403 formatted = pprint.pformat(ns)
404 self.assertEqual(formatted, "namespace(a=1, b=2)")
405
406 def test_simple_namespace(self):
407 ns = types.SimpleNamespace(
408 the=0,
409 quick=1,
410 brown=2,
411 fox=3,
412 jumped=4,
413 over=5,
414 a=6,
415 lazy=7,
416 dog=8,
417 )
418 formatted = pprint.pformat(ns, width=60)
419 self.assertEqual(formatted, """\
420namespace(the=0,
421 quick=1,
422 brown=2,
423 fox=3,
424 jumped=4,
425 over=5,
426 a=6,
427 lazy=7,
428 dog=8)""")
429
430 def test_simple_namespace_subclass(self):
431 class AdvancedNamespace(types.SimpleNamespace): pass
432 ns = AdvancedNamespace(
433 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 formatted = pprint.pformat(ns, width=60)
444 self.assertEqual(formatted, """\
445AdvancedNamespace(the=0,
446 quick=1,
447 brown=2,
448 fox=3,
449 jumped=4,
450 over=5,
451 a=6,
452 lazy=7,
453 dog=8)""")
454
Fred Drakeaee113d2002-04-02 05:08:35 +0000455 def test_subclassing(self):
456 o = {'names with spaces': 'should be presented using repr()',
457 'others.should.not.be': 'like.this'}
458 exp = """\
459{'names with spaces': 'should be presented using repr()',
460 others.should.not.be: like.this}"""
461 self.assertEqual(DottedPrettyPrinter().pformat(o), exp)
462
Serhiy Storchaka51844382013-10-02 11:40:49 +0300463 def test_set_reprs(self):
464 self.assertEqual(pprint.pformat(set()), 'set()')
465 self.assertEqual(pprint.pformat(set(range(3))), '{0, 1, 2}')
466 self.assertEqual(pprint.pformat(set(range(7)), width=20), '''\
467{0,
468 1,
469 2,
470 3,
471 4,
472 5,
473 6}''')
474 self.assertEqual(pprint.pformat(set2(range(7)), width=20), '''\
475set2({0,
476 1,
477 2,
478 3,
479 4,
480 5,
481 6})''')
482 self.assertEqual(pprint.pformat(set3(range(7)), width=20),
483 'set3({0, 1, 2, 3, 4, 5, 6})')
484
485 self.assertEqual(pprint.pformat(frozenset()), 'frozenset()')
486 self.assertEqual(pprint.pformat(frozenset(range(3))),
487 'frozenset({0, 1, 2})')
488 self.assertEqual(pprint.pformat(frozenset(range(7)), width=20), '''\
489frozenset({0,
490 1,
491 2,
492 3,
493 4,
494 5,
495 6})''')
496 self.assertEqual(pprint.pformat(frozenset2(range(7)), width=20), '''\
497frozenset2({0,
498 1,
499 2,
500 3,
501 4,
502 5,
503 6})''')
504 self.assertEqual(pprint.pformat(frozenset3(range(7)), width=20),
505 'frozenset3({0, 1, 2, 3, 4, 5, 6})')
506
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400507 @unittest.expectedFailure
508 #See http://bugs.python.org/issue13907
Daniel Stutzbachc944cfc2010-09-21 21:08:09 +0000509 @test.support.cpython_only
Serhiy Storchaka51844382013-10-02 11:40:49 +0300510 def test_set_of_sets_reprs(self):
Daniel Stutzbachc944cfc2010-09-21 21:08:09 +0000511 # This test creates a complex arrangement of frozensets and
512 # compares the pretty-printed repr against a string hard-coded in
513 # the test. The hard-coded repr depends on the sort order of
514 # frozensets.
515 #
516 # However, as the docs point out: "Since sets only define
517 # partial ordering (subset relationships), the output of the
518 # list.sort() method is undefined for lists of sets."
519 #
520 # In a nutshell, the test assumes frozenset({0}) will always
521 # sort before frozenset({1}), but:
522 #
523 # >>> frozenset({0}) < frozenset({1})
524 # False
525 # >>> frozenset({1}) < frozenset({0})
526 # False
527 #
528 # Consequently, this test is fragile and
529 # implementation-dependent. Small changes to Python's sort
530 # algorithm cause the test to fail when it should pass.
Min ho Kimc4cacc82019-07-31 08:16:13 +1000531 # XXX Or changes to the dictionary implementation...
Daniel Stutzbachc944cfc2010-09-21 21:08:09 +0000532
Christian Heimes969fe572008-01-25 11:23:10 +0000533 cube_repr_tgt = """\
534{frozenset(): frozenset({frozenset({2}), frozenset({0}), frozenset({1})}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000535 frozenset({0}): frozenset({frozenset(),
Christian Heimes969fe572008-01-25 11:23:10 +0000536 frozenset({0, 2}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000537 frozenset({0, 1})}),
538 frozenset({1}): frozenset({frozenset(),
Christian Heimes969fe572008-01-25 11:23:10 +0000539 frozenset({1, 2}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000540 frozenset({0, 1})}),
541 frozenset({2}): frozenset({frozenset(),
Christian Heimes969fe572008-01-25 11:23:10 +0000542 frozenset({1, 2}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000543 frozenset({0, 2})}),
544 frozenset({1, 2}): frozenset({frozenset({2}),
Christian Heimes969fe572008-01-25 11:23:10 +0000545 frozenset({1}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000546 frozenset({0, 1, 2})}),
547 frozenset({0, 2}): frozenset({frozenset({2}),
Christian Heimes969fe572008-01-25 11:23:10 +0000548 frozenset({0}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000549 frozenset({0, 1, 2})}),
550 frozenset({0, 1}): frozenset({frozenset({0}),
Christian Heimes969fe572008-01-25 11:23:10 +0000551 frozenset({1}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000552 frozenset({0, 1, 2})}),
553 frozenset({0, 1, 2}): frozenset({frozenset({1, 2}),
Christian Heimes969fe572008-01-25 11:23:10 +0000554 frozenset({0, 2}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000555 frozenset({0, 1})})}"""
Christian Heimes969fe572008-01-25 11:23:10 +0000556 cube = test.test_set.cube(3)
557 self.assertEqual(pprint.pformat(cube), cube_repr_tgt)
558 cubo_repr_tgt = """\
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000559{frozenset({frozenset({0, 2}), frozenset({0})}): frozenset({frozenset({frozenset({0,
560 2}),
561 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000562 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000563 2})}),
564 frozenset({frozenset({0}),
565 frozenset({0,
566 1})}),
567 frozenset({frozenset(),
568 frozenset({0})}),
569 frozenset({frozenset({2}),
570 frozenset({0,
571 2})})}),
572 frozenset({frozenset({0, 1}), frozenset({1})}): frozenset({frozenset({frozenset({0,
573 1}),
574 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000575 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000576 2})}),
577 frozenset({frozenset({0}),
578 frozenset({0,
579 1})}),
580 frozenset({frozenset({1}),
581 frozenset({1,
582 2})}),
583 frozenset({frozenset(),
584 frozenset({1})})}),
585 frozenset({frozenset({1, 2}), frozenset({1})}): frozenset({frozenset({frozenset({1,
586 2}),
587 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000588 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000589 2})}),
590 frozenset({frozenset({2}),
591 frozenset({1,
592 2})}),
593 frozenset({frozenset(),
594 frozenset({1})}),
595 frozenset({frozenset({1}),
596 frozenset({0,
597 1})})}),
598 frozenset({frozenset({1, 2}), frozenset({2})}): frozenset({frozenset({frozenset({1,
599 2}),
600 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000601 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000602 2})}),
603 frozenset({frozenset({1}),
604 frozenset({1,
605 2})}),
606 frozenset({frozenset({2}),
607 frozenset({0,
608 2})}),
609 frozenset({frozenset(),
610 frozenset({2})})}),
611 frozenset({frozenset(), frozenset({0})}): frozenset({frozenset({frozenset({0}),
612 frozenset({0,
613 1})}),
614 frozenset({frozenset({0}),
615 frozenset({0,
616 2})}),
617 frozenset({frozenset(),
618 frozenset({1})}),
619 frozenset({frozenset(),
620 frozenset({2})})}),
621 frozenset({frozenset(), frozenset({1})}): frozenset({frozenset({frozenset(),
622 frozenset({0})}),
623 frozenset({frozenset({1}),
624 frozenset({1,
625 2})}),
626 frozenset({frozenset(),
627 frozenset({2})}),
628 frozenset({frozenset({1}),
629 frozenset({0,
630 1})})}),
631 frozenset({frozenset({2}), frozenset()}): frozenset({frozenset({frozenset({2}),
632 frozenset({1,
633 2})}),
634 frozenset({frozenset(),
635 frozenset({0})}),
636 frozenset({frozenset(),
637 frozenset({1})}),
638 frozenset({frozenset({2}),
639 frozenset({0,
640 2})})}),
641 frozenset({frozenset({0, 1, 2}), frozenset({0, 1})}): frozenset({frozenset({frozenset({1,
642 2}),
643 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000644 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000645 2})}),
646 frozenset({frozenset({0,
647 2}),
648 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000649 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000650 2})}),
651 frozenset({frozenset({0}),
652 frozenset({0,
653 1})}),
654 frozenset({frozenset({1}),
655 frozenset({0,
656 1})})}),
657 frozenset({frozenset({0}), frozenset({0, 1})}): frozenset({frozenset({frozenset(),
658 frozenset({0})}),
659 frozenset({frozenset({0,
660 1}),
661 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000662 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000663 2})}),
664 frozenset({frozenset({0}),
665 frozenset({0,
666 2})}),
667 frozenset({frozenset({1}),
668 frozenset({0,
669 1})})}),
670 frozenset({frozenset({2}), frozenset({0, 2})}): frozenset({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({2}),
676 frozenset({1,
677 2})}),
678 frozenset({frozenset({0}),
679 frozenset({0,
680 2})}),
681 frozenset({frozenset(),
682 frozenset({2})})}),
683 frozenset({frozenset({0, 1, 2}), frozenset({0, 2})}): frozenset({frozenset({frozenset({1,
684 2}),
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 1}),
690 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000691 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000692 2})}),
693 frozenset({frozenset({0}),
694 frozenset({0,
695 2})}),
696 frozenset({frozenset({2}),
697 frozenset({0,
698 2})})}),
699 frozenset({frozenset({1, 2}), frozenset({0, 1, 2})}): frozenset({frozenset({frozenset({0,
700 2}),
701 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000702 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000703 2})}),
704 frozenset({frozenset({0,
705 1}),
706 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000707 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000708 2})}),
709 frozenset({frozenset({2}),
710 frozenset({1,
711 2})}),
712 frozenset({frozenset({1}),
713 frozenset({1,
714 2})})})}"""
Christian Heimes969fe572008-01-25 11:23:10 +0000715
716 cubo = test.test_set.linegraph(cube)
717 self.assertEqual(pprint.pformat(cubo), cubo_repr_tgt)
718
Alexandre Vassalottieca20b62008-05-16 02:54:33 +0000719 def test_depth(self):
720 nested_tuple = (1, (2, (3, (4, (5, 6)))))
721 nested_dict = {1: {2: {3: {4: {5: {6: 6}}}}}}
722 nested_list = [1, [2, [3, [4, [5, [6, []]]]]]]
723 self.assertEqual(pprint.pformat(nested_tuple), repr(nested_tuple))
724 self.assertEqual(pprint.pformat(nested_dict), repr(nested_dict))
725 self.assertEqual(pprint.pformat(nested_list), repr(nested_list))
726
727 lv1_tuple = '(1, (...))'
728 lv1_dict = '{1: {...}}'
729 lv1_list = '[1, [...]]'
730 self.assertEqual(pprint.pformat(nested_tuple, depth=1), lv1_tuple)
731 self.assertEqual(pprint.pformat(nested_dict, depth=1), lv1_dict)
732 self.assertEqual(pprint.pformat(nested_list, depth=1), lv1_list)
733
Raymond Hettingera7da1662009-11-19 01:07:05 +0000734 def test_sort_unorderable_values(self):
735 # Issue 3976: sorted pprints fail for unorderable values.
736 n = 20
737 keys = [Unorderable() for i in range(n)]
738 random.shuffle(keys)
739 skeys = sorted(keys, key=id)
740 clean = lambda s: s.replace(' ', '').replace('\n','')
741
742 self.assertEqual(clean(pprint.pformat(set(keys))),
743 '{' + ','.join(map(repr, skeys)) + '}')
744 self.assertEqual(clean(pprint.pformat(frozenset(keys))),
745 'frozenset({' + ','.join(map(repr, skeys)) + '})')
746 self.assertEqual(clean(pprint.pformat(dict.fromkeys(keys))),
747 '{' + ','.join('%r:None' % k for k in skeys) + '}')
Fred Drakeaee113d2002-04-02 05:08:35 +0000748
Florent Xiclunad6da90f2012-07-21 11:17:38 +0200749 # Issue 10017: TypeError on user-defined types as dict keys.
750 self.assertEqual(pprint.pformat({Unorderable: 0, 1: 0}),
751 '{1: 0, ' + repr(Unorderable) +': 0}')
752
753 # Issue 14998: TypeError on tuples with NoneTypes as dict keys.
Florent Xicluna6e571d62012-07-21 12:44:20 +0200754 keys = [(1,), (None,)]
755 self.assertEqual(pprint.pformat(dict.fromkeys(keys, 0)),
756 '{%r: 0, %r: 0}' % tuple(sorted(keys, key=id)))
Florent Xiclunad6da90f2012-07-21 11:17:38 +0200757
Serhiy Storchaka62aa7dc2015-04-06 22:52:44 +0300758 def test_sort_orderable_and_unorderable_values(self):
759 # Issue 22721: sorted pprints is not stable
760 a = Unorderable()
761 b = Orderable(hash(a)) # should have the same hash value
762 # self-test
763 self.assertLess(a, b)
764 self.assertLess(str(type(b)), str(type(a)))
765 self.assertEqual(sorted([b, a]), [a, b])
766 self.assertEqual(sorted([a, b]), [a, b])
767 # set
768 self.assertEqual(pprint.pformat(set([b, a]), width=1),
769 '{%r,\n %r}' % (a, b))
770 self.assertEqual(pprint.pformat(set([a, b]), width=1),
771 '{%r,\n %r}' % (a, b))
772 # dict
773 self.assertEqual(pprint.pformat(dict.fromkeys([b, a]), width=1),
774 '{%r: None,\n %r: None}' % (a, b))
775 self.assertEqual(pprint.pformat(dict.fromkeys([a, b]), width=1),
776 '{%r: None,\n %r: None}' % (a, b))
777
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100778 def test_str_wrap(self):
779 # pprint tries to wrap strings intelligently
780 fox = 'the quick brown fox jumped over a lazy dog'
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200781 self.assertEqual(pprint.pformat(fox, width=19), """\
782('the quick brown '
783 'fox jumped over '
784 'a lazy dog')""")
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100785 self.assertEqual(pprint.pformat({'a': 1, 'b': fox, 'c': 2},
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200786 width=25), """\
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100787{'a': 1,
788 'b': 'the quick brown '
789 'fox jumped over '
790 'a lazy dog',
791 'c': 2}""")
792 # With some special characters
793 # - \n always triggers a new line in the pprint
794 # - \t and \n are escaped
795 # - non-ASCII is allowed
796 # - an apostrophe doesn't disrupt the pprint
797 special = "Portons dix bons \"whiskys\"\nà l'avocat goujat\t qui fumait au zoo"
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200798 self.assertEqual(pprint.pformat(special, width=68), repr(special))
799 self.assertEqual(pprint.pformat(special, width=31), """\
800('Portons dix bons "whiskys"\\n'
801 "à l'avocat goujat\\t qui "
802 'fumait au zoo')""")
803 self.assertEqual(pprint.pformat(special, width=20), """\
804('Portons dix bons '
805 '"whiskys"\\n'
Serhiy Storchakafe3dc372014-12-20 20:57:15 +0200806 "à l'avocat "
807 'goujat\\t qui '
808 'fumait au zoo')""")
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200809 self.assertEqual(pprint.pformat([[[[[special]]]]], width=35), """\
810[[[[['Portons dix bons "whiskys"\\n'
811 "à l'avocat goujat\\t qui "
812 'fumait au zoo']]]]]""")
813 self.assertEqual(pprint.pformat([[[[[special]]]]], width=25), """\
814[[[[['Portons dix bons '
815 '"whiskys"\\n'
816 "à l'avocat "
817 'goujat\\t qui '
818 'fumait au zoo']]]]]""")
819 self.assertEqual(pprint.pformat([[[[[special]]]]], width=23), """\
820[[[[['Portons dix '
821 'bons "whiskys"\\n'
822 "à l'avocat "
823 'goujat\\t qui '
824 'fumait au '
825 'zoo']]]]]""")
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100826 # An unwrappable string is formatted as its repr
827 unwrappable = "x" * 100
828 self.assertEqual(pprint.pformat(unwrappable, width=80), repr(unwrappable))
829 self.assertEqual(pprint.pformat(''), "''")
830 # Check that the pprint is a usable repr
831 special *= 10
832 for width in range(3, 40):
833 formatted = pprint.pformat(special, width=width)
Serhiy Storchakafe3dc372014-12-20 20:57:15 +0200834 self.assertEqual(eval(formatted), special)
835 formatted = pprint.pformat([special] * 2, width=width)
836 self.assertEqual(eval(formatted), [special] * 2)
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100837
Serhiy Storchaka7c411a42013-10-02 11:56:18 +0300838 def test_compact(self):
839 o = ([list(range(i * i)) for i in range(5)] +
840 [list(range(i)) for i in range(6)])
841 expected = """\
842[[], [0], [0, 1, 2, 3],
843 [0, 1, 2, 3, 4, 5, 6, 7, 8],
844 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
845 14, 15],
846 [], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3],
847 [0, 1, 2, 3, 4]]"""
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200848 self.assertEqual(pprint.pformat(o, width=47, compact=True), expected)
849
850 def test_compact_width(self):
851 levels = 20
852 number = 10
853 o = [0] * number
854 for i in range(levels - 1):
855 o = [o]
856 for w in range(levels * 2 + 1, levels + 3 * number - 1):
857 lines = pprint.pformat(o, width=w, compact=True).splitlines()
858 maxwidth = max(map(len, lines))
859 self.assertLessEqual(maxwidth, w)
860 self.assertGreater(maxwidth, w - 3)
Serhiy Storchaka7c411a42013-10-02 11:56:18 +0300861
Serhiy Storchaka022f2032015-03-24 19:22:37 +0200862 def test_bytes_wrap(self):
863 self.assertEqual(pprint.pformat(b'', width=1), "b''")
864 self.assertEqual(pprint.pformat(b'abcd', width=1), "b'abcd'")
865 letters = b'abcdefghijklmnopqrstuvwxyz'
866 self.assertEqual(pprint.pformat(letters, width=29), repr(letters))
867 self.assertEqual(pprint.pformat(letters, width=19), """\
868(b'abcdefghijkl'
869 b'mnopqrstuvwxyz')""")
870 self.assertEqual(pprint.pformat(letters, width=18), """\
871(b'abcdefghijkl'
872 b'mnopqrstuvwx'
873 b'yz')""")
874 self.assertEqual(pprint.pformat(letters, width=16), """\
875(b'abcdefghijkl'
876 b'mnopqrstuvwx'
877 b'yz')""")
878 special = bytes(range(16))
879 self.assertEqual(pprint.pformat(special, width=61), repr(special))
880 self.assertEqual(pprint.pformat(special, width=48), """\
881(b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'
882 b'\\x0c\\r\\x0e\\x0f')""")
883 self.assertEqual(pprint.pformat(special, width=32), """\
884(b'\\x00\\x01\\x02\\x03'
885 b'\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'
886 b'\\x0c\\r\\x0e\\x0f')""")
887 self.assertEqual(pprint.pformat(special, width=1), """\
888(b'\\x00\\x01\\x02\\x03'
889 b'\\x04\\x05\\x06\\x07'
890 b'\\x08\\t\\n\\x0b'
891 b'\\x0c\\r\\x0e\\x0f')""")
892 self.assertEqual(pprint.pformat({'a': 1, 'b': letters, 'c': 2},
893 width=21), """\
894{'a': 1,
895 'b': b'abcdefghijkl'
896 b'mnopqrstuvwx'
897 b'yz',
898 'c': 2}""")
899 self.assertEqual(pprint.pformat({'a': 1, 'b': letters, 'c': 2},
900 width=20), """\
901{'a': 1,
902 'b': b'abcdefgh'
903 b'ijklmnop'
904 b'qrstuvwxyz',
905 'c': 2}""")
906 self.assertEqual(pprint.pformat([[[[[[letters]]]]]], width=25), """\
907[[[[[[b'abcdefghijklmnop'
908 b'qrstuvwxyz']]]]]]""")
909 self.assertEqual(pprint.pformat([[[[[[special]]]]]], width=41), """\
910[[[[[[b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07'
911 b'\\x08\\t\\n\\x0b\\x0c\\r\\x0e\\x0f']]]]]]""")
912 # Check that the pprint is a usable repr
913 for width in range(1, 64):
914 formatted = pprint.pformat(special, width=width)
915 self.assertEqual(eval(formatted), special)
916 formatted = pprint.pformat([special] * 2, width=width)
917 self.assertEqual(eval(formatted), [special] * 2)
918
919 def test_bytearray_wrap(self):
920 self.assertEqual(pprint.pformat(bytearray(), width=1), "bytearray(b'')")
921 letters = bytearray(b'abcdefghijklmnopqrstuvwxyz')
922 self.assertEqual(pprint.pformat(letters, width=40), repr(letters))
923 self.assertEqual(pprint.pformat(letters, width=28), """\
924bytearray(b'abcdefghijkl'
925 b'mnopqrstuvwxyz')""")
926 self.assertEqual(pprint.pformat(letters, width=27), """\
927bytearray(b'abcdefghijkl'
928 b'mnopqrstuvwx'
929 b'yz')""")
930 self.assertEqual(pprint.pformat(letters, width=25), """\
931bytearray(b'abcdefghijkl'
932 b'mnopqrstuvwx'
933 b'yz')""")
934 special = bytearray(range(16))
935 self.assertEqual(pprint.pformat(special, width=72), repr(special))
936 self.assertEqual(pprint.pformat(special, width=57), """\
937bytearray(b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'
938 b'\\x0c\\r\\x0e\\x0f')""")
939 self.assertEqual(pprint.pformat(special, width=41), """\
940bytearray(b'\\x00\\x01\\x02\\x03'
941 b'\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'
942 b'\\x0c\\r\\x0e\\x0f')""")
943 self.assertEqual(pprint.pformat(special, width=1), """\
944bytearray(b'\\x00\\x01\\x02\\x03'
945 b'\\x04\\x05\\x06\\x07'
946 b'\\x08\\t\\n\\x0b'
947 b'\\x0c\\r\\x0e\\x0f')""")
948 self.assertEqual(pprint.pformat({'a': 1, 'b': letters, 'c': 2},
949 width=31), """\
950{'a': 1,
951 'b': bytearray(b'abcdefghijkl'
952 b'mnopqrstuvwx'
953 b'yz'),
954 'c': 2}""")
955 self.assertEqual(pprint.pformat([[[[[letters]]]]], width=37), """\
956[[[[[bytearray(b'abcdefghijklmnop'
957 b'qrstuvwxyz')]]]]]""")
958 self.assertEqual(pprint.pformat([[[[[special]]]]], width=50), """\
959[[[[[bytearray(b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07'
960 b'\\x08\\t\\n\\x0b\\x0c\\r\\x0e\\x0f')]]]]]""")
961
Serhiy Storchakabedbf962015-05-12 13:35:48 +0300962 def test_default_dict(self):
963 d = collections.defaultdict(int)
Benjamin Petersonab078e92016-07-13 21:13:29 -0700964 self.assertEqual(pprint.pformat(d, width=1), "defaultdict(<class 'int'>, {})")
Serhiy Storchakabedbf962015-05-12 13:35:48 +0300965 words = 'the quick brown fox jumped over a lazy dog'.split()
966 d = collections.defaultdict(int, zip(words, itertools.count()))
Benjamin Petersonab078e92016-07-13 21:13:29 -0700967 self.assertEqual(pprint.pformat(d),
968"""\
969defaultdict(<class 'int'>,
Serhiy Storchakabedbf962015-05-12 13:35:48 +0300970 {'a': 6,
971 'brown': 2,
972 'dog': 8,
973 'fox': 3,
974 'jumped': 4,
975 'lazy': 7,
976 'over': 5,
977 'quick': 1,
Benjamin Petersonab078e92016-07-13 21:13:29 -0700978 'the': 0})""")
Serhiy Storchakabedbf962015-05-12 13:35:48 +0300979
980 def test_counter(self):
981 d = collections.Counter()
982 self.assertEqual(pprint.pformat(d, width=1), "Counter()")
983 d = collections.Counter('senselessness')
984 self.assertEqual(pprint.pformat(d, width=40),
985"""\
986Counter({'s': 6,
987 'e': 4,
988 'n': 2,
989 'l': 1})""")
990
991 def test_chainmap(self):
992 d = collections.ChainMap()
993 self.assertEqual(pprint.pformat(d, width=1), "ChainMap({})")
994 words = 'the quick brown fox jumped over a lazy dog'.split()
995 items = list(zip(words, itertools.count()))
996 d = collections.ChainMap(dict(items))
997 self.assertEqual(pprint.pformat(d),
998"""\
999ChainMap({'a': 6,
1000 'brown': 2,
1001 'dog': 8,
1002 'fox': 3,
1003 'jumped': 4,
1004 'lazy': 7,
1005 'over': 5,
1006 'quick': 1,
1007 'the': 0})""")
1008 d = collections.ChainMap(dict(items), collections.OrderedDict(items))
1009 self.assertEqual(pprint.pformat(d),
1010"""\
1011ChainMap({'a': 6,
1012 'brown': 2,
1013 'dog': 8,
1014 'fox': 3,
1015 'jumped': 4,
1016 'lazy': 7,
1017 'over': 5,
1018 'quick': 1,
1019 'the': 0},
1020 OrderedDict([('the', 0),
1021 ('quick', 1),
1022 ('brown', 2),
1023 ('fox', 3),
1024 ('jumped', 4),
1025 ('over', 5),
1026 ('a', 6),
1027 ('lazy', 7),
1028 ('dog', 8)]))""")
1029
1030 def test_deque(self):
1031 d = collections.deque()
1032 self.assertEqual(pprint.pformat(d, width=1), "deque([])")
1033 d = collections.deque(maxlen=7)
1034 self.assertEqual(pprint.pformat(d, width=1), "deque([], maxlen=7)")
1035 words = 'the quick brown fox jumped over a lazy dog'.split()
1036 d = collections.deque(zip(words, itertools.count()))
1037 self.assertEqual(pprint.pformat(d),
1038"""\
1039deque([('the', 0),
1040 ('quick', 1),
1041 ('brown', 2),
1042 ('fox', 3),
1043 ('jumped', 4),
1044 ('over', 5),
1045 ('a', 6),
1046 ('lazy', 7),
1047 ('dog', 8)])""")
1048 d = collections.deque(zip(words, itertools.count()), maxlen=7)
1049 self.assertEqual(pprint.pformat(d),
1050"""\
1051deque([('brown', 2),
1052 ('fox', 3),
1053 ('jumped', 4),
1054 ('over', 5),
1055 ('a', 6),
1056 ('lazy', 7),
1057 ('dog', 8)],
1058 maxlen=7)""")
1059
1060 def test_user_dict(self):
1061 d = collections.UserDict()
1062 self.assertEqual(pprint.pformat(d, width=1), "{}")
1063 words = 'the quick brown fox jumped over a lazy dog'.split()
1064 d = collections.UserDict(zip(words, itertools.count()))
1065 self.assertEqual(pprint.pformat(d),
1066"""\
1067{'a': 6,
1068 'brown': 2,
1069 'dog': 8,
1070 'fox': 3,
1071 'jumped': 4,
1072 'lazy': 7,
1073 'over': 5,
1074 'quick': 1,
1075 'the': 0}""")
1076
Serhiy Storchaka265cee02015-10-29 09:52:20 +02001077 def test_user_list(self):
Serhiy Storchakabedbf962015-05-12 13:35:48 +03001078 d = collections.UserList()
1079 self.assertEqual(pprint.pformat(d, width=1), "[]")
1080 words = 'the quick brown fox jumped over a lazy dog'.split()
1081 d = collections.UserList(zip(words, itertools.count()))
1082 self.assertEqual(pprint.pformat(d),
1083"""\
1084[('the', 0),
1085 ('quick', 1),
1086 ('brown', 2),
1087 ('fox', 3),
1088 ('jumped', 4),
1089 ('over', 5),
1090 ('a', 6),
1091 ('lazy', 7),
1092 ('dog', 8)]""")
1093
1094 def test_user_string(self):
1095 d = collections.UserString('')
1096 self.assertEqual(pprint.pformat(d, width=1), "''")
1097 d = collections.UserString('the quick brown fox jumped over a lazy dog')
1098 self.assertEqual(pprint.pformat(d, width=20),
1099"""\
1100('the quick brown '
1101 'fox jumped over '
1102 'a lazy dog')""")
1103 self.assertEqual(pprint.pformat({1: d}, width=20),
1104"""\
1105{1: 'the quick '
1106 'brown fox '
1107 'jumped over a '
1108 'lazy dog'}""")
1109
Florent Xiclunad6da90f2012-07-21 11:17:38 +02001110
Fred Drakeaee113d2002-04-02 05:08:35 +00001111class DottedPrettyPrinter(pprint.PrettyPrinter):
Guido van Rossum32c2ae72002-08-22 19:45:32 +00001112
Fred Drakeaee113d2002-04-02 05:08:35 +00001113 def format(self, object, context, maxlevels, level):
1114 if isinstance(object, str):
1115 if ' ' in object:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001116 return repr(object), 1, 0
Fred Drakeaee113d2002-04-02 05:08:35 +00001117 else:
1118 return object, 0, 0
1119 else:
1120 return pprint.PrettyPrinter.format(
1121 self, object, context, maxlevels, level)
1122
1123
Fred Drake2e2be372001-09-20 21:33:42 +00001124if __name__ == "__main__":
Serhiy Storchakacbfe07e2015-05-20 19:37:10 +03001125 unittest.main()