Debian Codegraph @

Lib/test/test_reprlib.py

raw
1 """
2 Test cases for the repr module
3 Nick Mathewson
4 """
5
6 import sys
7 import os
8 import shutil
9 import importlib
10 import importlib.util
11 import unittest
12 import textwrap
13
14 from test.support import verbose
15 from test.support.os_helper import create_empty_file
16 from reprlib import repr as r # Don't shadow builtin repr
17 from reprlib import Repr
18 from reprlib import recursive_repr
19
20
21 def nestedTuple(nesting):
22 t = ()
23 for i in range(nesting):
24 t = (t,)
25 return t
26
27 class ReprTests(unittest.TestCase):
28
29 def test_init_kwargs(self):
30 example_kwargs = {
31 "maxlevel": 101,
32 "maxtuple": 102,
33 "maxlist": 103,
34 "maxarray": 104,
35 "maxdict": 105,
36 "maxset": 106,
37 "maxfrozenset": 107,
38 "maxdeque": 108,
39 "maxstring": 109,
40 "maxlong": 110,
41 "maxother": 111,
42 "fillvalue": "x" * 112,
43 "indent": "x" * 113,
44 }
45 r1 = Repr()
46 for attr, val in example_kwargs.items():
47 setattr(r1, attr, val)
48 r2 = Repr(**example_kwargs)
49 for attr in example_kwargs:
50 self.assertEqual(getattr(r1, attr), getattr(r2, attr), msg=attr)
51
52 def test_string(self):
53 eq = self.assertEqual
54 eq(r("abc"), "'abc'")
55 eq(r("abcdefghijklmnop"),"'abcdefghijklmnop'")
56
57 s = "a"*30+"b"*30
58 expected = repr(s)[:13] + "..." + repr(s)[-14:]
59 eq(r(s), expected)
60
61 eq(r("\"'"), repr("\"'"))
62 s = "\""*30+"'"*100
63 expected = repr(s)[:13] + "..." + repr(s)[-14:]
64 eq(r(s), expected)
65
66 def test_tuple(self):
67 eq = self.assertEqual
68 eq(r((1,)), "(1,)")
69
70 t3 = (1, 2, 3)
71 eq(r(t3), "(1, 2, 3)")
72
73 r2 = Repr()
74 r2.maxtuple = 2
75 expected = repr(t3)[:-2] + "...)"
76 eq(r2.repr(t3), expected)
77
78 # modified fillvalue:
79 r3 = Repr()
80 r3.fillvalue = '+++'
81 r3.maxtuple = 2
82 expected = repr(t3)[:-2] + "+++)"
83 eq(r3.repr(t3), expected)
84
85 def test_container(self):
86 from array import array
87 from collections import deque
88
89 eq = self.assertEqual
90 # Tuples give up after 6 elements
91 eq(r(()), "()")
92 eq(r((1,)), "(1,)")
93 eq(r((1, 2, 3)), "(1, 2, 3)")
94 eq(r((1, 2, 3, 4, 5, 6)), "(1, 2, 3, 4, 5, 6)")
95 eq(r((1, 2, 3, 4, 5, 6, 7)), "(1, 2, 3, 4, 5, 6, ...)")
96
97 # Lists give up after 6 as well
98 eq(r([]), "[]")
99 eq(r([1]), "[1]")
100 eq(r([1, 2, 3]), "[1, 2, 3]")
101 eq(r([1, 2, 3, 4, 5, 6]), "[1, 2, 3, 4, 5, 6]")
102 eq(r([1, 2, 3, 4, 5, 6, 7]), "[1, 2, 3, 4, 5, 6, ...]")
103
104 # Sets give up after 6 as well
105 eq(r(set([])), "set()")
106 eq(r(set([1])), "{1}")
107 eq(r(set([1, 2, 3])), "{1, 2, 3}")
108 eq(r(set([1, 2, 3, 4, 5, 6])), "{1, 2, 3, 4, 5, 6}")
109 eq(r(set([1, 2, 3, 4, 5, 6, 7])), "{1, 2, 3, 4, 5, 6, ...}")
110
111 # Frozensets give up after 6 as well
112 eq(r(frozenset([])), "frozenset()")
113 eq(r(frozenset([1])), "frozenset({1})")
114 eq(r(frozenset([1, 2, 3])), "frozenset({1, 2, 3})")
115 eq(r(frozenset([1, 2, 3, 4, 5, 6])), "frozenset({1, 2, 3, 4, 5, 6})")
116 eq(r(frozenset([1, 2, 3, 4, 5, 6, 7])), "frozenset({1, 2, 3, 4, 5, 6, ...})")
117
118 # collections.deque after 6
119 eq(r(deque([1, 2, 3, 4, 5, 6, 7])), "deque([1, 2, 3, 4, 5, 6, ...])")
120
121 # Dictionaries give up after 4.
122 eq(r({}), "{}")
123 d = {'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4}
124 eq(r(d), "{'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4}")
125 d['arthur'] = 1
126 eq(r(d), "{'alice': 1, 'arthur': 1, 'bob': 2, 'charles': 3, ...}")
127
128 # array.array after 5.
129 eq(r(array('i')), "array('i')")
130 eq(r(array('i', [1])), "array('i', [1])")
131 eq(r(array('i', [1, 2])), "array('i', [1, 2])")
132 eq(r(array('i', [1, 2, 3])), "array('i', [1, 2, 3])")
133 eq(r(array('i', [1, 2, 3, 4])), "array('i', [1, 2, 3, 4])")
134 eq(r(array('i', [1, 2, 3, 4, 5])), "array('i', [1, 2, 3, 4, 5])")
135 eq(r(array('i', [1, 2, 3, 4, 5, 6])),
136 "array('i', [1, 2, 3, 4, 5, ...])")
137
138 def test_set_literal(self):
139 eq = self.assertEqual
140 eq(r({1}), "{1}")
141 eq(r({1, 2, 3}), "{1, 2, 3}")
142 eq(r({1, 2, 3, 4, 5, 6}), "{1, 2, 3, 4, 5, 6}")
143 eq(r({1, 2, 3, 4, 5, 6, 7}), "{1, 2, 3, 4, 5, 6, ...}")
144
145 def test_frozenset(self):
146 eq = self.assertEqual
147 eq(r(frozenset({1})), "frozenset({1})")
148 eq(r(frozenset({1, 2, 3})), "frozenset({1, 2, 3})")
149 eq(r(frozenset({1, 2, 3, 4, 5, 6})), "frozenset({1, 2, 3, 4, 5, 6})")
150 eq(r(frozenset({1, 2, 3, 4, 5, 6, 7})), "frozenset({1, 2, 3, 4, 5, 6, ...})")
151
152 def test_numbers(self):
153 for x in [123, 1.0 / 3]:
154 self.assertEqual(r(x), repr(x))
155
156 max_digits = sys.get_int_max_str_digits()
157 for k in [100, max_digits - 1]:
158 with self.subTest(f'10 ** {k}', k=k):
159 n = 10 ** k
160 expected = repr(n)[:18] + "..." + repr(n)[-19:]
161 self.assertEqual(r(n), expected)
162
163 def re_msg(n, d):
164 return (rf'<{n.__class__.__name__} instance with roughly {d} '
165 rf'digits \(limit at {max_digits}\) at 0x[a-f0-9]+>')
166
167 k = max_digits
168 with self.subTest(f'10 ** {k}', k=k):
169 n = 10 ** k
170 self.assertRaises(ValueError, repr, n)
171 self.assertRegex(r(n), re_msg(n, k + 1))
172
173 for k in [max_digits + 1, 2 * max_digits]:
174 self.assertGreater(k, 100)
175 with self.subTest(f'10 ** {k}', k=k):
176 n = 10 ** k
177 self.assertRaises(ValueError, repr, n)
178 self.assertRegex(r(n), re_msg(n, k + 1))
179 with self.subTest(f'10 ** {k} - 1', k=k):
180 n = 10 ** k - 1
181 # Here, since math.log10(n) == math.log10(n-1),
182 # the number of digits of n - 1 is overestimated.
183 self.assertRaises(ValueError, repr, n)
184 self.assertRegex(r(n), re_msg(n, k + 1))
185
186 def test_instance(self):
187 eq = self.assertEqual
188 i1 = ClassWithRepr("a")
189 eq(r(i1), repr(i1))
190
191 i2 = ClassWithRepr("x"*1000)
192 expected = repr(i2)[:13] + "..." + repr(i2)[-14:]
193 eq(r(i2), expected)
194
195 i3 = ClassWithFailingRepr()
196 eq(r(i3), ("<ClassWithFailingRepr instance at %#x>"%id(i3)))
197
198 s = r(ClassWithFailingRepr)
199 self.assertTrue(s.startswith("<class "))
200 self.assertTrue(s.endswith(">"))
201 self.assertIn(s.find("..."), [12, 13])
202
203 def test_lambda(self):
204 r = repr(lambda x: x)
205 self.assertTrue(r.startswith("<function ReprTests.test_lambda.<locals>.<lambda"), r)
206 # XXX anonymous functions? see func_repr
207
208 def test_builtin_function(self):
209 eq = self.assertEqual
210 # Functions
211 eq(repr(hash), '<built-in function hash>')
212 # Methods
213 self.assertTrue(repr(''.split).startswith(
214 '<built-in method split of str object at 0x'))
215
216 def test_range(self):
217 eq = self.assertEqual
218 eq(repr(range(1)), 'range(0, 1)')
219 eq(repr(range(1, 2)), 'range(1, 2)')
220 eq(repr(range(1, 4, 3)), 'range(1, 4, 3)')
221
222 def test_nesting(self):
223 eq = self.assertEqual
224 # everything is meant to give up after 6 levels.
225 eq(r([[[[[[[]]]]]]]), "[[[[[[[]]]]]]]")
226 eq(r([[[[[[[[]]]]]]]]), "[[[[[[[...]]]]]]]")
227
228 eq(r(nestedTuple(6)), "(((((((),),),),),),)")
229 eq(r(nestedTuple(7)), "(((((((...),),),),),),)")
230
231 eq(r({ nestedTuple(5) : nestedTuple(5) }),
232 "{((((((),),),),),): ((((((),),),),),)}")
233 eq(r({ nestedTuple(6) : nestedTuple(6) }),
234 "{((((((...),),),),),): ((((((...),),),),),)}")
235
236 eq(r([[[[[[{}]]]]]]), "[[[[[[{}]]]]]]")
237 eq(r([[[[[[[{}]]]]]]]), "[[[[[[[...]]]]]]]")
238
239 def test_cell(self):
240 def get_cell():
241 x = 42
242 def inner():
243 return x
244 return inner
245 x = get_cell().__closure__[0]
246 self.assertRegex(repr(x), r'<cell at 0x[0-9A-Fa-f]+: '
247 r'int object at 0x[0-9A-Fa-f]+>')
248 self.assertRegex(r(x), r'<cell at 0x.*\.\.\..*>')
249
250 def test_descriptors(self):
251 eq = self.assertEqual
252 # method descriptors
253 eq(repr(dict.items), "<method 'items' of 'dict' objects>")
254 # XXX member descriptors
255 # XXX attribute descriptors
256 # XXX slot descriptors
257 # static and class methods
258 class C:
259 def foo(cls): pass
260 x = staticmethod(C.foo)
261 self.assertEqual(repr(x), f'<staticmethod({C.foo!r})>')
262 x = classmethod(C.foo)
263 self.assertEqual(repr(x), f'<classmethod({C.foo!r})>')
264
265 def test_unsortable(self):
266 # Repr.repr() used to call sorted() on sets, frozensets and dicts
267 # without taking into account that not all objects are comparable
268 x = set([1j, 2j, 3j])
269 y = frozenset(x)
270 z = {1j: 1, 2j: 2}
271 r(x)
272 r(y)
273 r(z)
274
275 def test_valid_indent(self):
276 test_cases = [
277 {
278 'object': (),
279 'tests': (
280 (dict(indent=None), '()'),
281 (dict(indent=False), '()'),
282 (dict(indent=True), '()'),
283 (dict(indent=0), '()'),
284 (dict(indent=1), '()'),
285 (dict(indent=4), '()'),
286 (dict(indent=4, maxlevel=2), '()'),
287 (dict(indent=''), '()'),
288 (dict(indent='-->'), '()'),
289 (dict(indent='....'), '()'),
290 ),
291 },
292 {
293 'object': '',
294 'tests': (
295 (dict(indent=None), "''"),
296 (dict(indent=False), "''"),
297 (dict(indent=True), "''"),
298 (dict(indent=0), "''"),
299 (dict(indent=1), "''"),
300 (dict(indent=4), "''"),
301 (dict(indent=4, maxlevel=2), "''"),
302 (dict(indent=''), "''"),
303 (dict(indent='-->'), "''"),
304 (dict(indent='....'), "''"),
305 ),
306 },
307 {
308 'object': [1, 'spam', {'eggs': True, 'ham': []}],
309 'tests': (
310 (dict(indent=None), '''\
311 [1, 'spam', {'eggs': True, 'ham': []}]'''),
312 (dict(indent=False), '''\
313 [
314 1,
315 'spam',
316 {
317 'eggs': True,
318 'ham': [],
319 },
320 ]'''),
321 (dict(indent=True), '''\
322 [
323 1,
324 'spam',
325 {
326 'eggs': True,
327 'ham': [],
328 },
329 ]'''),
330 (dict(indent=0), '''\
331 [
332 1,
333 'spam',
334 {
335 'eggs': True,
336 'ham': [],
337 },
338 ]'''),
339 (dict(indent=1), '''\
340 [
341 1,
342 'spam',
343 {
344 'eggs': True,
345 'ham': [],
346 },
347 ]'''),
348 (dict(indent=4), '''\
349 [
350 1,
351 'spam',
352 {
353 'eggs': True,
354 'ham': [],
355 },
356 ]'''),
357 (dict(indent=4, maxlevel=2), '''\
358 [
359 1,
360 'spam',
361 {
362 'eggs': True,
363 'ham': [],
364 },
365 ]'''),
366 (dict(indent=''), '''\
367 [
368 1,
369 'spam',
370 {
371 'eggs': True,
372 'ham': [],
373 },
374 ]'''),
375 (dict(indent='-->'), '''\
376 [
377 -->1,
378 -->'spam',
379 -->{
380 -->-->'eggs': True,
381 -->-->'ham': [],
382 -->},
383 ]'''),
384 (dict(indent='....'), '''\
385 [
386 ....1,
387 ....'spam',
388 ....{
389 ........'eggs': True,
390 ........'ham': [],
391 ....},
392 ]'''),
393 ),
394 },
395 {
396 'object': {
397 1: 'two',
398 b'three': [
399 (4.5, 6.25),
400 [set((8, 9)), frozenset((10, 11))],
401 ],
402 },
403 'tests': (
404 (dict(indent=None), '''\
405 {1: 'two', b'three': [(4.5, 6.25), [{8, 9}, frozenset({10, 11})]]}'''),
406 (dict(indent=False), '''\
407 {
408 1: 'two',
409 b'three': [
410 (
411 4.5,
412 6.25,
413 ),
414 [
415 {
416 8,
417 9,
418 },
419 frozenset({
420 10,
421 11,
422 }),
423 ],
424 ],
425 }'''),
426 (dict(indent=True), '''\
427 {
428 1: 'two',
429 b'three': [
430 (
431 4.5,
432 6.25,
433 ),
434 [
435 {
436 8,
437 9,
438 },
439 frozenset({
440 10,
441 11,
442 }),
443 ],
444 ],
445 }'''),
446 (dict(indent=0), '''\
447 {
448 1: 'two',
449 b'three': [
450 (
451 4.5,
452 6.25,
453 ),
454 [
455 {
456 8,
457 9,
458 },
459 frozenset({
460 10,
461 11,
462 }),
463 ],
464 ],
465 }'''),
466 (dict(indent=1), '''\
467 {
468 1: 'two',
469 b'three': [
470 (
471 4.5,
472 6.25,
473 ),
474 [
475 {
476 8,
477 9,
478 },
479 frozenset({
480 10,
481 11,
482 }),
483 ],
484 ],
485 }'''),
486 (dict(indent=4), '''\
487 {
488 1: 'two',
489 b'three': [
490 (
491 4.5,
492 6.25,
493 ),
494 [
495 {
496 8,
497 9,
498 },
499 frozenset({
500 10,
501 11,
502 }),
503 ],
504 ],
505 }'''),
506 (dict(indent=4, maxlevel=2), '''\
507 {
508 1: 'two',
509 b'three': [
510 (...),
511 [...],
512 ],
513 }'''),
514 (dict(indent=''), '''\
515 {
516 1: 'two',
517 b'three': [
518 (
519 4.5,
520 6.25,
521 ),
522 [
523 {
524 8,
525 9,
526 },
527 frozenset({
528 10,
529 11,
530 }),
531 ],
532 ],
533 }'''),
534 (dict(indent='-->'), '''\
535 {
536 -->1: 'two',
537 -->b'three': [
538 -->-->(
539 -->-->-->4.5,
540 -->-->-->6.25,
541 -->-->),
542 -->-->[
543 -->-->-->{
544 -->-->-->-->8,
545 -->-->-->-->9,
546 -->-->-->},
547 -->-->-->frozenset({
548 -->-->-->-->10,
549 -->-->-->-->11,
550 -->-->-->}),
551 -->-->],
552 -->],
553 }'''),
554 (dict(indent='....'), '''\
555 {
556 ....1: 'two',
557 ....b'three': [
558 ........(
559 ............4.5,
560 ............6.25,
561 ........),
562 ........[
563 ............{
564 ................8,
565 ................9,
566 ............},
567 ............frozenset({
568 ................10,
569 ................11,
570 ............}),
571 ........],
572 ....],
573 }'''),
574 ),
575 },
576 ]
577 for test_case in test_cases:
578 with self.subTest(test_object=test_case['object']):
579 for repr_settings, expected_repr in test_case['tests']:
580 with self.subTest(repr_settings=repr_settings):
581 r = Repr()
582 for attribute, value in repr_settings.items():
583 setattr(r, attribute, value)
584 resulting_repr = r.repr(test_case['object'])
585 expected_repr = textwrap.dedent(expected_repr)
586 self.assertEqual(resulting_repr, expected_repr)
587
588 def test_invalid_indent(self):
589 test_object = [1, 'spam', {'eggs': True, 'ham': []}]
590 test_cases = [
591 (-1, (ValueError, '[Nn]egative|[Pp]ositive')),
592 (-4, (ValueError, '[Nn]egative|[Pp]ositive')),
593 ((), (TypeError, None)),
594 ([], (TypeError, None)),
595 ((4,), (TypeError, None)),
596 ([4,], (TypeError, None)),
597 (object(), (TypeError, None)),
598 ]
599 for indent, (expected_error, expected_msg) in test_cases:
600 with self.subTest(indent=indent):
601 r = Repr()
602 r.indent = indent
603 expected_msg = expected_msg or f'{type(indent)}'
604 with self.assertRaisesRegex(expected_error, expected_msg):
605 r.repr(test_object)
606
607 def test_shadowed_stdlib_array(self):
608 # Issue #113570: repr() should not be fooled by an array
609 class array:
610 def __repr__(self):
611 return "not array.array"
612
613 self.assertEqual(r(array()), "not array.array")
614
615 def test_shadowed_builtin(self):
616 # Issue #113570: repr() should not be fooled
617 # by a shadowed builtin function
618 class list:
619 def __repr__(self):
620 return "not builtins.list"
621
622 self.assertEqual(r(list()), "not builtins.list")
623
624 def test_custom_repr(self):
625 class MyRepr(Repr):
626
627 def repr_TextIOWrapper(self, obj, level):
628 if obj.name in {'<stdin>', '<stdout>', '<stderr>'}:
629 return obj.name
630 return repr(obj)
631
632 aRepr = MyRepr()
633 self.assertEqual(aRepr.repr(sys.stdin), "<stdin>")
634
635 def test_custom_repr_class_with_spaces(self):
636 class TypeWithSpaces:
637 pass
638
639 t = TypeWithSpaces()
640 type(t).__name__ = "type with spaces"
641 self.assertEqual(type(t).__name__, "type with spaces")
642
643 class MyRepr(Repr):
644 def repr_type_with_spaces(self, obj, level):
645 return "Type With Spaces"
646
647
648 aRepr = MyRepr()
649 self.assertEqual(aRepr.repr(t), "Type With Spaces")
650
651 def write_file(path, text):
652 with open(path, 'w', encoding='ASCII') as fp:
653 fp.write(text)
654
655 class LongReprTest(unittest.TestCase):
656 longname = 'areallylongpackageandmodulenametotestreprtruncation'
657
658 def setUp(self):
659 self.pkgname = os.path.join(self.longname)
660 self.subpkgname = os.path.join(self.longname, self.longname)
661 # Make the package and subpackage
662 shutil.rmtree(self.pkgname, ignore_errors=True)
663 os.mkdir(self.pkgname)
664 create_empty_file(os.path.join(self.pkgname, '__init__.py'))
665 shutil.rmtree(self.subpkgname, ignore_errors=True)
666 os.mkdir(self.subpkgname)
667 create_empty_file(os.path.join(self.subpkgname, '__init__.py'))
668 # Remember where we are
669 self.here = os.getcwd()
670 sys.path.insert(0, self.here)
671 # When regrtest is run with its -j option, this command alone is not
672 # enough.
673 importlib.invalidate_caches()
674
675 def tearDown(self):
676 actions = []
677 for dirpath, dirnames, filenames in os.walk(self.pkgname):
678 for name in dirnames + filenames:
679 actions.append(os.path.join(dirpath, name))
680 actions.append(self.pkgname)
681 actions.sort()
682 actions.reverse()
683 for p in actions:
684 if os.path.isdir(p):
685 os.rmdir(p)
686 else:
687 os.remove(p)
688 del sys.path[0]
689
690 def _check_path_limitations(self, module_name):
691 # base directory
692 source_path_len = len(self.here)
693 # a path separator + `longname` (twice)
694 source_path_len += 2 * (len(self.longname) + 1)
695 # a path separator + `module_name` + ".py"
696 source_path_len += len(module_name) + 1 + len(".py")
697 cached_path_len = (source_path_len +
698 len(importlib.util.cache_from_source("x.py")) - len("x.py"))
699 if os.name == 'nt' and cached_path_len >= 258:
700 # Under Windows, the max path len is 260 including C's terminating
701 # NUL character.
702 # (see http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx#maxpath)
703 self.skipTest("test paths too long (%d characters) for Windows' 260 character limit"
704 % cached_path_len)
705 elif os.name == 'nt' and verbose:
706 print("cached_path_len =", cached_path_len)
707
708 def test_module(self):
709 self.maxDiff = None
710 self._check_path_limitations(self.pkgname)
711 create_empty_file(os.path.join(self.subpkgname, self.pkgname + '.py'))
712 importlib.invalidate_caches()
713 from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import areallylongpackageandmodulenametotestreprtruncation
714 module = areallylongpackageandmodulenametotestreprtruncation
715 self.assertEqual(repr(module), "<module %r from %r>" % (module.__name__, module.__file__))
716 self.assertEqual(repr(sys), "<module 'sys' (built-in)>")
717
718 def test_type(self):
719 self._check_path_limitations('foo')
720 eq = self.assertEqual
721 write_file(os.path.join(self.subpkgname, 'foo.py'), '''\
722 class foo(object):
723 pass
724 ''')
725 importlib.invalidate_caches()
726 from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import foo
727 eq(repr(foo.foo),
728 "<class '%s.foo'>" % foo.__name__)
729
730 @unittest.skip('need a suitable object')
731 def test_object(self):
732 # XXX Test the repr of a type with a really long tp_name but with no
733 # tp_repr. WIBNI we had ::Inline? :)
734 pass
735
736 def test_class(self):
737 self._check_path_limitations('bar')
738 write_file(os.path.join(self.subpkgname, 'bar.py'), '''\
739 class bar:
740 pass
741 ''')
742 importlib.invalidate_caches()
743 from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import bar
744 # Module name may be prefixed with "test.", depending on how run.
745 self.assertEqual(repr(bar.bar), "<class '%s.bar'>" % bar.__name__)
746
747 def test_instance(self):
748 self._check_path_limitations('baz')
749 write_file(os.path.join(self.subpkgname, 'baz.py'), '''\
750 class baz:
751 pass
752 ''')
753 importlib.invalidate_caches()
754 from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import baz
755 ibaz = baz.baz()
756 self.assertTrue(repr(ibaz).startswith(
757 "<%s.baz object at 0x" % baz.__name__))
758
759 def test_method(self):
760 self._check_path_limitations('qux')
761 eq = self.assertEqual
762 write_file(os.path.join(self.subpkgname, 'qux.py'), '''\
763 class aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:
764 def amethod(self): pass
765 ''')
766 importlib.invalidate_caches()
767 from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import qux
768 # Unbound methods first
769 r = repr(qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod)
770 self.assertTrue(r.startswith('<function aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod'), r)
771 # Bound method next
772 iqux = qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()
773 r = repr(iqux.amethod)
774 self.assertTrue(r.startswith(
775 '<bound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod of <%s.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa object at 0x' \
776 % (qux.__name__,) ), r)
777
778 @unittest.skip('needs a built-in function with a really long name')
779 def test_builtin_function(self):
780 # XXX test built-in functions and methods with really long names
781 pass
782
783 class ClassWithRepr:
784 def __init__(self, s):
785 self.s = s
786 def __repr__(self):
787 return "ClassWithRepr(%r)" % self.s
788
789
790 class ClassWithFailingRepr:
791 def __repr__(self):
792 raise Exception("This should be caught by Repr.repr_instance")
793
794 class MyContainer:
795 'Helper class for TestRecursiveRepr'
796 def __init__(self, values):
797 self.values = list(values)
798 def append(self, value):
799 self.values.append(value)
800 @recursive_repr()
801 def __repr__(self):
802 return '<' + ', '.join(map(str, self.values)) + '>'
803
804 class MyContainer2(MyContainer):
805 @recursive_repr('+++')
806 def __repr__(self):
807 return '<' + ', '.join(map(str, self.values)) + '>'
808
809 class MyContainer3:
810 def __repr__(self):
811 'Test document content'
812 pass
813 wrapped = __repr__
814 wrapper = recursive_repr()(wrapped)
815
816 class TestRecursiveRepr(unittest.TestCase):
817 def test_recursive_repr(self):
818 m = MyContainer(list('abcde'))
819 m.append(m)
820 m.append('x')
821 m.append(m)
822 self.assertEqual(repr(m), '<a, b, c, d, e, ..., x, ...>')
823 m = MyContainer2(list('abcde'))
824 m.append(m)
825 m.append('x')
826 m.append(m)
827 self.assertEqual(repr(m), '<a, b, c, d, e, +++, x, +++>')
828
829 def test_assigned_attributes(self):
830 from functools import WRAPPER_ASSIGNMENTS as assigned
831 wrapped = MyContainer3.wrapped
832 wrapper = MyContainer3.wrapper
833 for name in assigned:
834 self.assertIs(getattr(wrapper, name), getattr(wrapped, name))
835
836 def test__wrapped__(self):
837 class X:
838 def __repr__(self):
839 return 'X()'
840 f = __repr__ # save reference to check it later
841 __repr__ = recursive_repr()(__repr__)
842
843 self.assertIs(X.f, X.__repr__.__wrapped__)
844
845 def test__type_params__(self):
846 class My:
847 @recursive_repr()
848 def __repr__[T: str](self, default: T = '') -> str:
849 return default
850
851 type_params = My().__repr__.__type_params__
852 self.assertEqual(len(type_params), 1)
853 self.assertEqual(type_params[0].__name__, 'T')
854 self.assertEqual(type_params[0].__bound__, str)
855
856 if __name__ == "__main__":
857 unittest.main()