blob: 428e77ef2195a8a682a35539acf6a39a87f357d5 [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
Walter Dörwald7a7ede52003-12-03 20:15:28 +000021class tuple2(tuple):
22 pass
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000023
Walter Dörwald7a7ede52003-12-03 20:15:28 +000024class tuple3(tuple):
25 def __repr__(self):
26 return tuple.__repr__(self)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000027
Serhiy Storchaka51844382013-10-02 11:40:49 +030028class set2(set):
29 pass
30
31class set3(set):
32 def __repr__(self):
33 return set.__repr__(self)
34
35class frozenset2(frozenset):
36 pass
37
38class frozenset3(frozenset):
39 def __repr__(self):
40 return frozenset.__repr__(self)
41
Walter Dörwald7a7ede52003-12-03 20:15:28 +000042class dict2(dict):
43 pass
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000044
Walter Dörwald7a7ede52003-12-03 20:15:28 +000045class dict3(dict):
46 def __repr__(self):
47 return dict.__repr__(self)
Tim Petersa814db52001-05-14 07:05:58 +000048
Raymond Hettingera7da1662009-11-19 01:07:05 +000049class Unorderable:
50 def __repr__(self):
51 return str(id(self))
52
Fred Drake43913dd2001-05-14 17:41:20 +000053class QueryTestCase(unittest.TestCase):
Tim Petersa814db52001-05-14 07:05:58 +000054
Fred Drake43913dd2001-05-14 17:41:20 +000055 def setUp(self):
Guido van Rossum805365e2007-05-07 22:24:25 +000056 self.a = list(range(100))
57 self.b = list(range(200))
Fred Drake43913dd2001-05-14 17:41:20 +000058 self.a[-12] = self.b
Tim Petersa814db52001-05-14 07:05:58 +000059
Serhiy Storchakaf3fa3082015-03-26 08:43:21 +020060 def test_init(self):
61 pp = pprint.PrettyPrinter()
62 pp = pprint.PrettyPrinter(indent=4, width=40, depth=5,
63 stream=io.StringIO(), compact=True)
64 pp = pprint.PrettyPrinter(4, 40, 5, io.StringIO())
65 with self.assertRaises(TypeError):
66 pp = pprint.PrettyPrinter(4, 40, 5, io.StringIO(), True)
67 self.assertRaises(ValueError, pprint.PrettyPrinter, indent=-1)
68 self.assertRaises(ValueError, pprint.PrettyPrinter, depth=0)
69 self.assertRaises(ValueError, pprint.PrettyPrinter, depth=-1)
70 self.assertRaises(ValueError, pprint.PrettyPrinter, width=0)
71
Fred Drake43913dd2001-05-14 17:41:20 +000072 def test_basic(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +000073 # Verify .isrecursive() and .isreadable() w/o recursion
Fred Drakeb456e4f2002-12-31 07:16:16 +000074 pp = pprint.PrettyPrinter()
Walter Dörwald5de48bd2007-06-11 21:38:39 +000075 for safe in (2, 2.0, 2j, "abc", [3], (2,2), {3: 3}, "yaddayadda",
Fred Drake43913dd2001-05-14 17:41:20 +000076 self.a, self.b):
Fred Drakeb456e4f2002-12-31 07:16:16 +000077 # module-level convenience functions
Ezio Melottib19f43d2010-01-24 20:59:24 +000078 self.assertFalse(pprint.isrecursive(safe),
79 "expected not isrecursive for %r" % (safe,))
80 self.assertTrue(pprint.isreadable(safe),
81 "expected isreadable for %r" % (safe,))
Fred Drakeb456e4f2002-12-31 07:16:16 +000082 # PrettyPrinter methods
Ezio Melottib19f43d2010-01-24 20:59:24 +000083 self.assertFalse(pp.isrecursive(safe),
84 "expected not isrecursive for %r" % (safe,))
85 self.assertTrue(pp.isreadable(safe),
86 "expected isreadable for %r" % (safe,))
Tim Petersa814db52001-05-14 07:05:58 +000087
Fred Drake43913dd2001-05-14 17:41:20 +000088 def test_knotted(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +000089 # Verify .isrecursive() and .isreadable() w/ recursion
Fred Drake43913dd2001-05-14 17:41:20 +000090 # Tie a knot.
91 self.b[67] = self.a
92 # Messy dict.
93 self.d = {}
94 self.d[0] = self.d[1] = self.d[2] = self.d
Tim Petersa814db52001-05-14 07:05:58 +000095
Fred Drakeb456e4f2002-12-31 07:16:16 +000096 pp = pprint.PrettyPrinter()
Tim Petersa814db52001-05-14 07:05:58 +000097
Fred Drake43913dd2001-05-14 17:41:20 +000098 for icky in self.a, self.b, self.d, (self.d, self.d):
Ezio Melottib19f43d2010-01-24 20:59:24 +000099 self.assertTrue(pprint.isrecursive(icky), "expected isrecursive")
100 self.assertFalse(pprint.isreadable(icky), "expected not isreadable")
101 self.assertTrue(pp.isrecursive(icky), "expected isrecursive")
102 self.assertFalse(pp.isreadable(icky), "expected not isreadable")
Fred Drake43913dd2001-05-14 17:41:20 +0000103
104 # Break the cycles.
105 self.d.clear()
106 del self.a[:]
107 del self.b[:]
108
109 for safe in self.a, self.b, self.d, (self.d, self.d):
Fred Drakeb456e4f2002-12-31 07:16:16 +0000110 # module-level convenience functions
Ezio Melottib19f43d2010-01-24 20:59:24 +0000111 self.assertFalse(pprint.isrecursive(safe),
112 "expected not isrecursive for %r" % (safe,))
113 self.assertTrue(pprint.isreadable(safe),
114 "expected isreadable for %r" % (safe,))
Fred Drakeb456e4f2002-12-31 07:16:16 +0000115 # PrettyPrinter methods
Ezio Melottib19f43d2010-01-24 20:59:24 +0000116 self.assertFalse(pp.isrecursive(safe),
117 "expected not isrecursive for %r" % (safe,))
118 self.assertTrue(pp.isreadable(safe),
119 "expected isreadable for %r" % (safe,))
Fred Drake43913dd2001-05-14 17:41:20 +0000120
121 def test_unreadable(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000122 # Not recursive but not readable anyway
Fred Drakeb456e4f2002-12-31 07:16:16 +0000123 pp = pprint.PrettyPrinter()
Fred Drake43913dd2001-05-14 17:41:20 +0000124 for unreadable in type(3), pprint, pprint.isrecursive:
Fred Drakeb456e4f2002-12-31 07:16:16 +0000125 # module-level convenience functions
Ezio Melottib19f43d2010-01-24 20:59:24 +0000126 self.assertFalse(pprint.isrecursive(unreadable),
127 "expected not isrecursive for %r" % (unreadable,))
128 self.assertFalse(pprint.isreadable(unreadable),
129 "expected not isreadable for %r" % (unreadable,))
Fred Drakeb456e4f2002-12-31 07:16:16 +0000130 # PrettyPrinter methods
Ezio Melottib19f43d2010-01-24 20:59:24 +0000131 self.assertFalse(pp.isrecursive(unreadable),
132 "expected not isrecursive for %r" % (unreadable,))
133 self.assertFalse(pp.isreadable(unreadable),
134 "expected not isreadable for %r" % (unreadable,))
Fred Drake43913dd2001-05-14 17:41:20 +0000135
Tim Peters95b3f782001-05-14 18:39:41 +0000136 def test_same_as_repr(self):
Walter Dörwald7a7ede52003-12-03 20:15:28 +0000137 # Simple objects, small containers and classes that overwrite __repr__
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000138 # For those the result should be the same as repr().
139 # Ahem. The docs don't say anything about that -- this appears to
140 # be testing an implementation quirk. Starting in Python 2.5, it's
141 # not true for dicts: pprint always sorts dicts by key now; before,
142 # it sorted a dict display if and only if the display required
143 # multiple lines. For that reason, dicts with more than one element
144 # aren't tested here.
Walter Dörwald5de48bd2007-06-11 21:38:39 +0000145 for simple in (0, 0, 0+0j, 0.0, "", b"",
Walter Dörwald7a7ede52003-12-03 20:15:28 +0000146 (), tuple2(), tuple3(),
147 [], list2(), list3(),
Serhiy Storchaka51844382013-10-02 11:40:49 +0300148 set(), set2(), set3(),
149 frozenset(), frozenset2(), frozenset3(),
Walter Dörwald7a7ede52003-12-03 20:15:28 +0000150 {}, dict2(), dict3(),
Ezio Melottib19f43d2010-01-24 20:59:24 +0000151 self.assertTrue, pprint,
Walter Dörwald5de48bd2007-06-11 21:38:39 +0000152 -6, -6, -6-6j, -1.5, "x", b"x", (3,), [3], {3: 6},
Benjamin Petersond23f8222009-04-05 19:13:16 +0000153 (1,2), [3,4], {5: 6},
Walter Dörwald7a7ede52003-12-03 20:15:28 +0000154 tuple2((1,2)), tuple3((1,2)), tuple3(range(100)),
155 [3,4], list2([3,4]), list3([3,4]), list3(range(100)),
Serhiy Storchaka51844382013-10-02 11:40:49 +0300156 set({7}), set2({7}), set3({7}),
157 frozenset({8}), frozenset2({8}), frozenset3({8}),
Benjamin Petersond23f8222009-04-05 19:13:16 +0000158 dict2({5: 6}), dict3({5: 6}),
Tim Peters95b3f782001-05-14 18:39:41 +0000159 range(10, -11, -1)
160 ):
161 native = repr(simple)
Serhiy Storchaka51844382013-10-02 11:40:49 +0300162 self.assertEqual(pprint.pformat(simple), native)
163 self.assertEqual(pprint.pformat(simple, width=1, indent=0)
164 .replace('\n', ' '), native)
165 self.assertEqual(pprint.saferepr(simple), native)
Fred Drake43913dd2001-05-14 17:41:20 +0000166
Barry Warsaw00859c02001-11-28 05:49:39 +0000167 def test_basic_line_wrap(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000168 # verify basic line-wrapping operation
Barry Warsaw00859c02001-11-28 05:49:39 +0000169 o = {'RPM_cal': 0,
170 'RPM_cal2': 48059,
171 'Speed_cal': 0,
172 'controldesk_runtime_us': 0,
173 'main_code_runtime_us': 0,
174 'read_io_runtime_us': 0,
175 'write_io_runtime_us': 43690}
176 exp = """\
177{'RPM_cal': 0,
178 'RPM_cal2': 48059,
179 'Speed_cal': 0,
180 'controldesk_runtime_us': 0,
181 'main_code_runtime_us': 0,
182 'read_io_runtime_us': 0,
183 'write_io_runtime_us': 43690}"""
Walter Dörwald7a7ede52003-12-03 20:15:28 +0000184 for type in [dict, dict2]:
185 self.assertEqual(pprint.pformat(type(o)), exp)
186
187 o = range(100)
188 exp = '[%s]' % ',\n '.join(map(str, o))
189 for type in [list, list2]:
190 self.assertEqual(pprint.pformat(type(o)), exp)
191
192 o = tuple(range(100))
193 exp = '(%s)' % ',\n '.join(map(str, o))
194 for type in [tuple, tuple2]:
195 self.assertEqual(pprint.pformat(type(o)), exp)
Barry Warsaw00859c02001-11-28 05:49:39 +0000196
Walter Dörwaldc8de4582003-12-03 20:26:05 +0000197 # indent parameter
198 o = range(100)
199 exp = '[ %s]' % ',\n '.join(map(str, o))
200 for type in [list, list2]:
201 self.assertEqual(pprint.pformat(type(o), indent=4), exp)
202
Georg Brandl3ccb7872008-07-16 03:00:45 +0000203 def test_nested_indentations(self):
204 o1 = list(range(10))
205 o2 = dict(first=1, second=2, third=3)
206 o = [o1, o2]
207 expected = """\
208[ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200209 {'first': 1, 'second': 2, 'third': 3}]"""
210 self.assertEqual(pprint.pformat(o, indent=4, width=42), expected)
211 expected = """\
212[ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
Georg Brandl3ccb7872008-07-16 03:00:45 +0000213 { 'first': 1,
214 'second': 2,
215 'third': 3}]"""
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200216 self.assertEqual(pprint.pformat(o, indent=4, width=41), expected)
217
218 def test_width(self):
219 expected = """\
220[[[[[[1, 2, 3],
221 '1 2']]]],
222 {1: [1, 2, 3],
223 2: [12, 34]},
224 'abc def ghi',
225 ('ab cd ef',),
226 set2({1, 23}),
227 [[[[[1, 2, 3],
228 '1 2']]]]]"""
229 o = eval(expected)
230 self.assertEqual(pprint.pformat(o, width=15), expected)
231 self.assertEqual(pprint.pformat(o, width=16), expected)
232 self.assertEqual(pprint.pformat(o, width=25), expected)
233 self.assertEqual(pprint.pformat(o, width=14), """\
234[[[[[[1,
235 2,
236 3],
237 '1 '
238 '2']]]],
239 {1: [1,
240 2,
241 3],
242 2: [12,
243 34]},
244 'abc def '
245 'ghi',
246 ('ab cd '
247 'ef',),
248 set2({1,
249 23}),
250 [[[[[1,
251 2,
252 3],
253 '1 '
254 '2']]]]]""")
Georg Brandl3ccb7872008-07-16 03:00:45 +0000255
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000256 def test_sorted_dict(self):
257 # Starting in Python 2.5, pprint sorts dict displays by key regardless
258 # of how small the dictionary may be.
259 # Before the change, on 32-bit Windows pformat() gave order
260 # 'a', 'c', 'b' here, so this test failed.
261 d = {'a': 1, 'b': 1, 'c': 1}
262 self.assertEqual(pprint.pformat(d), "{'a': 1, 'b': 1, 'c': 1}")
263 self.assertEqual(pprint.pformat([d, d]),
264 "[{'a': 1, 'b': 1, 'c': 1}, {'a': 1, 'b': 1, 'c': 1}]")
265
266 # The next one is kind of goofy. The sorted order depends on the
267 # alphabetic order of type names: "int" < "str" < "tuple". Before
268 # Python 2.5, this was in the test_same_as_repr() test. It's worth
269 # keeping around for now because it's one of few tests of pprint
270 # against a crazy mix of types.
271 self.assertEqual(pprint.pformat({"xy\tab\n": (3,), 5: [[]], (): {}}),
272 r"{5: [[]], 'xy\tab\n': (3,), (): {}}")
273
Raymond Hettingerbad3c882010-09-09 12:31:00 +0000274 def test_ordered_dict(self):
Serhiy Storchakaaa4c36f2015-03-26 08:51:33 +0200275 d = collections.OrderedDict()
276 self.assertEqual(pprint.pformat(d, width=1), 'OrderedDict()')
277 d = collections.OrderedDict([])
278 self.assertEqual(pprint.pformat(d, width=1), 'OrderedDict()')
Raymond Hettingerbad3c882010-09-09 12:31:00 +0000279 words = 'the quick brown fox jumped over a lazy dog'.split()
280 d = collections.OrderedDict(zip(words, itertools.count()))
281 self.assertEqual(pprint.pformat(d),
282"""\
Serhiy Storchakaaa4c36f2015-03-26 08:51:33 +0200283OrderedDict([('the', 0),
284 ('quick', 1),
285 ('brown', 2),
286 ('fox', 3),
287 ('jumped', 4),
288 ('over', 5),
289 ('a', 6),
290 ('lazy', 7),
291 ('dog', 8)])""")
Serhiy Storchaka87eb4822015-03-24 19:31:50 +0200292
293 def test_mapping_proxy(self):
294 words = 'the quick brown fox jumped over a lazy dog'.split()
295 d = dict(zip(words, itertools.count()))
296 m = types.MappingProxyType(d)
297 self.assertEqual(pprint.pformat(m), """\
298mappingproxy({'a': 6,
299 'brown': 2,
300 'dog': 8,
301 'fox': 3,
302 'jumped': 4,
303 'lazy': 7,
304 'over': 5,
305 'quick': 1,
306 'the': 0})""")
307 d = collections.OrderedDict(zip(words, itertools.count()))
308 m = types.MappingProxyType(d)
309 self.assertEqual(pprint.pformat(m), """\
Serhiy Storchakaaa4c36f2015-03-26 08:51:33 +0200310mappingproxy(OrderedDict([('the', 0),
311 ('quick', 1),
312 ('brown', 2),
313 ('fox', 3),
314 ('jumped', 4),
315 ('over', 5),
316 ('a', 6),
317 ('lazy', 7),
318 ('dog', 8)]))""")
Serhiy Storchaka87eb4822015-03-24 19:31:50 +0200319
Fred Drakeaee113d2002-04-02 05:08:35 +0000320 def test_subclassing(self):
321 o = {'names with spaces': 'should be presented using repr()',
322 'others.should.not.be': 'like.this'}
323 exp = """\
324{'names with spaces': 'should be presented using repr()',
325 others.should.not.be: like.this}"""
326 self.assertEqual(DottedPrettyPrinter().pformat(o), exp)
327
Serhiy Storchaka51844382013-10-02 11:40:49 +0300328 def test_set_reprs(self):
329 self.assertEqual(pprint.pformat(set()), 'set()')
330 self.assertEqual(pprint.pformat(set(range(3))), '{0, 1, 2}')
331 self.assertEqual(pprint.pformat(set(range(7)), width=20), '''\
332{0,
333 1,
334 2,
335 3,
336 4,
337 5,
338 6}''')
339 self.assertEqual(pprint.pformat(set2(range(7)), width=20), '''\
340set2({0,
341 1,
342 2,
343 3,
344 4,
345 5,
346 6})''')
347 self.assertEqual(pprint.pformat(set3(range(7)), width=20),
348 'set3({0, 1, 2, 3, 4, 5, 6})')
349
350 self.assertEqual(pprint.pformat(frozenset()), 'frozenset()')
351 self.assertEqual(pprint.pformat(frozenset(range(3))),
352 'frozenset({0, 1, 2})')
353 self.assertEqual(pprint.pformat(frozenset(range(7)), width=20), '''\
354frozenset({0,
355 1,
356 2,
357 3,
358 4,
359 5,
360 6})''')
361 self.assertEqual(pprint.pformat(frozenset2(range(7)), width=20), '''\
362frozenset2({0,
363 1,
364 2,
365 3,
366 4,
367 5,
368 6})''')
369 self.assertEqual(pprint.pformat(frozenset3(range(7)), width=20),
370 'frozenset3({0, 1, 2, 3, 4, 5, 6})')
371
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400372 @unittest.expectedFailure
373 #See http://bugs.python.org/issue13907
Daniel Stutzbachc944cfc2010-09-21 21:08:09 +0000374 @test.support.cpython_only
Serhiy Storchaka51844382013-10-02 11:40:49 +0300375 def test_set_of_sets_reprs(self):
Daniel Stutzbachc944cfc2010-09-21 21:08:09 +0000376 # This test creates a complex arrangement of frozensets and
377 # compares the pretty-printed repr against a string hard-coded in
378 # the test. The hard-coded repr depends on the sort order of
379 # frozensets.
380 #
381 # However, as the docs point out: "Since sets only define
382 # partial ordering (subset relationships), the output of the
383 # list.sort() method is undefined for lists of sets."
384 #
385 # In a nutshell, the test assumes frozenset({0}) will always
386 # sort before frozenset({1}), but:
387 #
388 # >>> frozenset({0}) < frozenset({1})
389 # False
390 # >>> frozenset({1}) < frozenset({0})
391 # False
392 #
393 # Consequently, this test is fragile and
394 # implementation-dependent. Small changes to Python's sort
395 # algorithm cause the test to fail when it should pass.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400396 # XXX Or changes to the dictionary implmentation...
Daniel Stutzbachc944cfc2010-09-21 21:08:09 +0000397
Christian Heimes969fe572008-01-25 11:23:10 +0000398 cube_repr_tgt = """\
399{frozenset(): frozenset({frozenset({2}), frozenset({0}), frozenset({1})}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000400 frozenset({0}): frozenset({frozenset(),
Christian Heimes969fe572008-01-25 11:23:10 +0000401 frozenset({0, 2}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000402 frozenset({0, 1})}),
403 frozenset({1}): frozenset({frozenset(),
Christian Heimes969fe572008-01-25 11:23:10 +0000404 frozenset({1, 2}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000405 frozenset({0, 1})}),
406 frozenset({2}): frozenset({frozenset(),
Christian Heimes969fe572008-01-25 11:23:10 +0000407 frozenset({1, 2}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000408 frozenset({0, 2})}),
409 frozenset({1, 2}): frozenset({frozenset({2}),
Christian Heimes969fe572008-01-25 11:23:10 +0000410 frozenset({1}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000411 frozenset({0, 1, 2})}),
412 frozenset({0, 2}): frozenset({frozenset({2}),
Christian Heimes969fe572008-01-25 11:23:10 +0000413 frozenset({0}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000414 frozenset({0, 1, 2})}),
415 frozenset({0, 1}): frozenset({frozenset({0}),
Christian Heimes969fe572008-01-25 11:23:10 +0000416 frozenset({1}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000417 frozenset({0, 1, 2})}),
418 frozenset({0, 1, 2}): frozenset({frozenset({1, 2}),
Christian Heimes969fe572008-01-25 11:23:10 +0000419 frozenset({0, 2}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000420 frozenset({0, 1})})}"""
Christian Heimes969fe572008-01-25 11:23:10 +0000421 cube = test.test_set.cube(3)
422 self.assertEqual(pprint.pformat(cube), cube_repr_tgt)
423 cubo_repr_tgt = """\
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000424{frozenset({frozenset({0, 2}), frozenset({0})}): frozenset({frozenset({frozenset({0,
425 2}),
426 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000427 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000428 2})}),
429 frozenset({frozenset({0}),
430 frozenset({0,
431 1})}),
432 frozenset({frozenset(),
433 frozenset({0})}),
434 frozenset({frozenset({2}),
435 frozenset({0,
436 2})})}),
437 frozenset({frozenset({0, 1}), frozenset({1})}): frozenset({frozenset({frozenset({0,
438 1}),
439 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000440 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000441 2})}),
442 frozenset({frozenset({0}),
443 frozenset({0,
444 1})}),
445 frozenset({frozenset({1}),
446 frozenset({1,
447 2})}),
448 frozenset({frozenset(),
449 frozenset({1})})}),
450 frozenset({frozenset({1, 2}), frozenset({1})}): frozenset({frozenset({frozenset({1,
451 2}),
452 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000453 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000454 2})}),
455 frozenset({frozenset({2}),
456 frozenset({1,
457 2})}),
458 frozenset({frozenset(),
459 frozenset({1})}),
460 frozenset({frozenset({1}),
461 frozenset({0,
462 1})})}),
463 frozenset({frozenset({1, 2}), frozenset({2})}): frozenset({frozenset({frozenset({1,
464 2}),
465 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000466 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000467 2})}),
468 frozenset({frozenset({1}),
469 frozenset({1,
470 2})}),
471 frozenset({frozenset({2}),
472 frozenset({0,
473 2})}),
474 frozenset({frozenset(),
475 frozenset({2})})}),
476 frozenset({frozenset(), frozenset({0})}): frozenset({frozenset({frozenset({0}),
477 frozenset({0,
478 1})}),
479 frozenset({frozenset({0}),
480 frozenset({0,
481 2})}),
482 frozenset({frozenset(),
483 frozenset({1})}),
484 frozenset({frozenset(),
485 frozenset({2})})}),
486 frozenset({frozenset(), frozenset({1})}): frozenset({frozenset({frozenset(),
487 frozenset({0})}),
488 frozenset({frozenset({1}),
489 frozenset({1,
490 2})}),
491 frozenset({frozenset(),
492 frozenset({2})}),
493 frozenset({frozenset({1}),
494 frozenset({0,
495 1})})}),
496 frozenset({frozenset({2}), frozenset()}): frozenset({frozenset({frozenset({2}),
497 frozenset({1,
498 2})}),
499 frozenset({frozenset(),
500 frozenset({0})}),
501 frozenset({frozenset(),
502 frozenset({1})}),
503 frozenset({frozenset({2}),
504 frozenset({0,
505 2})})}),
506 frozenset({frozenset({0, 1, 2}), frozenset({0, 1})}): frozenset({frozenset({frozenset({1,
507 2}),
508 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000509 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000510 2})}),
511 frozenset({frozenset({0,
512 2}),
513 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000514 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000515 2})}),
516 frozenset({frozenset({0}),
517 frozenset({0,
518 1})}),
519 frozenset({frozenset({1}),
520 frozenset({0,
521 1})})}),
522 frozenset({frozenset({0}), frozenset({0, 1})}): frozenset({frozenset({frozenset(),
523 frozenset({0})}),
524 frozenset({frozenset({0,
525 1}),
526 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000527 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000528 2})}),
529 frozenset({frozenset({0}),
530 frozenset({0,
531 2})}),
532 frozenset({frozenset({1}),
533 frozenset({0,
534 1})})}),
535 frozenset({frozenset({2}), frozenset({0, 2})}): frozenset({frozenset({frozenset({0,
536 2}),
537 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000538 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000539 2})}),
540 frozenset({frozenset({2}),
541 frozenset({1,
542 2})}),
543 frozenset({frozenset({0}),
544 frozenset({0,
545 2})}),
546 frozenset({frozenset(),
547 frozenset({2})})}),
548 frozenset({frozenset({0, 1, 2}), frozenset({0, 2})}): frozenset({frozenset({frozenset({1,
549 2}),
550 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000551 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000552 2})}),
553 frozenset({frozenset({0,
554 1}),
555 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000556 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000557 2})}),
558 frozenset({frozenset({0}),
559 frozenset({0,
560 2})}),
561 frozenset({frozenset({2}),
562 frozenset({0,
563 2})})}),
564 frozenset({frozenset({1, 2}), frozenset({0, 1, 2})}): frozenset({frozenset({frozenset({0,
565 2}),
566 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000567 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000568 2})}),
569 frozenset({frozenset({0,
570 1}),
571 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000572 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000573 2})}),
574 frozenset({frozenset({2}),
575 frozenset({1,
576 2})}),
577 frozenset({frozenset({1}),
578 frozenset({1,
579 2})})})}"""
Christian Heimes969fe572008-01-25 11:23:10 +0000580
581 cubo = test.test_set.linegraph(cube)
582 self.assertEqual(pprint.pformat(cubo), cubo_repr_tgt)
583
Alexandre Vassalottieca20b62008-05-16 02:54:33 +0000584 def test_depth(self):
585 nested_tuple = (1, (2, (3, (4, (5, 6)))))
586 nested_dict = {1: {2: {3: {4: {5: {6: 6}}}}}}
587 nested_list = [1, [2, [3, [4, [5, [6, []]]]]]]
588 self.assertEqual(pprint.pformat(nested_tuple), repr(nested_tuple))
589 self.assertEqual(pprint.pformat(nested_dict), repr(nested_dict))
590 self.assertEqual(pprint.pformat(nested_list), repr(nested_list))
591
592 lv1_tuple = '(1, (...))'
593 lv1_dict = '{1: {...}}'
594 lv1_list = '[1, [...]]'
595 self.assertEqual(pprint.pformat(nested_tuple, depth=1), lv1_tuple)
596 self.assertEqual(pprint.pformat(nested_dict, depth=1), lv1_dict)
597 self.assertEqual(pprint.pformat(nested_list, depth=1), lv1_list)
598
Raymond Hettingera7da1662009-11-19 01:07:05 +0000599 def test_sort_unorderable_values(self):
600 # Issue 3976: sorted pprints fail for unorderable values.
601 n = 20
602 keys = [Unorderable() for i in range(n)]
603 random.shuffle(keys)
604 skeys = sorted(keys, key=id)
605 clean = lambda s: s.replace(' ', '').replace('\n','')
606
607 self.assertEqual(clean(pprint.pformat(set(keys))),
608 '{' + ','.join(map(repr, skeys)) + '}')
609 self.assertEqual(clean(pprint.pformat(frozenset(keys))),
610 'frozenset({' + ','.join(map(repr, skeys)) + '})')
611 self.assertEqual(clean(pprint.pformat(dict.fromkeys(keys))),
612 '{' + ','.join('%r:None' % k for k in skeys) + '}')
Fred Drakeaee113d2002-04-02 05:08:35 +0000613
Florent Xiclunad6da90f2012-07-21 11:17:38 +0200614 # Issue 10017: TypeError on user-defined types as dict keys.
615 self.assertEqual(pprint.pformat({Unorderable: 0, 1: 0}),
616 '{1: 0, ' + repr(Unorderable) +': 0}')
617
618 # Issue 14998: TypeError on tuples with NoneTypes as dict keys.
Florent Xicluna6e571d62012-07-21 12:44:20 +0200619 keys = [(1,), (None,)]
620 self.assertEqual(pprint.pformat(dict.fromkeys(keys, 0)),
621 '{%r: 0, %r: 0}' % tuple(sorted(keys, key=id)))
Florent Xiclunad6da90f2012-07-21 11:17:38 +0200622
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100623 def test_str_wrap(self):
624 # pprint tries to wrap strings intelligently
625 fox = 'the quick brown fox jumped over a lazy dog'
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200626 self.assertEqual(pprint.pformat(fox, width=19), """\
627('the quick brown '
628 'fox jumped over '
629 'a lazy dog')""")
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100630 self.assertEqual(pprint.pformat({'a': 1, 'b': fox, 'c': 2},
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200631 width=25), """\
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100632{'a': 1,
633 'b': 'the quick brown '
634 'fox jumped over '
635 'a lazy dog',
636 'c': 2}""")
637 # With some special characters
638 # - \n always triggers a new line in the pprint
639 # - \t and \n are escaped
640 # - non-ASCII is allowed
641 # - an apostrophe doesn't disrupt the pprint
642 special = "Portons dix bons \"whiskys\"\nà l'avocat goujat\t qui fumait au zoo"
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200643 self.assertEqual(pprint.pformat(special, width=68), repr(special))
644 self.assertEqual(pprint.pformat(special, width=31), """\
645('Portons dix bons "whiskys"\\n'
646 "à l'avocat goujat\\t qui "
647 'fumait au zoo')""")
648 self.assertEqual(pprint.pformat(special, width=20), """\
649('Portons dix bons '
650 '"whiskys"\\n'
Serhiy Storchakafe3dc372014-12-20 20:57:15 +0200651 "à l'avocat "
652 'goujat\\t qui '
653 'fumait au zoo')""")
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200654 self.assertEqual(pprint.pformat([[[[[special]]]]], width=35), """\
655[[[[['Portons dix bons "whiskys"\\n'
656 "à l'avocat goujat\\t qui "
657 'fumait au zoo']]]]]""")
658 self.assertEqual(pprint.pformat([[[[[special]]]]], width=25), """\
659[[[[['Portons dix bons '
660 '"whiskys"\\n'
661 "à l'avocat "
662 'goujat\\t qui '
663 'fumait au zoo']]]]]""")
664 self.assertEqual(pprint.pformat([[[[[special]]]]], width=23), """\
665[[[[['Portons dix '
666 'bons "whiskys"\\n'
667 "à l'avocat "
668 'goujat\\t qui '
669 'fumait au '
670 'zoo']]]]]""")
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100671 # An unwrappable string is formatted as its repr
672 unwrappable = "x" * 100
673 self.assertEqual(pprint.pformat(unwrappable, width=80), repr(unwrappable))
674 self.assertEqual(pprint.pformat(''), "''")
675 # Check that the pprint is a usable repr
676 special *= 10
677 for width in range(3, 40):
678 formatted = pprint.pformat(special, width=width)
Serhiy Storchakafe3dc372014-12-20 20:57:15 +0200679 self.assertEqual(eval(formatted), special)
680 formatted = pprint.pformat([special] * 2, width=width)
681 self.assertEqual(eval(formatted), [special] * 2)
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100682
Serhiy Storchaka7c411a42013-10-02 11:56:18 +0300683 def test_compact(self):
684 o = ([list(range(i * i)) for i in range(5)] +
685 [list(range(i)) for i in range(6)])
686 expected = """\
687[[], [0], [0, 1, 2, 3],
688 [0, 1, 2, 3, 4, 5, 6, 7, 8],
689 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
690 14, 15],
691 [], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3],
692 [0, 1, 2, 3, 4]]"""
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200693 self.assertEqual(pprint.pformat(o, width=47, compact=True), expected)
694
695 def test_compact_width(self):
696 levels = 20
697 number = 10
698 o = [0] * number
699 for i in range(levels - 1):
700 o = [o]
701 for w in range(levels * 2 + 1, levels + 3 * number - 1):
702 lines = pprint.pformat(o, width=w, compact=True).splitlines()
703 maxwidth = max(map(len, lines))
704 self.assertLessEqual(maxwidth, w)
705 self.assertGreater(maxwidth, w - 3)
Serhiy Storchaka7c411a42013-10-02 11:56:18 +0300706
Serhiy Storchaka022f2032015-03-24 19:22:37 +0200707 def test_bytes_wrap(self):
708 self.assertEqual(pprint.pformat(b'', width=1), "b''")
709 self.assertEqual(pprint.pformat(b'abcd', width=1), "b'abcd'")
710 letters = b'abcdefghijklmnopqrstuvwxyz'
711 self.assertEqual(pprint.pformat(letters, width=29), repr(letters))
712 self.assertEqual(pprint.pformat(letters, width=19), """\
713(b'abcdefghijkl'
714 b'mnopqrstuvwxyz')""")
715 self.assertEqual(pprint.pformat(letters, width=18), """\
716(b'abcdefghijkl'
717 b'mnopqrstuvwx'
718 b'yz')""")
719 self.assertEqual(pprint.pformat(letters, width=16), """\
720(b'abcdefghijkl'
721 b'mnopqrstuvwx'
722 b'yz')""")
723 special = bytes(range(16))
724 self.assertEqual(pprint.pformat(special, width=61), repr(special))
725 self.assertEqual(pprint.pformat(special, width=48), """\
726(b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'
727 b'\\x0c\\r\\x0e\\x0f')""")
728 self.assertEqual(pprint.pformat(special, width=32), """\
729(b'\\x00\\x01\\x02\\x03'
730 b'\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'
731 b'\\x0c\\r\\x0e\\x0f')""")
732 self.assertEqual(pprint.pformat(special, width=1), """\
733(b'\\x00\\x01\\x02\\x03'
734 b'\\x04\\x05\\x06\\x07'
735 b'\\x08\\t\\n\\x0b'
736 b'\\x0c\\r\\x0e\\x0f')""")
737 self.assertEqual(pprint.pformat({'a': 1, 'b': letters, 'c': 2},
738 width=21), """\
739{'a': 1,
740 'b': b'abcdefghijkl'
741 b'mnopqrstuvwx'
742 b'yz',
743 'c': 2}""")
744 self.assertEqual(pprint.pformat({'a': 1, 'b': letters, 'c': 2},
745 width=20), """\
746{'a': 1,
747 'b': b'abcdefgh'
748 b'ijklmnop'
749 b'qrstuvwxyz',
750 'c': 2}""")
751 self.assertEqual(pprint.pformat([[[[[[letters]]]]]], width=25), """\
752[[[[[[b'abcdefghijklmnop'
753 b'qrstuvwxyz']]]]]]""")
754 self.assertEqual(pprint.pformat([[[[[[special]]]]]], width=41), """\
755[[[[[[b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07'
756 b'\\x08\\t\\n\\x0b\\x0c\\r\\x0e\\x0f']]]]]]""")
757 # Check that the pprint is a usable repr
758 for width in range(1, 64):
759 formatted = pprint.pformat(special, width=width)
760 self.assertEqual(eval(formatted), special)
761 formatted = pprint.pformat([special] * 2, width=width)
762 self.assertEqual(eval(formatted), [special] * 2)
763
764 def test_bytearray_wrap(self):
765 self.assertEqual(pprint.pformat(bytearray(), width=1), "bytearray(b'')")
766 letters = bytearray(b'abcdefghijklmnopqrstuvwxyz')
767 self.assertEqual(pprint.pformat(letters, width=40), repr(letters))
768 self.assertEqual(pprint.pformat(letters, width=28), """\
769bytearray(b'abcdefghijkl'
770 b'mnopqrstuvwxyz')""")
771 self.assertEqual(pprint.pformat(letters, width=27), """\
772bytearray(b'abcdefghijkl'
773 b'mnopqrstuvwx'
774 b'yz')""")
775 self.assertEqual(pprint.pformat(letters, width=25), """\
776bytearray(b'abcdefghijkl'
777 b'mnopqrstuvwx'
778 b'yz')""")
779 special = bytearray(range(16))
780 self.assertEqual(pprint.pformat(special, width=72), repr(special))
781 self.assertEqual(pprint.pformat(special, width=57), """\
782bytearray(b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'
783 b'\\x0c\\r\\x0e\\x0f')""")
784 self.assertEqual(pprint.pformat(special, width=41), """\
785bytearray(b'\\x00\\x01\\x02\\x03'
786 b'\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'
787 b'\\x0c\\r\\x0e\\x0f')""")
788 self.assertEqual(pprint.pformat(special, width=1), """\
789bytearray(b'\\x00\\x01\\x02\\x03'
790 b'\\x04\\x05\\x06\\x07'
791 b'\\x08\\t\\n\\x0b'
792 b'\\x0c\\r\\x0e\\x0f')""")
793 self.assertEqual(pprint.pformat({'a': 1, 'b': letters, 'c': 2},
794 width=31), """\
795{'a': 1,
796 'b': bytearray(b'abcdefghijkl'
797 b'mnopqrstuvwx'
798 b'yz'),
799 'c': 2}""")
800 self.assertEqual(pprint.pformat([[[[[letters]]]]], width=37), """\
801[[[[[bytearray(b'abcdefghijklmnop'
802 b'qrstuvwxyz')]]]]]""")
803 self.assertEqual(pprint.pformat([[[[[special]]]]], width=50), """\
804[[[[[bytearray(b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07'
805 b'\\x08\\t\\n\\x0b\\x0c\\r\\x0e\\x0f')]]]]]""")
806
Florent Xiclunad6da90f2012-07-21 11:17:38 +0200807
Fred Drakeaee113d2002-04-02 05:08:35 +0000808class DottedPrettyPrinter(pprint.PrettyPrinter):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000809
Fred Drakeaee113d2002-04-02 05:08:35 +0000810 def format(self, object, context, maxlevels, level):
811 if isinstance(object, str):
812 if ' ' in object:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000813 return repr(object), 1, 0
Fred Drakeaee113d2002-04-02 05:08:35 +0000814 else:
815 return object, 0, 0
816 else:
817 return pprint.PrettyPrinter.format(
818 self, object, context, maxlevels, level)
819
820
Fred Drake2e2be372001-09-20 21:33:42 +0000821def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000822 test.support.run_unittest(QueryTestCase)
Fred Drake2e2be372001-09-20 21:33:42 +0000823
824
825if __name__ == "__main__":
826 test_main()