blob: ef2a8a58cef8be3b07b6938acaff68cfe94e63e8 [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
Serhiy Storchaka62aa7dc2015-04-06 22:52:44 +030053# Class Orderable is orderable with any type
54class Orderable:
55 def __init__(self, hash):
56 self._hash = hash
57 def __lt__(self, other):
58 return False
59 def __gt__(self, other):
60 return self != other
61 def __le__(self, other):
62 return self == other
63 def __ge__(self, other):
64 return True
65 def __eq__(self, other):
66 return self is other
67 def __ne__(self, other):
68 return self is not other
69 def __hash__(self):
70 return self._hash
71
Fred Drake43913dd2001-05-14 17:41:20 +000072class QueryTestCase(unittest.TestCase):
Tim Petersa814db52001-05-14 07:05:58 +000073
Fred Drake43913dd2001-05-14 17:41:20 +000074 def setUp(self):
Guido van Rossum805365e2007-05-07 22:24:25 +000075 self.a = list(range(100))
76 self.b = list(range(200))
Fred Drake43913dd2001-05-14 17:41:20 +000077 self.a[-12] = self.b
Tim Petersa814db52001-05-14 07:05:58 +000078
Serhiy Storchakaf3fa3082015-03-26 08:43:21 +020079 def test_init(self):
80 pp = pprint.PrettyPrinter()
81 pp = pprint.PrettyPrinter(indent=4, width=40, depth=5,
82 stream=io.StringIO(), compact=True)
83 pp = pprint.PrettyPrinter(4, 40, 5, io.StringIO())
84 with self.assertRaises(TypeError):
85 pp = pprint.PrettyPrinter(4, 40, 5, io.StringIO(), True)
86 self.assertRaises(ValueError, pprint.PrettyPrinter, indent=-1)
87 self.assertRaises(ValueError, pprint.PrettyPrinter, depth=0)
88 self.assertRaises(ValueError, pprint.PrettyPrinter, depth=-1)
89 self.assertRaises(ValueError, pprint.PrettyPrinter, width=0)
90
Fred Drake43913dd2001-05-14 17:41:20 +000091 def test_basic(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +000092 # Verify .isrecursive() and .isreadable() w/o recursion
Fred Drakeb456e4f2002-12-31 07:16:16 +000093 pp = pprint.PrettyPrinter()
Walter Dörwald5de48bd2007-06-11 21:38:39 +000094 for safe in (2, 2.0, 2j, "abc", [3], (2,2), {3: 3}, "yaddayadda",
Fred Drake43913dd2001-05-14 17:41:20 +000095 self.a, self.b):
Fred Drakeb456e4f2002-12-31 07:16:16 +000096 # module-level convenience functions
Ezio Melottib19f43d2010-01-24 20:59:24 +000097 self.assertFalse(pprint.isrecursive(safe),
98 "expected not isrecursive for %r" % (safe,))
99 self.assertTrue(pprint.isreadable(safe),
100 "expected isreadable for %r" % (safe,))
Fred Drakeb456e4f2002-12-31 07:16:16 +0000101 # PrettyPrinter methods
Ezio Melottib19f43d2010-01-24 20:59:24 +0000102 self.assertFalse(pp.isrecursive(safe),
103 "expected not isrecursive for %r" % (safe,))
104 self.assertTrue(pp.isreadable(safe),
105 "expected isreadable for %r" % (safe,))
Tim Petersa814db52001-05-14 07:05:58 +0000106
Fred Drake43913dd2001-05-14 17:41:20 +0000107 def test_knotted(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000108 # Verify .isrecursive() and .isreadable() w/ recursion
Fred Drake43913dd2001-05-14 17:41:20 +0000109 # Tie a knot.
110 self.b[67] = self.a
111 # Messy dict.
112 self.d = {}
113 self.d[0] = self.d[1] = self.d[2] = self.d
Tim Petersa814db52001-05-14 07:05:58 +0000114
Fred Drakeb456e4f2002-12-31 07:16:16 +0000115 pp = pprint.PrettyPrinter()
Tim Petersa814db52001-05-14 07:05:58 +0000116
Fred Drake43913dd2001-05-14 17:41:20 +0000117 for icky in self.a, self.b, self.d, (self.d, self.d):
Ezio Melottib19f43d2010-01-24 20:59:24 +0000118 self.assertTrue(pprint.isrecursive(icky), "expected isrecursive")
119 self.assertFalse(pprint.isreadable(icky), "expected not isreadable")
120 self.assertTrue(pp.isrecursive(icky), "expected isrecursive")
121 self.assertFalse(pp.isreadable(icky), "expected not isreadable")
Fred Drake43913dd2001-05-14 17:41:20 +0000122
123 # Break the cycles.
124 self.d.clear()
125 del self.a[:]
126 del self.b[:]
127
128 for safe in self.a, self.b, self.d, (self.d, self.d):
Fred Drakeb456e4f2002-12-31 07:16:16 +0000129 # module-level convenience functions
Ezio Melottib19f43d2010-01-24 20:59:24 +0000130 self.assertFalse(pprint.isrecursive(safe),
131 "expected not isrecursive for %r" % (safe,))
132 self.assertTrue(pprint.isreadable(safe),
133 "expected isreadable for %r" % (safe,))
Fred Drakeb456e4f2002-12-31 07:16:16 +0000134 # PrettyPrinter methods
Ezio Melottib19f43d2010-01-24 20:59:24 +0000135 self.assertFalse(pp.isrecursive(safe),
136 "expected not isrecursive for %r" % (safe,))
137 self.assertTrue(pp.isreadable(safe),
138 "expected isreadable for %r" % (safe,))
Fred Drake43913dd2001-05-14 17:41:20 +0000139
140 def test_unreadable(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000141 # Not recursive but not readable anyway
Fred Drakeb456e4f2002-12-31 07:16:16 +0000142 pp = pprint.PrettyPrinter()
Fred Drake43913dd2001-05-14 17:41:20 +0000143 for unreadable in type(3), pprint, pprint.isrecursive:
Fred Drakeb456e4f2002-12-31 07:16:16 +0000144 # module-level convenience functions
Ezio Melottib19f43d2010-01-24 20:59:24 +0000145 self.assertFalse(pprint.isrecursive(unreadable),
146 "expected not isrecursive for %r" % (unreadable,))
147 self.assertFalse(pprint.isreadable(unreadable),
148 "expected not isreadable for %r" % (unreadable,))
Fred Drakeb456e4f2002-12-31 07:16:16 +0000149 # PrettyPrinter methods
Ezio Melottib19f43d2010-01-24 20:59:24 +0000150 self.assertFalse(pp.isrecursive(unreadable),
151 "expected not isrecursive for %r" % (unreadable,))
152 self.assertFalse(pp.isreadable(unreadable),
153 "expected not isreadable for %r" % (unreadable,))
Fred Drake43913dd2001-05-14 17:41:20 +0000154
Tim Peters95b3f782001-05-14 18:39:41 +0000155 def test_same_as_repr(self):
Walter Dörwald7a7ede52003-12-03 20:15:28 +0000156 # Simple objects, small containers and classes that overwrite __repr__
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000157 # For those the result should be the same as repr().
158 # Ahem. The docs don't say anything about that -- this appears to
159 # be testing an implementation quirk. Starting in Python 2.5, it's
160 # not true for dicts: pprint always sorts dicts by key now; before,
161 # it sorted a dict display if and only if the display required
162 # multiple lines. For that reason, dicts with more than one element
163 # aren't tested here.
Walter Dörwald5de48bd2007-06-11 21:38:39 +0000164 for simple in (0, 0, 0+0j, 0.0, "", b"",
Walter Dörwald7a7ede52003-12-03 20:15:28 +0000165 (), tuple2(), tuple3(),
166 [], list2(), list3(),
Serhiy Storchaka51844382013-10-02 11:40:49 +0300167 set(), set2(), set3(),
168 frozenset(), frozenset2(), frozenset3(),
Walter Dörwald7a7ede52003-12-03 20:15:28 +0000169 {}, dict2(), dict3(),
Ezio Melottib19f43d2010-01-24 20:59:24 +0000170 self.assertTrue, pprint,
Walter Dörwald5de48bd2007-06-11 21:38:39 +0000171 -6, -6, -6-6j, -1.5, "x", b"x", (3,), [3], {3: 6},
Benjamin Petersond23f8222009-04-05 19:13:16 +0000172 (1,2), [3,4], {5: 6},
Walter Dörwald7a7ede52003-12-03 20:15:28 +0000173 tuple2((1,2)), tuple3((1,2)), tuple3(range(100)),
174 [3,4], list2([3,4]), list3([3,4]), list3(range(100)),
Serhiy Storchaka51844382013-10-02 11:40:49 +0300175 set({7}), set2({7}), set3({7}),
176 frozenset({8}), frozenset2({8}), frozenset3({8}),
Benjamin Petersond23f8222009-04-05 19:13:16 +0000177 dict2({5: 6}), dict3({5: 6}),
Tim Peters95b3f782001-05-14 18:39:41 +0000178 range(10, -11, -1)
179 ):
180 native = repr(simple)
Serhiy Storchaka51844382013-10-02 11:40:49 +0300181 self.assertEqual(pprint.pformat(simple), native)
182 self.assertEqual(pprint.pformat(simple, width=1, indent=0)
183 .replace('\n', ' '), native)
184 self.assertEqual(pprint.saferepr(simple), native)
Fred Drake43913dd2001-05-14 17:41:20 +0000185
Barry Warsaw00859c02001-11-28 05:49:39 +0000186 def test_basic_line_wrap(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000187 # verify basic line-wrapping operation
Barry Warsaw00859c02001-11-28 05:49:39 +0000188 o = {'RPM_cal': 0,
189 'RPM_cal2': 48059,
190 'Speed_cal': 0,
191 'controldesk_runtime_us': 0,
192 'main_code_runtime_us': 0,
193 'read_io_runtime_us': 0,
194 'write_io_runtime_us': 43690}
195 exp = """\
196{'RPM_cal': 0,
197 'RPM_cal2': 48059,
198 'Speed_cal': 0,
199 'controldesk_runtime_us': 0,
200 'main_code_runtime_us': 0,
201 'read_io_runtime_us': 0,
202 'write_io_runtime_us': 43690}"""
Walter Dörwald7a7ede52003-12-03 20:15:28 +0000203 for type in [dict, dict2]:
204 self.assertEqual(pprint.pformat(type(o)), exp)
205
206 o = range(100)
207 exp = '[%s]' % ',\n '.join(map(str, o))
208 for type in [list, list2]:
209 self.assertEqual(pprint.pformat(type(o)), exp)
210
211 o = tuple(range(100))
212 exp = '(%s)' % ',\n '.join(map(str, o))
213 for type in [tuple, tuple2]:
214 self.assertEqual(pprint.pformat(type(o)), exp)
Barry Warsaw00859c02001-11-28 05:49:39 +0000215
Walter Dörwaldc8de4582003-12-03 20:26:05 +0000216 # indent parameter
217 o = range(100)
218 exp = '[ %s]' % ',\n '.join(map(str, o))
219 for type in [list, list2]:
220 self.assertEqual(pprint.pformat(type(o), indent=4), exp)
221
Georg Brandl3ccb7872008-07-16 03:00:45 +0000222 def test_nested_indentations(self):
223 o1 = list(range(10))
224 o2 = dict(first=1, second=2, third=3)
225 o = [o1, o2]
226 expected = """\
227[ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200228 {'first': 1, 'second': 2, 'third': 3}]"""
229 self.assertEqual(pprint.pformat(o, indent=4, width=42), expected)
230 expected = """\
231[ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
Georg Brandl3ccb7872008-07-16 03:00:45 +0000232 { 'first': 1,
233 'second': 2,
234 'third': 3}]"""
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200235 self.assertEqual(pprint.pformat(o, indent=4, width=41), expected)
236
237 def test_width(self):
238 expected = """\
239[[[[[[1, 2, 3],
240 '1 2']]]],
241 {1: [1, 2, 3],
242 2: [12, 34]},
243 'abc def ghi',
244 ('ab cd ef',),
245 set2({1, 23}),
246 [[[[[1, 2, 3],
247 '1 2']]]]]"""
248 o = eval(expected)
249 self.assertEqual(pprint.pformat(o, width=15), expected)
250 self.assertEqual(pprint.pformat(o, width=16), expected)
251 self.assertEqual(pprint.pformat(o, width=25), expected)
252 self.assertEqual(pprint.pformat(o, width=14), """\
253[[[[[[1,
254 2,
255 3],
256 '1 '
257 '2']]]],
258 {1: [1,
259 2,
260 3],
261 2: [12,
262 34]},
263 'abc def '
264 'ghi',
265 ('ab cd '
266 'ef',),
267 set2({1,
268 23}),
269 [[[[[1,
270 2,
271 3],
272 '1 '
273 '2']]]]]""")
Georg Brandl3ccb7872008-07-16 03:00:45 +0000274
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000275 def test_sorted_dict(self):
276 # Starting in Python 2.5, pprint sorts dict displays by key regardless
277 # of how small the dictionary may be.
278 # Before the change, on 32-bit Windows pformat() gave order
279 # 'a', 'c', 'b' here, so this test failed.
280 d = {'a': 1, 'b': 1, 'c': 1}
281 self.assertEqual(pprint.pformat(d), "{'a': 1, 'b': 1, 'c': 1}")
282 self.assertEqual(pprint.pformat([d, d]),
283 "[{'a': 1, 'b': 1, 'c': 1}, {'a': 1, 'b': 1, 'c': 1}]")
284
285 # The next one is kind of goofy. The sorted order depends on the
286 # alphabetic order of type names: "int" < "str" < "tuple". Before
287 # Python 2.5, this was in the test_same_as_repr() test. It's worth
288 # keeping around for now because it's one of few tests of pprint
289 # against a crazy mix of types.
290 self.assertEqual(pprint.pformat({"xy\tab\n": (3,), 5: [[]], (): {}}),
291 r"{5: [[]], 'xy\tab\n': (3,), (): {}}")
292
Raymond Hettingerbad3c882010-09-09 12:31:00 +0000293 def test_ordered_dict(self):
Serhiy Storchakaaa4c36f2015-03-26 08:51:33 +0200294 d = collections.OrderedDict()
295 self.assertEqual(pprint.pformat(d, width=1), 'OrderedDict()')
296 d = collections.OrderedDict([])
297 self.assertEqual(pprint.pformat(d, width=1), 'OrderedDict()')
Raymond Hettingerbad3c882010-09-09 12:31:00 +0000298 words = 'the quick brown fox jumped over a lazy dog'.split()
299 d = collections.OrderedDict(zip(words, itertools.count()))
300 self.assertEqual(pprint.pformat(d),
301"""\
Serhiy Storchakaaa4c36f2015-03-26 08:51:33 +0200302OrderedDict([('the', 0),
303 ('quick', 1),
304 ('brown', 2),
305 ('fox', 3),
306 ('jumped', 4),
307 ('over', 5),
308 ('a', 6),
309 ('lazy', 7),
310 ('dog', 8)])""")
Serhiy Storchaka87eb4822015-03-24 19:31:50 +0200311
312 def test_mapping_proxy(self):
313 words = 'the quick brown fox jumped over a lazy dog'.split()
314 d = dict(zip(words, itertools.count()))
315 m = types.MappingProxyType(d)
316 self.assertEqual(pprint.pformat(m), """\
317mappingproxy({'a': 6,
318 'brown': 2,
319 'dog': 8,
320 'fox': 3,
321 'jumped': 4,
322 'lazy': 7,
323 'over': 5,
324 'quick': 1,
325 'the': 0})""")
326 d = collections.OrderedDict(zip(words, itertools.count()))
327 m = types.MappingProxyType(d)
328 self.assertEqual(pprint.pformat(m), """\
Serhiy Storchakaaa4c36f2015-03-26 08:51:33 +0200329mappingproxy(OrderedDict([('the', 0),
330 ('quick', 1),
331 ('brown', 2),
332 ('fox', 3),
333 ('jumped', 4),
334 ('over', 5),
335 ('a', 6),
336 ('lazy', 7),
337 ('dog', 8)]))""")
Serhiy Storchaka87eb4822015-03-24 19:31:50 +0200338
Fred Drakeaee113d2002-04-02 05:08:35 +0000339 def test_subclassing(self):
340 o = {'names with spaces': 'should be presented using repr()',
341 'others.should.not.be': 'like.this'}
342 exp = """\
343{'names with spaces': 'should be presented using repr()',
344 others.should.not.be: like.this}"""
345 self.assertEqual(DottedPrettyPrinter().pformat(o), exp)
346
Serhiy Storchaka51844382013-10-02 11:40:49 +0300347 def test_set_reprs(self):
348 self.assertEqual(pprint.pformat(set()), 'set()')
349 self.assertEqual(pprint.pformat(set(range(3))), '{0, 1, 2}')
350 self.assertEqual(pprint.pformat(set(range(7)), width=20), '''\
351{0,
352 1,
353 2,
354 3,
355 4,
356 5,
357 6}''')
358 self.assertEqual(pprint.pformat(set2(range(7)), width=20), '''\
359set2({0,
360 1,
361 2,
362 3,
363 4,
364 5,
365 6})''')
366 self.assertEqual(pprint.pformat(set3(range(7)), width=20),
367 'set3({0, 1, 2, 3, 4, 5, 6})')
368
369 self.assertEqual(pprint.pformat(frozenset()), 'frozenset()')
370 self.assertEqual(pprint.pformat(frozenset(range(3))),
371 'frozenset({0, 1, 2})')
372 self.assertEqual(pprint.pformat(frozenset(range(7)), width=20), '''\
373frozenset({0,
374 1,
375 2,
376 3,
377 4,
378 5,
379 6})''')
380 self.assertEqual(pprint.pformat(frozenset2(range(7)), width=20), '''\
381frozenset2({0,
382 1,
383 2,
384 3,
385 4,
386 5,
387 6})''')
388 self.assertEqual(pprint.pformat(frozenset3(range(7)), width=20),
389 'frozenset3({0, 1, 2, 3, 4, 5, 6})')
390
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400391 @unittest.expectedFailure
392 #See http://bugs.python.org/issue13907
Daniel Stutzbachc944cfc2010-09-21 21:08:09 +0000393 @test.support.cpython_only
Serhiy Storchaka51844382013-10-02 11:40:49 +0300394 def test_set_of_sets_reprs(self):
Daniel Stutzbachc944cfc2010-09-21 21:08:09 +0000395 # This test creates a complex arrangement of frozensets and
396 # compares the pretty-printed repr against a string hard-coded in
397 # the test. The hard-coded repr depends on the sort order of
398 # frozensets.
399 #
400 # However, as the docs point out: "Since sets only define
401 # partial ordering (subset relationships), the output of the
402 # list.sort() method is undefined for lists of sets."
403 #
404 # In a nutshell, the test assumes frozenset({0}) will always
405 # sort before frozenset({1}), but:
406 #
407 # >>> frozenset({0}) < frozenset({1})
408 # False
409 # >>> frozenset({1}) < frozenset({0})
410 # False
411 #
412 # Consequently, this test is fragile and
413 # implementation-dependent. Small changes to Python's sort
414 # algorithm cause the test to fail when it should pass.
Benjamin Peterson7d95e402012-04-23 11:24:50 -0400415 # XXX Or changes to the dictionary implmentation...
Daniel Stutzbachc944cfc2010-09-21 21:08:09 +0000416
Christian Heimes969fe572008-01-25 11:23:10 +0000417 cube_repr_tgt = """\
418{frozenset(): frozenset({frozenset({2}), frozenset({0}), frozenset({1})}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000419 frozenset({0}): frozenset({frozenset(),
Christian Heimes969fe572008-01-25 11:23:10 +0000420 frozenset({0, 2}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000421 frozenset({0, 1})}),
422 frozenset({1}): frozenset({frozenset(),
Christian Heimes969fe572008-01-25 11:23:10 +0000423 frozenset({1, 2}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000424 frozenset({0, 1})}),
425 frozenset({2}): frozenset({frozenset(),
Christian Heimes969fe572008-01-25 11:23:10 +0000426 frozenset({1, 2}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000427 frozenset({0, 2})}),
428 frozenset({1, 2}): frozenset({frozenset({2}),
Christian Heimes969fe572008-01-25 11:23:10 +0000429 frozenset({1}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000430 frozenset({0, 1, 2})}),
431 frozenset({0, 2}): frozenset({frozenset({2}),
Christian Heimes969fe572008-01-25 11:23:10 +0000432 frozenset({0}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000433 frozenset({0, 1, 2})}),
434 frozenset({0, 1}): frozenset({frozenset({0}),
Christian Heimes969fe572008-01-25 11:23:10 +0000435 frozenset({1}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000436 frozenset({0, 1, 2})}),
437 frozenset({0, 1, 2}): frozenset({frozenset({1, 2}),
Christian Heimes969fe572008-01-25 11:23:10 +0000438 frozenset({0, 2}),
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000439 frozenset({0, 1})})}"""
Christian Heimes969fe572008-01-25 11:23:10 +0000440 cube = test.test_set.cube(3)
441 self.assertEqual(pprint.pformat(cube), cube_repr_tgt)
442 cubo_repr_tgt = """\
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000443{frozenset({frozenset({0, 2}), frozenset({0})}): frozenset({frozenset({frozenset({0,
444 2}),
445 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000446 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000447 2})}),
448 frozenset({frozenset({0}),
449 frozenset({0,
450 1})}),
451 frozenset({frozenset(),
452 frozenset({0})}),
453 frozenset({frozenset({2}),
454 frozenset({0,
455 2})})}),
456 frozenset({frozenset({0, 1}), frozenset({1})}): frozenset({frozenset({frozenset({0,
457 1}),
458 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000459 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000460 2})}),
461 frozenset({frozenset({0}),
462 frozenset({0,
463 1})}),
464 frozenset({frozenset({1}),
465 frozenset({1,
466 2})}),
467 frozenset({frozenset(),
468 frozenset({1})})}),
469 frozenset({frozenset({1, 2}), frozenset({1})}): frozenset({frozenset({frozenset({1,
470 2}),
471 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000472 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000473 2})}),
474 frozenset({frozenset({2}),
475 frozenset({1,
476 2})}),
477 frozenset({frozenset(),
478 frozenset({1})}),
479 frozenset({frozenset({1}),
480 frozenset({0,
481 1})})}),
482 frozenset({frozenset({1, 2}), frozenset({2})}): frozenset({frozenset({frozenset({1,
483 2}),
484 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000485 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000486 2})}),
487 frozenset({frozenset({1}),
488 frozenset({1,
489 2})}),
490 frozenset({frozenset({2}),
491 frozenset({0,
492 2})}),
493 frozenset({frozenset(),
494 frozenset({2})})}),
495 frozenset({frozenset(), frozenset({0})}): frozenset({frozenset({frozenset({0}),
496 frozenset({0,
497 1})}),
498 frozenset({frozenset({0}),
499 frozenset({0,
500 2})}),
501 frozenset({frozenset(),
502 frozenset({1})}),
503 frozenset({frozenset(),
504 frozenset({2})})}),
505 frozenset({frozenset(), frozenset({1})}): frozenset({frozenset({frozenset(),
506 frozenset({0})}),
507 frozenset({frozenset({1}),
508 frozenset({1,
509 2})}),
510 frozenset({frozenset(),
511 frozenset({2})}),
512 frozenset({frozenset({1}),
513 frozenset({0,
514 1})})}),
515 frozenset({frozenset({2}), frozenset()}): frozenset({frozenset({frozenset({2}),
516 frozenset({1,
517 2})}),
518 frozenset({frozenset(),
519 frozenset({0})}),
520 frozenset({frozenset(),
521 frozenset({1})}),
522 frozenset({frozenset({2}),
523 frozenset({0,
524 2})})}),
525 frozenset({frozenset({0, 1, 2}), frozenset({0, 1})}): frozenset({frozenset({frozenset({1,
526 2}),
527 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000528 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000529 2})}),
530 frozenset({frozenset({0,
531 2}),
532 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000533 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000534 2})}),
535 frozenset({frozenset({0}),
536 frozenset({0,
537 1})}),
538 frozenset({frozenset({1}),
539 frozenset({0,
540 1})})}),
541 frozenset({frozenset({0}), frozenset({0, 1})}): frozenset({frozenset({frozenset(),
542 frozenset({0})}),
543 frozenset({frozenset({0,
544 1}),
545 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000546 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000547 2})}),
548 frozenset({frozenset({0}),
549 frozenset({0,
550 2})}),
551 frozenset({frozenset({1}),
552 frozenset({0,
553 1})})}),
554 frozenset({frozenset({2}), frozenset({0, 2})}): frozenset({frozenset({frozenset({0,
555 2}),
556 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000557 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000558 2})}),
559 frozenset({frozenset({2}),
560 frozenset({1,
561 2})}),
562 frozenset({frozenset({0}),
563 frozenset({0,
564 2})}),
565 frozenset({frozenset(),
566 frozenset({2})})}),
567 frozenset({frozenset({0, 1, 2}), frozenset({0, 2})}): frozenset({frozenset({frozenset({1,
568 2}),
569 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000570 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000571 2})}),
572 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 2})}),
580 frozenset({frozenset({2}),
581 frozenset({0,
582 2})})}),
583 frozenset({frozenset({1, 2}), frozenset({0, 1, 2})}): 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 1}),
590 frozenset({0,
Christian Heimes969fe572008-01-25 11:23:10 +0000591 1,
Raymond Hettinger4b8db412008-01-31 01:10:03 +0000592 2})}),
593 frozenset({frozenset({2}),
594 frozenset({1,
595 2})}),
596 frozenset({frozenset({1}),
597 frozenset({1,
598 2})})})}"""
Christian Heimes969fe572008-01-25 11:23:10 +0000599
600 cubo = test.test_set.linegraph(cube)
601 self.assertEqual(pprint.pformat(cubo), cubo_repr_tgt)
602
Alexandre Vassalottieca20b62008-05-16 02:54:33 +0000603 def test_depth(self):
604 nested_tuple = (1, (2, (3, (4, (5, 6)))))
605 nested_dict = {1: {2: {3: {4: {5: {6: 6}}}}}}
606 nested_list = [1, [2, [3, [4, [5, [6, []]]]]]]
607 self.assertEqual(pprint.pformat(nested_tuple), repr(nested_tuple))
608 self.assertEqual(pprint.pformat(nested_dict), repr(nested_dict))
609 self.assertEqual(pprint.pformat(nested_list), repr(nested_list))
610
611 lv1_tuple = '(1, (...))'
612 lv1_dict = '{1: {...}}'
613 lv1_list = '[1, [...]]'
614 self.assertEqual(pprint.pformat(nested_tuple, depth=1), lv1_tuple)
615 self.assertEqual(pprint.pformat(nested_dict, depth=1), lv1_dict)
616 self.assertEqual(pprint.pformat(nested_list, depth=1), lv1_list)
617
Raymond Hettingera7da1662009-11-19 01:07:05 +0000618 def test_sort_unorderable_values(self):
619 # Issue 3976: sorted pprints fail for unorderable values.
620 n = 20
621 keys = [Unorderable() for i in range(n)]
622 random.shuffle(keys)
623 skeys = sorted(keys, key=id)
624 clean = lambda s: s.replace(' ', '').replace('\n','')
625
626 self.assertEqual(clean(pprint.pformat(set(keys))),
627 '{' + ','.join(map(repr, skeys)) + '}')
628 self.assertEqual(clean(pprint.pformat(frozenset(keys))),
629 'frozenset({' + ','.join(map(repr, skeys)) + '})')
630 self.assertEqual(clean(pprint.pformat(dict.fromkeys(keys))),
631 '{' + ','.join('%r:None' % k for k in skeys) + '}')
Fred Drakeaee113d2002-04-02 05:08:35 +0000632
Florent Xiclunad6da90f2012-07-21 11:17:38 +0200633 # Issue 10017: TypeError on user-defined types as dict keys.
634 self.assertEqual(pprint.pformat({Unorderable: 0, 1: 0}),
635 '{1: 0, ' + repr(Unorderable) +': 0}')
636
637 # Issue 14998: TypeError on tuples with NoneTypes as dict keys.
Florent Xicluna6e571d62012-07-21 12:44:20 +0200638 keys = [(1,), (None,)]
639 self.assertEqual(pprint.pformat(dict.fromkeys(keys, 0)),
640 '{%r: 0, %r: 0}' % tuple(sorted(keys, key=id)))
Florent Xiclunad6da90f2012-07-21 11:17:38 +0200641
Serhiy Storchaka62aa7dc2015-04-06 22:52:44 +0300642 def test_sort_orderable_and_unorderable_values(self):
643 # Issue 22721: sorted pprints is not stable
644 a = Unorderable()
645 b = Orderable(hash(a)) # should have the same hash value
646 # self-test
647 self.assertLess(a, b)
648 self.assertLess(str(type(b)), str(type(a)))
649 self.assertEqual(sorted([b, a]), [a, b])
650 self.assertEqual(sorted([a, b]), [a, b])
651 # set
652 self.assertEqual(pprint.pformat(set([b, a]), width=1),
653 '{%r,\n %r}' % (a, b))
654 self.assertEqual(pprint.pformat(set([a, b]), width=1),
655 '{%r,\n %r}' % (a, b))
656 # dict
657 self.assertEqual(pprint.pformat(dict.fromkeys([b, a]), width=1),
658 '{%r: None,\n %r: None}' % (a, b))
659 self.assertEqual(pprint.pformat(dict.fromkeys([a, b]), width=1),
660 '{%r: None,\n %r: None}' % (a, b))
661
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100662 def test_str_wrap(self):
663 # pprint tries to wrap strings intelligently
664 fox = 'the quick brown fox jumped over a lazy dog'
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200665 self.assertEqual(pprint.pformat(fox, width=19), """\
666('the quick brown '
667 'fox jumped over '
668 'a lazy dog')""")
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100669 self.assertEqual(pprint.pformat({'a': 1, 'b': fox, 'c': 2},
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200670 width=25), """\
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100671{'a': 1,
672 'b': 'the quick brown '
673 'fox jumped over '
674 'a lazy dog',
675 'c': 2}""")
676 # With some special characters
677 # - \n always triggers a new line in the pprint
678 # - \t and \n are escaped
679 # - non-ASCII is allowed
680 # - an apostrophe doesn't disrupt the pprint
681 special = "Portons dix bons \"whiskys\"\nà l'avocat goujat\t qui fumait au zoo"
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200682 self.assertEqual(pprint.pformat(special, width=68), repr(special))
683 self.assertEqual(pprint.pformat(special, width=31), """\
684('Portons dix bons "whiskys"\\n'
685 "à l'avocat goujat\\t qui "
686 'fumait au zoo')""")
687 self.assertEqual(pprint.pformat(special, width=20), """\
688('Portons dix bons '
689 '"whiskys"\\n'
Serhiy Storchakafe3dc372014-12-20 20:57:15 +0200690 "à l'avocat "
691 'goujat\\t qui '
692 'fumait au zoo')""")
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200693 self.assertEqual(pprint.pformat([[[[[special]]]]], width=35), """\
694[[[[['Portons dix bons "whiskys"\\n'
695 "à l'avocat goujat\\t qui "
696 'fumait au zoo']]]]]""")
697 self.assertEqual(pprint.pformat([[[[[special]]]]], width=25), """\
698[[[[['Portons dix bons '
699 '"whiskys"\\n'
700 "à l'avocat "
701 'goujat\\t qui '
702 'fumait au zoo']]]]]""")
703 self.assertEqual(pprint.pformat([[[[[special]]]]], width=23), """\
704[[[[['Portons dix '
705 'bons "whiskys"\\n'
706 "à l'avocat "
707 'goujat\\t qui '
708 'fumait au '
709 'zoo']]]]]""")
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100710 # An unwrappable string is formatted as its repr
711 unwrappable = "x" * 100
712 self.assertEqual(pprint.pformat(unwrappable, width=80), repr(unwrappable))
713 self.assertEqual(pprint.pformat(''), "''")
714 # Check that the pprint is a usable repr
715 special *= 10
716 for width in range(3, 40):
717 formatted = pprint.pformat(special, width=width)
Serhiy Storchakafe3dc372014-12-20 20:57:15 +0200718 self.assertEqual(eval(formatted), special)
719 formatted = pprint.pformat([special] * 2, width=width)
720 self.assertEqual(eval(formatted), [special] * 2)
Antoine Pitrou64c16c32013-03-23 20:30:39 +0100721
Serhiy Storchaka7c411a42013-10-02 11:56:18 +0300722 def test_compact(self):
723 o = ([list(range(i * i)) for i in range(5)] +
724 [list(range(i)) for i in range(6)])
725 expected = """\
726[[], [0], [0, 1, 2, 3],
727 [0, 1, 2, 3, 4, 5, 6, 7, 8],
728 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
729 14, 15],
730 [], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3],
731 [0, 1, 2, 3, 4]]"""
Serhiy Storchakaa750ce32015-02-14 10:55:19 +0200732 self.assertEqual(pprint.pformat(o, width=47, compact=True), expected)
733
734 def test_compact_width(self):
735 levels = 20
736 number = 10
737 o = [0] * number
738 for i in range(levels - 1):
739 o = [o]
740 for w in range(levels * 2 + 1, levels + 3 * number - 1):
741 lines = pprint.pformat(o, width=w, compact=True).splitlines()
742 maxwidth = max(map(len, lines))
743 self.assertLessEqual(maxwidth, w)
744 self.assertGreater(maxwidth, w - 3)
Serhiy Storchaka7c411a42013-10-02 11:56:18 +0300745
Serhiy Storchaka022f2032015-03-24 19:22:37 +0200746 def test_bytes_wrap(self):
747 self.assertEqual(pprint.pformat(b'', width=1), "b''")
748 self.assertEqual(pprint.pformat(b'abcd', width=1), "b'abcd'")
749 letters = b'abcdefghijklmnopqrstuvwxyz'
750 self.assertEqual(pprint.pformat(letters, width=29), repr(letters))
751 self.assertEqual(pprint.pformat(letters, width=19), """\
752(b'abcdefghijkl'
753 b'mnopqrstuvwxyz')""")
754 self.assertEqual(pprint.pformat(letters, width=18), """\
755(b'abcdefghijkl'
756 b'mnopqrstuvwx'
757 b'yz')""")
758 self.assertEqual(pprint.pformat(letters, width=16), """\
759(b'abcdefghijkl'
760 b'mnopqrstuvwx'
761 b'yz')""")
762 special = bytes(range(16))
763 self.assertEqual(pprint.pformat(special, width=61), repr(special))
764 self.assertEqual(pprint.pformat(special, width=48), """\
765(b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'
766 b'\\x0c\\r\\x0e\\x0f')""")
767 self.assertEqual(pprint.pformat(special, width=32), """\
768(b'\\x00\\x01\\x02\\x03'
769 b'\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'
770 b'\\x0c\\r\\x0e\\x0f')""")
771 self.assertEqual(pprint.pformat(special, width=1), """\
772(b'\\x00\\x01\\x02\\x03'
773 b'\\x04\\x05\\x06\\x07'
774 b'\\x08\\t\\n\\x0b'
775 b'\\x0c\\r\\x0e\\x0f')""")
776 self.assertEqual(pprint.pformat({'a': 1, 'b': letters, 'c': 2},
777 width=21), """\
778{'a': 1,
779 'b': b'abcdefghijkl'
780 b'mnopqrstuvwx'
781 b'yz',
782 'c': 2}""")
783 self.assertEqual(pprint.pformat({'a': 1, 'b': letters, 'c': 2},
784 width=20), """\
785{'a': 1,
786 'b': b'abcdefgh'
787 b'ijklmnop'
788 b'qrstuvwxyz',
789 'c': 2}""")
790 self.assertEqual(pprint.pformat([[[[[[letters]]]]]], width=25), """\
791[[[[[[b'abcdefghijklmnop'
792 b'qrstuvwxyz']]]]]]""")
793 self.assertEqual(pprint.pformat([[[[[[special]]]]]], width=41), """\
794[[[[[[b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07'
795 b'\\x08\\t\\n\\x0b\\x0c\\r\\x0e\\x0f']]]]]]""")
796 # Check that the pprint is a usable repr
797 for width in range(1, 64):
798 formatted = pprint.pformat(special, width=width)
799 self.assertEqual(eval(formatted), special)
800 formatted = pprint.pformat([special] * 2, width=width)
801 self.assertEqual(eval(formatted), [special] * 2)
802
803 def test_bytearray_wrap(self):
804 self.assertEqual(pprint.pformat(bytearray(), width=1), "bytearray(b'')")
805 letters = bytearray(b'abcdefghijklmnopqrstuvwxyz')
806 self.assertEqual(pprint.pformat(letters, width=40), repr(letters))
807 self.assertEqual(pprint.pformat(letters, width=28), """\
808bytearray(b'abcdefghijkl'
809 b'mnopqrstuvwxyz')""")
810 self.assertEqual(pprint.pformat(letters, width=27), """\
811bytearray(b'abcdefghijkl'
812 b'mnopqrstuvwx'
813 b'yz')""")
814 self.assertEqual(pprint.pformat(letters, width=25), """\
815bytearray(b'abcdefghijkl'
816 b'mnopqrstuvwx'
817 b'yz')""")
818 special = bytearray(range(16))
819 self.assertEqual(pprint.pformat(special, width=72), repr(special))
820 self.assertEqual(pprint.pformat(special, width=57), """\
821bytearray(b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'
822 b'\\x0c\\r\\x0e\\x0f')""")
823 self.assertEqual(pprint.pformat(special, width=41), """\
824bytearray(b'\\x00\\x01\\x02\\x03'
825 b'\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b'
826 b'\\x0c\\r\\x0e\\x0f')""")
827 self.assertEqual(pprint.pformat(special, width=1), """\
828bytearray(b'\\x00\\x01\\x02\\x03'
829 b'\\x04\\x05\\x06\\x07'
830 b'\\x08\\t\\n\\x0b'
831 b'\\x0c\\r\\x0e\\x0f')""")
832 self.assertEqual(pprint.pformat({'a': 1, 'b': letters, 'c': 2},
833 width=31), """\
834{'a': 1,
835 'b': bytearray(b'abcdefghijkl'
836 b'mnopqrstuvwx'
837 b'yz'),
838 'c': 2}""")
839 self.assertEqual(pprint.pformat([[[[[letters]]]]], width=37), """\
840[[[[[bytearray(b'abcdefghijklmnop'
841 b'qrstuvwxyz')]]]]]""")
842 self.assertEqual(pprint.pformat([[[[[special]]]]], width=50), """\
843[[[[[bytearray(b'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07'
844 b'\\x08\\t\\n\\x0b\\x0c\\r\\x0e\\x0f')]]]]]""")
845
Florent Xiclunad6da90f2012-07-21 11:17:38 +0200846
Fred Drakeaee113d2002-04-02 05:08:35 +0000847class DottedPrettyPrinter(pprint.PrettyPrinter):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000848
Fred Drakeaee113d2002-04-02 05:08:35 +0000849 def format(self, object, context, maxlevels, level):
850 if isinstance(object, str):
851 if ' ' in object:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000852 return repr(object), 1, 0
Fred Drakeaee113d2002-04-02 05:08:35 +0000853 else:
854 return object, 0, 0
855 else:
856 return pprint.PrettyPrinter.format(
857 self, object, context, maxlevels, level)
858
859
Fred Drake2e2be372001-09-20 21:33:42 +0000860def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000861 test.support.run_unittest(QueryTestCase)
Fred Drake2e2be372001-09-20 21:33:42 +0000862
863
864if __name__ == "__main__":
865 test_main()