Debian Codegraph @

lib-python/3/test/test_reprlib.py

raw symbols SCIP
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
13 from test.support import verbose
14 from test.support.os_helper import create_empty_file
15 from reprlib import repr as r # Don't shadow builtin repr
16 from reprlib import Repr
17 from reprlib import recursive_repr
18
19
20 def nestedTuple(nesting):
21 t = ()
22 for i in range(nesting):
23 t = (t,)
24 return t
25
26 class ReprTests(unittest.TestCase):
27
28 def test_string(self):
29 eq = self.assertEqual
30 eq(r("abc"), "'abc'")
31 eq(r("abcdefghijklmnop"),"'abcdefghijklmnop'")
32
33 s = "a"*30+"b"*30
34 expected = repr(s)[:13] + "..." + repr(s)[-14:]
35 eq(r(s), expected)
36
37 eq(r("\"'"), repr("\"'"))
38 s = "\""*30+"'"*100
39 expected = repr(s)[:13] + "..." + repr(s)[-14:]
40 eq(r(s), expected)
41
42 def test_tuple(self):
43 eq = self.assertEqual
44 eq(r((1,)), "(1,)")
45
46 t3 = (1, 2, 3)
47 eq(r(t3), "(1, 2, 3)")
48
49 r2 = Repr()
50 r2.maxtuple = 2
51 expected = repr(t3)[:-2] + "...)"
52 eq(r2.repr(t3), expected)
53
54 # modified fillvalue:
55 r3 = Repr()
56 r3.fillvalue = '+++'
57 r3.maxtuple = 2
58 expected = repr(t3)[:-2] + "+++)"
59 eq(r3.repr(t3), expected)
60
61 def test_container(self):
62 from array import array
63 from collections import deque
64
65 eq = self.assertEqual
66 # Tuples give up after 6 elements
67 eq(r(()), "()")
68 eq(r((1,)), "(1,)")
69 eq(r((1, 2, 3)), "(1, 2, 3)")
70 eq(r((1, 2, 3, 4, 5, 6)), "(1, 2, 3, 4, 5, 6)")
71 eq(r((1, 2, 3, 4, 5, 6, 7)), "(1, 2, 3, 4, 5, 6, ...)")
72
73 # Lists give up after 6 as well
74 eq(r([]), "[]")
75 eq(r([1]), "[1]")
76 eq(r([1, 2, 3]), "[1, 2, 3]")
77 eq(r([1, 2, 3, 4, 5, 6]), "[1, 2, 3, 4, 5, 6]")
78 eq(r([1, 2, 3, 4, 5, 6, 7]), "[1, 2, 3, 4, 5, 6, ...]")
79
80 # Sets give up after 6 as well
81 eq(r(set([])), "set()")
82 eq(r(set([1])), "{1}")
83 eq(r(set([1, 2, 3])), "{1, 2, 3}")
84 eq(r(set([1, 2, 3, 4, 5, 6])), "{1, 2, 3, 4, 5, 6}")
85 eq(r(set([1, 2, 3, 4, 5, 6, 7])), "{1, 2, 3, 4, 5, 6, ...}")
86
87 # Frozensets give up after 6 as well
88 eq(r(frozenset([])), "frozenset()")
89 eq(r(frozenset([1])), "frozenset({1})")
90 eq(r(frozenset([1, 2, 3])), "frozenset({1, 2, 3})")
91 eq(r(frozenset([1, 2, 3, 4, 5, 6])), "frozenset({1, 2, 3, 4, 5, 6})")
92 eq(r(frozenset([1, 2, 3, 4, 5, 6, 7])), "frozenset({1, 2, 3, 4, 5, 6, ...})")
93
94 # collections.deque after 6
95 eq(r(deque([1, 2, 3, 4, 5, 6, 7])), "deque([1, 2, 3, 4, 5, 6, ...])")
96
97 # Dictionaries give up after 4.
98 eq(r({}), "{}")
99 d = {'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4}
100 eq(r(d), "{'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4}")
101 d['arthur'] = 1
102 eq(r(d), "{'alice': 1, 'arthur': 1, 'bob': 2, 'charles': 3, ...}")
103
104 # array.array after 5.
105 eq(r(array('i')), "array('i')")
106 eq(r(array('i', [1])), "array('i', [1])")
107 eq(r(array('i', [1, 2])), "array('i', [1, 2])")
108 eq(r(array('i', [1, 2, 3])), "array('i', [1, 2, 3])")
109 eq(r(array('i', [1, 2, 3, 4])), "array('i', [1, 2, 3, 4])")
110 eq(r(array('i', [1, 2, 3, 4, 5])), "array('i', [1, 2, 3, 4, 5])")
111 eq(r(array('i', [1, 2, 3, 4, 5, 6])),
112 "array('i', [1, 2, 3, 4, 5, ...])")
113
114 def test_set_literal(self):
115 eq = self.assertEqual
116 eq(r({1}), "{1}")
117 eq(r({1, 2, 3}), "{1, 2, 3}")
118 eq(r({1, 2, 3, 4, 5, 6}), "{1, 2, 3, 4, 5, 6}")
119 eq(r({1, 2, 3, 4, 5, 6, 7}), "{1, 2, 3, 4, 5, 6, ...}")
120
121 def test_frozenset(self):
122 eq = self.assertEqual
123 eq(r(frozenset({1})), "frozenset({1})")
124 eq(r(frozenset({1, 2, 3})), "frozenset({1, 2, 3})")
125 eq(r(frozenset({1, 2, 3, 4, 5, 6})), "frozenset({1, 2, 3, 4, 5, 6})")
126 eq(r(frozenset({1, 2, 3, 4, 5, 6, 7})), "frozenset({1, 2, 3, 4, 5, 6, ...})")
127
128 def test_numbers(self):
129 eq = self.assertEqual
130 eq(r(123), repr(123))
131 eq(r(123), repr(123))
132 eq(r(1.0/3), repr(1.0/3))
133
134 n = 10**100
135 expected = repr(n)[:18] + "..." + repr(n)[-19:]
136 eq(r(n), expected)
137
138 def test_instance(self):
139 eq = self.assertEqual
140 i1 = ClassWithRepr("a")
141 eq(r(i1), repr(i1))
142
143 i2 = ClassWithRepr("x"*1000)
144 expected = repr(i2)[:13] + "..." + repr(i2)[-14:]
145 eq(r(i2), expected)
146
147 i3 = ClassWithFailingRepr()
148 eq(r(i3), ("<ClassWithFailingRepr instance at %#x>"%id(i3)))
149
150 s = r(ClassWithFailingRepr)
151 self.assertTrue(s.startswith("<class "))
152 self.assertTrue(s.endswith(">"))
153 self.assertIn(s.find("..."), [12, 13])
154
155 def test_lambda(self):
156 r = repr(lambda x: x)
157 self.assertTrue(r.startswith("<function ReprTests.test_lambda.<locals>.<lambda"), r)
158 # XXX anonymous functions? see func_repr
159
160 def test_builtin_function(self):
161 eq = self.assertEqual
162 # Functions
163 eq(repr(hash), '<built-in function hash>')
164 # Methods
165 self.assertTrue(any((
166 # cpython
167 repr(''.split).startswith('<built-in method split of str object at 0x'),
168 # pypy
169 repr(''.split) == "<bound method str.split of ''>",
170 )))
171
172 def test_range(self):
173 eq = self.assertEqual
174 eq(repr(range(1)), 'range(0, 1)')
175 eq(repr(range(1, 2)), 'range(1, 2)')
176 eq(repr(range(1, 4, 3)), 'range(1, 4, 3)')
177
178 def test_nesting(self):
179 eq = self.assertEqual
180 # everything is meant to give up after 6 levels.
181 eq(r([[[[[[[]]]]]]]), "[[[[[[[]]]]]]]")
182 eq(r([[[[[[[[]]]]]]]]), "[[[[[[[...]]]]]]]")
183
184 eq(r(nestedTuple(6)), "(((((((),),),),),),)")
185 eq(r(nestedTuple(7)), "(((((((...),),),),),),)")
186
187 eq(r({ nestedTuple(5) : nestedTuple(5) }),
188 "{((((((),),),),),): ((((((),),),),),)}")
189 eq(r({ nestedTuple(6) : nestedTuple(6) }),
190 "{((((((...),),),),),): ((((((...),),),),),)}")
191
192 eq(r([[[[[[{}]]]]]]), "[[[[[[{}]]]]]]")
193 eq(r([[[[[[[{}]]]]]]]), "[[[[[[[...]]]]]]]")
194
195 def test_cell(self):
196 def get_cell():
197 x = 42
198 def inner():
199 return x
200 return inner
201 x = get_cell().__closure__[0]
202 self.assertRegex(repr(x), r'<cell at 0x[0-9A-Fa-f]+: '
203 r'int object at 0x[0-9A-Fa-f]+>')
204 self.assertRegex(r(x), r'<cell at 0x.*\.\.\..*>')
205
206 def test_descriptors(self):
207 eq = self.assertEqual
208 # method descriptors
209 self.assertTrue(any((
210 # cpython
211 repr(dict.items) == "<method 'items' of 'dict' objects>",
212 # pypy
213 repr(dict.items).startswith("<function dict.items at 0x"),
214 )))
215 # XXX member descriptors
216 # XXX attribute descriptors
217 # XXX slot descriptors
218 # static and class methods
219 class C:
220 def foo(cls): pass
221 x = staticmethod(C.foo)
222 self.assertEqual(repr(x), f'<staticmethod({C.foo!r})>')
223 x = classmethod(C.foo)
224 self.assertEqual(repr(x), f'<classmethod({C.foo!r})>')
225
226 def test_unsortable(self):
227 # Repr.repr() used to call sorted() on sets, frozensets and dicts
228 # without taking into account that not all objects are comparable
229 x = set([1j, 2j, 3j])
230 y = frozenset(x)
231 z = {1j: 1, 2j: 2}
232 r(x)
233 r(y)
234 r(z)
235
236 def write_file(path, text):
237 with open(path, 'w', encoding='ASCII') as fp:
238 fp.write(text)
239
240 class LongReprTest(unittest.TestCase):
241 longname = 'areallylongpackageandmodulenametotestreprtruncation'
242
243 def setUp(self):
244 self.pkgname = os.path.join(self.longname)
245 self.subpkgname = os.path.join(self.longname, self.longname)
246 # Make the package and subpackage
247 shutil.rmtree(self.pkgname, ignore_errors=True)
248 os.mkdir(self.pkgname)
249 create_empty_file(os.path.join(self.pkgname, '__init__.py'))
250 shutil.rmtree(self.subpkgname, ignore_errors=True)
251 os.mkdir(self.subpkgname)
252 create_empty_file(os.path.join(self.subpkgname, '__init__.py'))
253 # Remember where we are
254 self.here = os.getcwd()
255 sys.path.insert(0, self.here)
256 # When regrtest is run with its -j option, this command alone is not
257 # enough.
258 importlib.invalidate_caches()
259
260 def tearDown(self):
261 actions = []
262 for dirpath, dirnames, filenames in os.walk(self.pkgname):
263 for name in dirnames + filenames:
264 actions.append(os.path.join(dirpath, name))
265 actions.append(self.pkgname)
266 actions.sort()
267 actions.reverse()
268 for p in actions:
269 if os.path.isdir(p):
270 os.rmdir(p)
271 else:
272 os.remove(p)
273 del sys.path[0]
274
275 def _check_path_limitations(self, module_name):
276 # base directory
277 source_path_len = len(self.here)
278 # a path separator + `longname` (twice)
279 source_path_len += 2 * (len(self.longname) + 1)
280 # a path separator + `module_name` + ".py"
281 source_path_len += len(module_name) + 1 + len(".py")
282 cached_path_len = (source_path_len +
283 len(importlib.util.cache_from_source("x.py")) - len("x.py"))
284 if os.name == 'nt' and cached_path_len >= 258:
285 # Under Windows, the max path len is 260 including C's terminating
286 # NUL character.
287 # (see http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx#maxpath)
288 self.skipTest("test paths too long (%d characters) for Windows' 260 character limit"
289 % cached_path_len)
290 elif os.name == 'nt' and verbose:
291 print("cached_path_len =", cached_path_len)
292
293 def test_module(self):
294 self.maxDiff = None
295 self._check_path_limitations(self.pkgname)
296 create_empty_file(os.path.join(self.subpkgname, self.pkgname + '.py'))
297 importlib.invalidate_caches()
298 from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import areallylongpackageandmodulenametotestreprtruncation
299 module = areallylongpackageandmodulenametotestreprtruncation
300 self.assertEqual(repr(module), "<module %r from %r>" % (module.__name__, module.__file__))
301 self.assertEqual(repr(sys), "<module 'sys' (built-in)>")
302
303 def test_type(self):
304 self._check_path_limitations('foo')
305 eq = self.assertEqual
306 write_file(os.path.join(self.subpkgname, 'foo.py'), '''\
307 class foo(object):
308 pass
309 ''')
310 importlib.invalidate_caches()
311 from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import foo
312 eq(repr(foo.foo),
313 "<class '%s.foo'>" % foo.__name__)
314
315 @unittest.skip('need a suitable object')
316 def test_object(self):
317 # XXX Test the repr of a type with a really long tp_name but with no
318 # tp_repr. WIBNI we had ::Inline? :)
319 pass
320
321 def test_class(self):
322 self._check_path_limitations('bar')
323 write_file(os.path.join(self.subpkgname, 'bar.py'), '''\
324 class bar:
325 pass
326 ''')
327 importlib.invalidate_caches()
328 from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import bar
329 # Module name may be prefixed with "test.", depending on how run.
330 self.assertEqual(repr(bar.bar), "<class '%s.bar'>" % bar.__name__)
331
332 def test_instance(self):
333 self._check_path_limitations('baz')
334 write_file(os.path.join(self.subpkgname, 'baz.py'), '''\
335 class baz:
336 pass
337 ''')
338 importlib.invalidate_caches()
339 from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import baz
340 ibaz = baz.baz()
341 self.assertTrue(repr(ibaz).startswith(
342 "<%s.baz object at 0x" % baz.__name__))
343
344 def test_method(self):
345 self._check_path_limitations('qux')
346 eq = self.assertEqual
347 write_file(os.path.join(self.subpkgname, 'qux.py'), '''\
348 class aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:
349 def amethod(self): pass
350 ''')
351 importlib.invalidate_caches()
352 from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import qux
353 # Unbound methods first
354 r = repr(qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod)
355 self.assertTrue(r.startswith('<function aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod'), r)
356 # Bound method next
357 iqux = qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()
358 r = repr(iqux.amethod)
359 self.assertTrue(r.startswith(
360 '<bound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod of <%s.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa object at 0x' \
361 % (qux.__name__,) ), r)
362
363 @unittest.skip('needs a built-in function with a really long name')
364 def test_builtin_function(self):
365 # XXX test built-in functions and methods with really long names
366 pass
367
368 class ClassWithRepr:
369 def __init__(self, s):
370 self.s = s
371 def __repr__(self):
372 return "ClassWithRepr(%r)" % self.s
373
374
375 class ClassWithFailingRepr:
376 def __repr__(self):
377 raise Exception("This should be caught by Repr.repr_instance")
378
379 class MyContainer:
380 'Helper class for TestRecursiveRepr'
381 def __init__(self, values):
382 self.values = list(values)
383 def append(self, value):
384 self.values.append(value)
385 @recursive_repr()
386 def __repr__(self):
387 return '<' + ', '.join(map(str, self.values)) + '>'
388
389 class MyContainer2(MyContainer):
390 @recursive_repr('+++')
391 def __repr__(self):
392 return '<' + ', '.join(map(str, self.values)) + '>'
393
394 class MyContainer3:
395 def __repr__(self):
396 'Test document content'
397 pass
398 wrapped = __repr__
399 wrapper = recursive_repr()(wrapped)
400
401 class TestRecursiveRepr(unittest.TestCase):
402 def test_recursive_repr(self):
403 m = MyContainer(list('abcde'))
404 m.append(m)
405 m.append('x')
406 m.append(m)
407 self.assertEqual(repr(m), '<a, b, c, d, e, ..., x, ...>')
408 m = MyContainer2(list('abcde'))
409 m.append(m)
410 m.append('x')
411 m.append(m)
412 self.assertEqual(repr(m), '<a, b, c, d, e, +++, x, +++>')
413
414 def test_assigned_attributes(self):
415 from functools import WRAPPER_ASSIGNMENTS as assigned
416 wrapped = MyContainer3.wrapped
417 wrapper = MyContainer3.wrapper
418 for name in assigned:
419 # pypy fix: can't use assertIs() to compare two strings
420 self.assertEqual(getattr(wrapper, name), getattr(wrapped, name))
421
422 if __name__ == "__main__":
423 unittest.main()