blob: 6284f4095a0f404dbb3ff6850839725e9721e0ac [file] [log] [blame]
Fred Drake8e6669a2001-07-19 22:27:56 +00001"""
2 Test cases for the repr module
3 Nick Mathewson
4"""
5
Barry Warsaw0bcf6d82001-08-24 18:37:32 +00006import sys
7import os
Neal Norwitz008b8612006-05-30 07:21:10 +00008import shutil
Fred Drake8e6669a2001-07-19 22:27:56 +00009import unittest
Barry Warsaw0bcf6d82001-08-24 18:37:32 +000010
Barry Warsaw04f357c2002-07-23 19:04:11 +000011from test.test_support import run_unittest
Tim Petersab9ba272001-08-09 21:40:30 +000012from repr import repr as r # Don't shadow builtin repr
Neal Norwitzc161cb92007-06-11 07:29:43 +000013from repr import Repr
Fred Drake8e6669a2001-07-19 22:27:56 +000014
15
16def nestedTuple(nesting):
17 t = ()
18 for i in range(nesting):
19 t = (t,)
20 return t
21
22class ReprTests(unittest.TestCase):
23
24 def test_string(self):
25 eq = self.assertEquals
26 eq(r("abc"), "'abc'")
27 eq(r("abcdefghijklmnop"),"'abcdefghijklmnop'")
28
29 s = "a"*30+"b"*30
Walter Dörwald70a6b492004-02-12 17:35:32 +000030 expected = repr(s)[:13] + "..." + repr(s)[-14:]
Fred Drake8e6669a2001-07-19 22:27:56 +000031 eq(r(s), expected)
Tim Petersab9ba272001-08-09 21:40:30 +000032
Fred Drake8e6669a2001-07-19 22:27:56 +000033 eq(r("\"'"), repr("\"'"))
34 s = "\""*30+"'"*100
Walter Dörwald70a6b492004-02-12 17:35:32 +000035 expected = repr(s)[:13] + "..." + repr(s)[-14:]
Fred Drake8e6669a2001-07-19 22:27:56 +000036 eq(r(s), expected)
37
Neal Norwitzc161cb92007-06-11 07:29:43 +000038 def test_tuple(self):
39 eq = self.assertEquals
40 eq(r((1,)), "(1,)")
41
42 t3 = (1, 2, 3)
43 eq(r(t3), "(1, 2, 3)")
44
45 r2 = Repr()
46 r2.maxtuple = 2
47 expected = repr(t3)[:-2] + "...)"
48 eq(r2.repr(t3), expected)
49
Fred Drake8e6669a2001-07-19 22:27:56 +000050 def test_container(self):
Tim Peters6ee04802003-02-05 18:29:34 +000051 from array import array
Raymond Hettinger1453e4a2004-05-21 23:01:18 +000052 from collections import deque
Tim Peters6ee04802003-02-05 18:29:34 +000053
Fred Drake8e6669a2001-07-19 22:27:56 +000054 eq = self.assertEquals
55 # Tuples give up after 6 elements
56 eq(r(()), "()")
57 eq(r((1,)), "(1,)")
58 eq(r((1, 2, 3)), "(1, 2, 3)")
59 eq(r((1, 2, 3, 4, 5, 6)), "(1, 2, 3, 4, 5, 6)")
60 eq(r((1, 2, 3, 4, 5, 6, 7)), "(1, 2, 3, 4, 5, 6, ...)")
61
62 # Lists give up after 6 as well
63 eq(r([]), "[]")
64 eq(r([1]), "[1]")
65 eq(r([1, 2, 3]), "[1, 2, 3]")
66 eq(r([1, 2, 3, 4, 5, 6]), "[1, 2, 3, 4, 5, 6]")
67 eq(r([1, 2, 3, 4, 5, 6, 7]), "[1, 2, 3, 4, 5, 6, ...]")
68
Raymond Hettingerba6cd362004-05-21 10:00:15 +000069 # Sets give up after 6 as well
70 eq(r(set([])), "set([])")
71 eq(r(set([1])), "set([1])")
72 eq(r(set([1, 2, 3])), "set([1, 2, 3])")
73 eq(r(set([1, 2, 3, 4, 5, 6])), "set([1, 2, 3, 4, 5, 6])")
74 eq(r(set([1, 2, 3, 4, 5, 6, 7])), "set([1, 2, 3, 4, 5, 6, ...])")
75
76 # Frozensets give up after 6 as well
77 eq(r(frozenset([])), "frozenset([])")
78 eq(r(frozenset([1])), "frozenset([1])")
79 eq(r(frozenset([1, 2, 3])), "frozenset([1, 2, 3])")
80 eq(r(frozenset([1, 2, 3, 4, 5, 6])), "frozenset([1, 2, 3, 4, 5, 6])")
81 eq(r(frozenset([1, 2, 3, 4, 5, 6, 7])), "frozenset([1, 2, 3, 4, 5, 6, ...])")
82
Raymond Hettinger1453e4a2004-05-21 23:01:18 +000083 # collections.deque after 6
84 eq(r(deque([1, 2, 3, 4, 5, 6, 7])), "deque([1, 2, 3, 4, 5, 6, ...])")
85
Fred Drake8e6669a2001-07-19 22:27:56 +000086 # Dictionaries give up after 4.
87 eq(r({}), "{}")
88 d = {'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4}
89 eq(r(d), "{'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4}")
90 d['arthur'] = 1
91 eq(r(d), "{'alice': 1, 'arthur': 1, 'bob': 2, 'charles': 3, ...}")
92
Tim Peters6ee04802003-02-05 18:29:34 +000093 # array.array after 5.
94 eq(r(array('i')), "array('i', [])")
95 eq(r(array('i', [1])), "array('i', [1])")
96 eq(r(array('i', [1, 2])), "array('i', [1, 2])")
97 eq(r(array('i', [1, 2, 3])), "array('i', [1, 2, 3])")
98 eq(r(array('i', [1, 2, 3, 4])), "array('i', [1, 2, 3, 4])")
99 eq(r(array('i', [1, 2, 3, 4, 5])), "array('i', [1, 2, 3, 4, 5])")
100 eq(r(array('i', [1, 2, 3, 4, 5, 6])),
101 "array('i', [1, 2, 3, 4, 5, ...])")
102
Fred Drake8e6669a2001-07-19 22:27:56 +0000103 def test_numbers(self):
104 eq = self.assertEquals
105 eq(r(123), repr(123))
106 eq(r(123L), repr(123L))
107 eq(r(1.0/3), repr(1.0/3))
108
109 n = 10L**100
Walter Dörwald70a6b492004-02-12 17:35:32 +0000110 expected = repr(n)[:18] + "..." + repr(n)[-19:]
Fred Drake8e6669a2001-07-19 22:27:56 +0000111 eq(r(n), expected)
112
113 def test_instance(self):
114 eq = self.assertEquals
115 i1 = ClassWithRepr("a")
116 eq(r(i1), repr(i1))
Tim Petersab9ba272001-08-09 21:40:30 +0000117
Fred Drake8e6669a2001-07-19 22:27:56 +0000118 i2 = ClassWithRepr("x"*1000)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000119 expected = repr(i2)[:13] + "..." + repr(i2)[-14:]
Fred Drake8e6669a2001-07-19 22:27:56 +0000120 eq(r(i2), expected)
121
122 i3 = ClassWithFailingRepr()
123 eq(r(i3), ("<ClassWithFailingRepr instance at %x>"%id(i3)))
124
Guido van Rossumcf856f92001-09-05 02:26:26 +0000125 s = r(ClassWithFailingRepr)
126 self.failUnless(s.startswith("<class "))
127 self.failUnless(s.endswith(">"))
128 self.failUnless(s.find("...") == 8)
129
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000130 def test_file(self):
131 fp = open(unittest.__file__)
132 self.failUnless(repr(fp).startswith(
133 "<open file '%s', mode 'r' at 0x" % unittest.__file__))
134 fp.close()
135 self.failUnless(repr(fp).startswith(
136 "<closed file '%s', mode 'r' at 0x" % unittest.__file__))
137
138 def test_lambda(self):
139 self.failUnless(repr(lambda x: x).startswith(
Neil Schemenauerab541bb2005-10-21 18:11:40 +0000140 "<function <lambda"))
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000141 # XXX anonymous functions? see func_repr
142
143 def test_builtin_function(self):
144 eq = self.assertEquals
145 # Functions
146 eq(repr(hash), '<built-in function hash>')
147 # Methods
148 self.failUnless(repr(''.split).startswith(
149 '<built-in method split of str object at 0x'))
150
151 def test_xrange(self):
152 eq = self.assertEquals
153 eq(repr(xrange(1)), 'xrange(1)')
154 eq(repr(xrange(1, 2)), 'xrange(1, 2)')
155 eq(repr(xrange(1, 2, 3)), 'xrange(1, 4, 3)')
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000156
Fred Drake8e6669a2001-07-19 22:27:56 +0000157 def test_nesting(self):
158 eq = self.assertEquals
159 # everything is meant to give up after 6 levels.
160 eq(r([[[[[[[]]]]]]]), "[[[[[[[]]]]]]]")
161 eq(r([[[[[[[[]]]]]]]]), "[[[[[[[...]]]]]]]")
162
163 eq(r(nestedTuple(6)), "(((((((),),),),),),)")
164 eq(r(nestedTuple(7)), "(((((((...),),),),),),)")
165
166 eq(r({ nestedTuple(5) : nestedTuple(5) }),
167 "{((((((),),),),),): ((((((),),),),),)}")
168 eq(r({ nestedTuple(6) : nestedTuple(6) }),
169 "{((((((...),),),),),): ((((((...),),),),),)}")
170
171 eq(r([[[[[[{}]]]]]]), "[[[[[[{}]]]]]]")
172 eq(r([[[[[[[{}]]]]]]]), "[[[[[[[...]]]]]]]")
173
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000174 def test_buffer(self):
175 # XXX doesn't test buffers with no b_base or read-write buffers (see
176 # bufferobject.c). The test is fairly incomplete too. Sigh.
177 x = buffer('foo')
178 self.failUnless(repr(x).startswith('<read-only buffer for 0x'))
179
180 def test_cell(self):
181 # XXX Hmm? How to get at a cell object?
182 pass
183
184 def test_descriptors(self):
185 eq = self.assertEquals
186 # method descriptors
Tim Petersa427a2b2001-10-29 22:25:45 +0000187 eq(repr(dict.items), "<method 'items' of 'dict' objects>")
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000188 # XXX member descriptors
189 # XXX attribute descriptors
190 # XXX slot descriptors
191 # static and class methods
192 class C:
193 def foo(cls): pass
194 x = staticmethod(C.foo)
195 self.failUnless(repr(x).startswith('<staticmethod object at 0x'))
196 x = classmethod(C.foo)
197 self.failUnless(repr(x).startswith('<classmethod object at 0x'))
198
Georg Brandl8fd3ecf2007-09-12 19:00:07 +0000199 def test_unsortable(self):
200 # Repr.repr() used to call sorted() on sets, frozensets and dicts
201 # without taking into account that not all objects are comparable
202 x = set([1j, 2j, 3j])
203 y = frozenset(x)
204 z = {1j: 1, 2j: 2}
205 r(x)
206 r(y)
207 r(z)
208
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000209def touch(path, text=''):
210 fp = open(path, 'w')
211 fp.write(text)
212 fp.close()
213
214def zap(actions, dirname, names):
215 for name in names:
216 actions.append(os.path.join(dirname, name))
217
218class LongReprTest(unittest.TestCase):
219 def setUp(self):
220 longname = 'areallylongpackageandmodulenametotestreprtruncation'
221 self.pkgname = os.path.join(longname)
222 self.subpkgname = os.path.join(longname, longname)
223 # Make the package and subpackage
Neal Norwitz008b8612006-05-30 07:21:10 +0000224 shutil.rmtree(self.pkgname, ignore_errors=True)
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000225 os.mkdir(self.pkgname)
Guido van Rossume2ae77b2001-10-24 20:42:55 +0000226 touch(os.path.join(self.pkgname, '__init__'+os.extsep+'py'))
Neal Norwitz008b8612006-05-30 07:21:10 +0000227 shutil.rmtree(self.subpkgname, ignore_errors=True)
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000228 os.mkdir(self.subpkgname)
Guido van Rossume2ae77b2001-10-24 20:42:55 +0000229 touch(os.path.join(self.subpkgname, '__init__'+os.extsep+'py'))
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000230 # Remember where we are
231 self.here = os.getcwd()
232 sys.path.insert(0, self.here)
233
234 def tearDown(self):
235 actions = []
236 os.path.walk(self.pkgname, zap, actions)
237 actions.append(self.pkgname)
238 actions.sort()
239 actions.reverse()
240 for p in actions:
241 if os.path.isdir(p):
242 os.rmdir(p)
243 else:
244 os.remove(p)
245 del sys.path[0]
246
247 def test_module(self):
248 eq = self.assertEquals
Guido van Rossume2ae77b2001-10-24 20:42:55 +0000249 touch(os.path.join(self.subpkgname, self.pkgname + os.extsep + 'py'))
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000250 from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import areallylongpackageandmodulenametotestreprtruncation
251 eq(repr(areallylongpackageandmodulenametotestreprtruncation),
Mark Hammondd800ae12003-01-16 04:56:52 +0000252 "<module '%s' from '%s'>" % (areallylongpackageandmodulenametotestreprtruncation.__name__, areallylongpackageandmodulenametotestreprtruncation.__file__))
Neal Norwitz70769012001-12-29 00:25:42 +0000253 eq(repr(sys), "<module 'sys' (built-in)>")
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000254
255 def test_type(self):
256 eq = self.assertEquals
Guido van Rossume2ae77b2001-10-24 20:42:55 +0000257 touch(os.path.join(self.subpkgname, 'foo'+os.extsep+'py'), '''\
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000258class foo(object):
259 pass
260''')
261 from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import foo
262 eq(repr(foo.foo),
Mark Hammondd800ae12003-01-16 04:56:52 +0000263 "<class '%s.foo'>" % foo.__name__)
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000264
265 def test_object(self):
266 # XXX Test the repr of a type with a really long tp_name but with no
267 # tp_repr. WIBNI we had ::Inline? :)
268 pass
269
270 def test_class(self):
Guido van Rossume2ae77b2001-10-24 20:42:55 +0000271 touch(os.path.join(self.subpkgname, 'bar'+os.extsep+'py'), '''\
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000272class bar:
273 pass
274''')
275 from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import bar
Mark Hammondd800ae12003-01-16 04:56:52 +0000276 # Module name may be prefixed with "test.", depending on how run.
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000277 self.failUnless(repr(bar.bar).startswith(
Mark Hammondd800ae12003-01-16 04:56:52 +0000278 "<class %s.bar at 0x" % bar.__name__))
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000279
280 def test_instance(self):
Guido van Rossume2ae77b2001-10-24 20:42:55 +0000281 touch(os.path.join(self.subpkgname, 'baz'+os.extsep+'py'), '''\
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000282class baz:
283 pass
284''')
285 from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import baz
286 ibaz = baz.baz()
287 self.failUnless(repr(ibaz).startswith(
Mark Hammondd800ae12003-01-16 04:56:52 +0000288 "<%s.baz instance at 0x" % baz.__name__))
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000289
290 def test_method(self):
291 eq = self.assertEquals
Guido van Rossume2ae77b2001-10-24 20:42:55 +0000292 touch(os.path.join(self.subpkgname, 'qux'+os.extsep+'py'), '''\
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000293class aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:
294 def amethod(self): pass
295''')
296 from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import qux
297 # Unbound methods first
298 eq(repr(qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod),
299 '<unbound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod>')
300 # Bound method next
301 iqux = qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()
302 self.failUnless(repr(iqux.amethod).startswith(
Mark Hammondd800ae12003-01-16 04:56:52 +0000303 '<bound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod of <%s.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa instance at 0x' \
304 % (qux.__name__,) ))
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000305
306 def test_builtin_function(self):
307 # XXX test built-in functions and methods with really long names
308 pass
Fred Drake8e6669a2001-07-19 22:27:56 +0000309
310class ClassWithRepr:
311 def __init__(self, s):
312 self.s = s
313 def __repr__(self):
314 return "ClassWithLongRepr(%r)" % self.s
315
316
317class ClassWithFailingRepr:
318 def __repr__(self):
319 raise Exception("This should be caught by Repr.repr_instance")
320
321
Fred Drake2e2be372001-09-20 21:33:42 +0000322def test_main():
323 run_unittest(ReprTests)
324 if os.name != 'mac':
325 run_unittest(LongReprTest)
326
327
328if __name__ == "__main__":
329 test_main()