Debian Codegraph @

tests/test_pretty.py

raw
1 # coding: utf-8
2 """Tests for IPython.lib.pretty."""
3
4 # Copyright (c) IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
6
7
8 from collections import Counter, defaultdict, deque, OrderedDict, UserList
9 import os
10 import pytest
11 import types
12 import string
13 import sys
14 import unittest
15
16 import pytest
17
18 from IPython.lib import pretty
19
20 from io import StringIO
21
22
23 class MyList(object):
24 def __init__(self, content):
25 self.content = content
26
27 def _repr_pretty_(self, p, cycle):
28 if cycle:
29 p.text("MyList(...)")
30 else:
31 with p.group(3, "MyList(", ")"):
32 for i, child in enumerate(self.content):
33 if i:
34 p.text(",")
35 p.breakable()
36 else:
37 p.breakable("")
38 p.pretty(child)
39
40
41 class MyDict(dict):
42 def _repr_pretty_(self, p, cycle):
43 p.text("MyDict(...)")
44
45
46 class MyObj(object):
47 def somemethod(self):
48 pass
49
50
51 class Dummy1(object):
52 def _repr_pretty_(self, p, cycle):
53 p.text("Dummy1(...)")
54
55
56 class Dummy2(Dummy1):
57 _repr_pretty_ = None
58
59
60 class NoModule(object):
61 pass
62
63
64 NoModule.__module__ = None
65
66
67 class Breaking(object):
68 def _repr_pretty_(self, p, cycle):
69 with p.group(4, "TG: ", ":"):
70 p.text("Breaking(")
71 p.break_()
72 p.text(")")
73
74
75 class BreakingRepr(object):
76 def __repr__(self):
77 return "Breaking(\n)"
78
79
80 class BadRepr(object):
81 def __repr__(self):
82 return 1 / 0
83
84
85 def test_indentation():
86 """Test correct indentation in groups"""
87 count = 40
88 gotoutput = pretty.pretty(MyList(range(count)))
89 expectedoutput = "MyList(\n" + ",\n".join(" %d" % i for i in range(count)) + ")"
90
91 assert gotoutput == expectedoutput
92
93
94 def test_dispatch():
95 """
96 Test correct dispatching: The _repr_pretty_ method for MyDict
97 must be found before the registered printer for dict.
98 """
99 gotoutput = pretty.pretty(MyDict())
100 expectedoutput = "MyDict(...)"
101
102 assert gotoutput == expectedoutput
103
104
105 def test_callability_checking():
106 """
107 Test that the _repr_pretty_ method is tested for callability and skipped if
108 not.
109 """
110 gotoutput = pretty.pretty(Dummy2())
111 expectedoutput = "Dummy1(...)"
112
113 assert gotoutput == expectedoutput
114
115
116 @pytest.mark.parametrize(
117 "obj,expected_output",
118 zip(
119 [
120 set(),
121 frozenset(),
122 set([1]),
123 frozenset([1]),
124 set([1, 2]),
125 frozenset([1, 2]),
126 set([-1, -2, -3]),
127 ],
128 [
129 "set()",
130 "frozenset()",
131 "{1}",
132 "frozenset({1})",
133 "{1, 2}",
134 "frozenset({1, 2})",
135 "{-3, -2, -1}",
136 ],
137 ),
138 )
139 def test_sets(obj, expected_output):
140 """
141 Test that set and frozenset use Python 3 formatting.
142 """
143 got_output = pretty.pretty(obj)
144 assert got_output == expected_output
145
146
147 def test_pprint_heap_allocated_type():
148 """
149 Test that pprint works for heap allocated types.
150 """
151 module_name = "xxlimited_35"
152 expected_output = "xxlimited_35.Null"
153 xxlimited = pytest.importorskip(module_name)
154 output = pretty.pretty(xxlimited.Null)
155 assert output == expected_output
156
157
158 def test_pprint_nomod():
159 """
160 Test that pprint works for classes with no __module__.
161 """
162 output = pretty.pretty(NoModule)
163 assert output == "NoModule"
164
165
166 def test_pprint_break():
167 """
168 Test that p.break_ produces expected output
169 """
170 output = pretty.pretty(Breaking())
171 expected = "TG: Breaking(\n ):"
172 assert output == expected
173
174
175 def test_pprint_break_repr():
176 """
177 Test that p.break_ is used in repr
178 """
179 output = pretty.pretty([[BreakingRepr()]])
180 expected = "[[Breaking(\n )]]"
181 assert output == expected
182
183 output = pretty.pretty([[BreakingRepr()] * 2])
184 expected = "[[Breaking(\n ),\n Breaking(\n )]]"
185 assert output == expected
186
187
188 def test_bad_repr():
189 """Don't catch bad repr errors"""
190 with pytest.raises(ZeroDivisionError):
191 pretty.pretty(BadRepr())
192
193
194 class BadException(Exception):
195 def __str__(self):
196 return -1
197
198
199 class ReallyBadRepr(object):
200 __module__ = 1
201
202 @property
203 def __class__(self):
204 raise ValueError("I am horrible")
205
206 def __repr__(self):
207 raise BadException()
208
209
210 def test_really_bad_repr():
211 with pytest.raises(BadException):
212 pretty.pretty(ReallyBadRepr())
213
214
215 class SA(object):
216 pass
217
218
219 class SB(SA):
220 pass
221
222
223 class TestsPretty(unittest.TestCase):
224 def test_super_repr(self):
225 # "<super: module_name.SA, None>"
226 output = pretty.pretty(super(SA))
227 self.assertRegex(output, r"<super: \S+.SA, None>")
228
229 # "<super: module_name.SA, <module_name.SB at 0x...>>"
230 sb = SB()
231 output = pretty.pretty(super(SA, sb))
232 self.assertRegex(output, r"<super: \S+.SA,\s+<\S+.SB at 0x\S+>>")
233
234 def test_long_list(self):
235 lis = list(range(10000))
236 p = pretty.pretty(lis)
237 last2 = p.rsplit("\n", 2)[-2:]
238 self.assertEqual(last2, [" 999,", " ...]"])
239
240 def test_long_set(self):
241 s = set(range(10000))
242 p = pretty.pretty(s)
243 last2 = p.rsplit("\n", 2)[-2:]
244 self.assertEqual(last2, [" 999,", " ...}"])
245
246 def test_long_tuple(self):
247 tup = tuple(range(10000))
248 p = pretty.pretty(tup)
249 last2 = p.rsplit("\n", 2)[-2:]
250 self.assertEqual(last2, [" 999,", " ...)"])
251
252 def test_long_dict(self):
253 d = {n: n for n in range(10000)}
254 p = pretty.pretty(d)
255 last2 = p.rsplit("\n", 2)[-2:]
256 self.assertEqual(last2, [" 999: 999,", " ...}"])
257
258 def test_unbound_method(self):
259 output = pretty.pretty(MyObj.somemethod)
260 self.assertIn("MyObj.somemethod", output)
261
262
263 class MetaClass(type):
264 def __new__(cls, name):
265 return type.__new__(cls, name, (object,), {"name": name})
266
267 def __repr__(self):
268 return "[CUSTOM REPR FOR CLASS %s]" % self.name
269
270
271 ClassWithMeta = MetaClass("ClassWithMeta")
272
273
274 def test_metaclass_repr():
275 output = pretty.pretty(ClassWithMeta)
276 assert output == "[CUSTOM REPR FOR CLASS ClassWithMeta]"
277
278
279 def test_unicode_repr():
280 u = "üniçodé"
281 ustr = u
282
283 class C(object):
284 def __repr__(self):
285 return ustr
286
287 c = C()
288 p = pretty.pretty(c)
289 assert p == u
290 p = pretty.pretty([c])
291 assert p == "[%s]" % u
292
293
294 def test_basic_class():
295 def type_pprint_wrapper(obj, p, cycle):
296 if obj is MyObj:
297 type_pprint_wrapper.called = True
298 return pretty._type_pprint(obj, p, cycle)
299
300 type_pprint_wrapper.called = False
301
302 stream = StringIO()
303 printer = pretty.RepresentationPrinter(stream)
304 printer.type_pprinters[type] = type_pprint_wrapper
305 printer.pretty(MyObj)
306 printer.flush()
307 output = stream.getvalue()
308
309 assert output == "%s.MyObj" % __name__
310 assert type_pprint_wrapper.called is True
311
312
313 def test_collections_userlist():
314 # Create userlist with cycle
315 a = UserList()
316 a.append(a)
317
318 cases = [
319 (UserList(), "UserList([])"),
320 (
321 UserList(i for i in range(1000, 1020)),
322 "UserList([1000,\n"
323 " 1001,\n"
324 " 1002,\n"
325 " 1003,\n"
326 " 1004,\n"
327 " 1005,\n"
328 " 1006,\n"
329 " 1007,\n"
330 " 1008,\n"
331 " 1009,\n"
332 " 1010,\n"
333 " 1011,\n"
334 " 1012,\n"
335 " 1013,\n"
336 " 1014,\n"
337 " 1015,\n"
338 " 1016,\n"
339 " 1017,\n"
340 " 1018,\n"
341 " 1019])",
342 ),
343 (a, "UserList([UserList(...)])"),
344 ]
345 for obj, expected in cases:
346 assert pretty.pretty(obj) == expected
347
348
349 # TODO : pytest.mark.parametrise once nose is gone.
350 def test_collections_defaultdict():
351 # Create defaultdicts with cycles
352 a = defaultdict()
353 a.default_factory = a
354 b = defaultdict(list)
355 b["key"] = b
356
357 # Dictionary order cannot be relied on, test against single keys.
358 cases = [
359 (defaultdict(list), "defaultdict(list, {})"),
360 (
361 defaultdict(list, {"key": "-" * 50}),
362 "defaultdict(list,\n"
363 " {'key': '--------------------------------------------------'})",
364 ),
365 (a, "defaultdict(defaultdict(...), {})"),
366 (b, "defaultdict(list, {'key': defaultdict(...)})"),
367 ]
368 for obj, expected in cases:
369 assert pretty.pretty(obj) == expected
370
371
372 # TODO : pytest.mark.parametrise once nose is gone.
373 def test_collections_ordereddict():
374 # Create OrderedDict with cycle
375 a = OrderedDict()
376 a["key"] = a
377
378 cases = [
379 (OrderedDict(), "OrderedDict()"),
380 (
381 OrderedDict((i, i) for i in range(1000, 1010)),
382 "OrderedDict([(1000, 1000),\n"
383 " (1001, 1001),\n"
384 " (1002, 1002),\n"
385 " (1003, 1003),\n"
386 " (1004, 1004),\n"
387 " (1005, 1005),\n"
388 " (1006, 1006),\n"
389 " (1007, 1007),\n"
390 " (1008, 1008),\n"
391 " (1009, 1009)])",
392 ),
393 (a, "OrderedDict([('key', OrderedDict(...))])"),
394 ]
395 for obj, expected in cases:
396 assert pretty.pretty(obj) == expected
397
398
399 # TODO : pytest.mark.parametrise once nose is gone.
400 def test_collections_deque():
401 # Create deque with cycle
402 a = deque()
403 a.append(a)
404
405 cases = [
406 (deque(), "deque([])"),
407 (
408 deque(i for i in range(1000, 1020)),
409 "deque([1000,\n"
410 " 1001,\n"
411 " 1002,\n"
412 " 1003,\n"
413 " 1004,\n"
414 " 1005,\n"
415 " 1006,\n"
416 " 1007,\n"
417 " 1008,\n"
418 " 1009,\n"
419 " 1010,\n"
420 " 1011,\n"
421 " 1012,\n"
422 " 1013,\n"
423 " 1014,\n"
424 " 1015,\n"
425 " 1016,\n"
426 " 1017,\n"
427 " 1018,\n"
428 " 1019])",
429 ),
430 (a, "deque([deque(...)])"),
431 ]
432 for obj, expected in cases:
433 assert pretty.pretty(obj) == expected
434
435
436 # TODO : pytest.mark.parametrise once nose is gone.
437 def test_collections_counter():
438 class MyCounter(Counter):
439 pass
440
441 cases = [
442 (Counter(), "Counter()"),
443 (Counter(a=1), "Counter({'a': 1})"),
444 (MyCounter(a=1), "MyCounter({'a': 1})"),
445 (Counter(a=1, c=22), "Counter({'c': 22, 'a': 1})"),
446 ]
447 for obj, expected in cases:
448 assert pretty.pretty(obj) == expected
449
450
451 # TODO : pytest.mark.parametrise once nose is gone.
452 def test_mappingproxy():
453 MP = types.MappingProxyType
454 underlying_dict = {}
455 mp_recursive = MP(underlying_dict)
456 underlying_dict[2] = mp_recursive
457 underlying_dict[3] = underlying_dict
458
459 cases = [
460 (MP({}), "mappingproxy({})"),
461 (MP({None: MP({})}), "mappingproxy({None: mappingproxy({})})"),
462 (
463 MP({k: k.upper() for k in string.ascii_lowercase}),
464 "mappingproxy({'a': 'A',\n"
465 " 'b': 'B',\n"
466 " 'c': 'C',\n"
467 " 'd': 'D',\n"
468 " 'e': 'E',\n"
469 " 'f': 'F',\n"
470 " 'g': 'G',\n"
471 " 'h': 'H',\n"
472 " 'i': 'I',\n"
473 " 'j': 'J',\n"
474 " 'k': 'K',\n"
475 " 'l': 'L',\n"
476 " 'm': 'M',\n"
477 " 'n': 'N',\n"
478 " 'o': 'O',\n"
479 " 'p': 'P',\n"
480 " 'q': 'Q',\n"
481 " 'r': 'R',\n"
482 " 's': 'S',\n"
483 " 't': 'T',\n"
484 " 'u': 'U',\n"
485 " 'v': 'V',\n"
486 " 'w': 'W',\n"
487 " 'x': 'X',\n"
488 " 'y': 'Y',\n"
489 " 'z': 'Z'})",
490 ),
491 (mp_recursive, "mappingproxy({2: {...}, 3: {2: {...}, 3: {...}}})"),
492 (underlying_dict, "{2: mappingproxy({2: {...}, 3: {...}}), 3: {...}}"),
493 ]
494 for obj, expected in cases:
495 assert pretty.pretty(obj) == expected
496
497
498 # TODO : pytest.mark.parametrise once nose is gone.
499 def test_simplenamespace():
500 SN = types.SimpleNamespace
501
502 sn_recursive = SN()
503 sn_recursive.first = sn_recursive
504 sn_recursive.second = sn_recursive
505 cases = [
506 (SN(), "namespace()"),
507 (SN(x=SN()), "namespace(x=namespace())"),
508 (
509 SN(a_long_name=[SN(s=string.ascii_lowercase)] * 3, a_short_name=None),
510 "namespace(a_long_name=[namespace(s='abcdefghijklmnopqrstuvwxyz'),\n"
511 " namespace(s='abcdefghijklmnopqrstuvwxyz'),\n"
512 " namespace(s='abcdefghijklmnopqrstuvwxyz')],\n"
513 " a_short_name=None)",
514 ),
515 (sn_recursive, "namespace(first=namespace(...), second=namespace(...))"),
516 ]
517 for obj, expected in cases:
518 assert pretty.pretty(obj) == expected
519
520
521 @pytest.mark.skipif(sys.version_info[1] == 12, reason="issue on old-deps + python 3.12")
522 def test_pretty_environ():
523 dict_repr = pretty.pretty(dict(os.environ))
524 # reindent to align with 'environ' prefix
525 dict_indented = dict_repr.replace("\n", "\n" + (" " * len("environ")))
526 env_repr = pretty.pretty(os.environ)
527 assert env_repr == "environ" + dict_indented
528
529
530 def test_function_pretty():
531 "Test pretty print of function"
532 # posixpath is a pure python module, its interface is consistent
533 # across Python distributions
534
535 import posixpath
536
537 if sys.version_info > (3, 15):
538 assert pretty.pretty(posixpath.join) == "<function posixpath.join(a, /, *p)>"
539 else:
540 assert pretty.pretty(posixpath.join) == "<function posixpath.join(a, *p)>"
541
542 # custom function
543 def meaning_of_life(question=None):
544 if question:
545 return 42
546 return "Don't panic"
547
548 assert "meaning_of_life(question=None)" in pretty.pretty(meaning_of_life)
549
550
551 def test_annotated_function_pretty():
552 "Test pretty print of a function with PEP-649 annotations"
553 # Confirm that the name is not in scope
554 try:
555 b
556 except NameError:
557 pass
558 else:
559 assert False, "Unexpected 'b' found in scope"
560 try:
561 def f(a: b): pass
562 except NameError as e:
563 if e.name == 'b':
564 # PEP-649 not available
565 return
566 raise
567 # Check whether __future__.annotations is in effect
568 # It probably shouldn't be, but to be sure:
569 import __future__
570 if f.__code__.co_flags & __future__.annotations.compiler_flag:
571 assert "f(a: 'b')" in pretty.pretty(f)
572 else:
573 assert "f(a: b)" in pretty.pretty(f)
574
575
576 class OrderedCounter(Counter, OrderedDict):
577 "Counter that remembers the order elements are first encountered"
578
579 def __repr__(self):
580 return "%s(%r)" % (self.__class__.__name__, OrderedDict(self))
581
582 def __reduce__(self):
583 return self.__class__, (OrderedDict(self),)
584
585
586 class MySet(set): # Override repr of a basic type
587 def __repr__(self):
588 return "mine"
589
590
591 def test_custom_repr():
592 """A custom repr should override a pretty printer for a parent type"""
593 oc = OrderedCounter("abracadabra")
594 assert "OrderedCounter(OrderedDict" in pretty.pretty(oc)
595
596 assert pretty.pretty(MySet()) == "mine"