blob: 1d7ea856d08226010aa009b82297d18bc44357de [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
Fred Drake8e6669a2001-07-19 22:27:56 +00008import unittest
Barry Warsaw0bcf6d82001-08-24 18:37:32 +00009
Fred Drake8e6669a2001-07-19 22:27:56 +000010from test_support import run_unittest
Tim Petersab9ba272001-08-09 21:40:30 +000011from repr import repr as r # Don't shadow builtin repr
Fred Drake8e6669a2001-07-19 22:27:56 +000012
13
14def nestedTuple(nesting):
15 t = ()
16 for i in range(nesting):
17 t = (t,)
18 return t
19
20class ReprTests(unittest.TestCase):
21
22 def test_string(self):
23 eq = self.assertEquals
24 eq(r("abc"), "'abc'")
25 eq(r("abcdefghijklmnop"),"'abcdefghijklmnop'")
26
27 s = "a"*30+"b"*30
28 expected = `s`[:13] + "..." + `s`[-14:]
29 eq(r(s), expected)
Tim Petersab9ba272001-08-09 21:40:30 +000030
Fred Drake8e6669a2001-07-19 22:27:56 +000031 eq(r("\"'"), repr("\"'"))
32 s = "\""*30+"'"*100
33 expected = `s`[:13] + "..." + `s`[-14:]
34 eq(r(s), expected)
35
36 def test_container(self):
37 eq = self.assertEquals
38 # Tuples give up after 6 elements
39 eq(r(()), "()")
40 eq(r((1,)), "(1,)")
41 eq(r((1, 2, 3)), "(1, 2, 3)")
42 eq(r((1, 2, 3, 4, 5, 6)), "(1, 2, 3, 4, 5, 6)")
43 eq(r((1, 2, 3, 4, 5, 6, 7)), "(1, 2, 3, 4, 5, 6, ...)")
44
45 # Lists give up after 6 as well
46 eq(r([]), "[]")
47 eq(r([1]), "[1]")
48 eq(r([1, 2, 3]), "[1, 2, 3]")
49 eq(r([1, 2, 3, 4, 5, 6]), "[1, 2, 3, 4, 5, 6]")
50 eq(r([1, 2, 3, 4, 5, 6, 7]), "[1, 2, 3, 4, 5, 6, ...]")
51
52 # Dictionaries give up after 4.
53 eq(r({}), "{}")
54 d = {'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4}
55 eq(r(d), "{'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4}")
56 d['arthur'] = 1
57 eq(r(d), "{'alice': 1, 'arthur': 1, 'bob': 2, 'charles': 3, ...}")
58
59 def test_numbers(self):
60 eq = self.assertEquals
61 eq(r(123), repr(123))
62 eq(r(123L), repr(123L))
63 eq(r(1.0/3), repr(1.0/3))
64
65 n = 10L**100
66 expected = `n`[:18] + "..." + `n`[-19:]
67 eq(r(n), expected)
68
69 def test_instance(self):
70 eq = self.assertEquals
71 i1 = ClassWithRepr("a")
72 eq(r(i1), repr(i1))
Tim Petersab9ba272001-08-09 21:40:30 +000073
Fred Drake8e6669a2001-07-19 22:27:56 +000074 i2 = ClassWithRepr("x"*1000)
75 expected = `i2`[:13] + "..." + `i2`[-14:]
76 eq(r(i2), expected)
77
78 i3 = ClassWithFailingRepr()
79 eq(r(i3), ("<ClassWithFailingRepr instance at %x>"%id(i3)))
80
Guido van Rossumcf856f92001-09-05 02:26:26 +000081 s = r(ClassWithFailingRepr)
82 self.failUnless(s.startswith("<class "))
83 self.failUnless(s.endswith(">"))
84 self.failUnless(s.find("...") == 8)
85
Barry Warsaw0bcf6d82001-08-24 18:37:32 +000086 def test_file(self):
87 fp = open(unittest.__file__)
88 self.failUnless(repr(fp).startswith(
89 "<open file '%s', mode 'r' at 0x" % unittest.__file__))
90 fp.close()
91 self.failUnless(repr(fp).startswith(
92 "<closed file '%s', mode 'r' at 0x" % unittest.__file__))
93
94 def test_lambda(self):
95 self.failUnless(repr(lambda x: x).startswith(
Jeremy Hyltondd321382001-09-14 23:01:49 +000096 "<function <lambda"))
Barry Warsaw0bcf6d82001-08-24 18:37:32 +000097 # XXX anonymous functions? see func_repr
98
99 def test_builtin_function(self):
100 eq = self.assertEquals
101 # Functions
102 eq(repr(hash), '<built-in function hash>')
103 # Methods
104 self.failUnless(repr(''.split).startswith(
105 '<built-in method split of str object at 0x'))
106
107 def test_xrange(self):
Tim Petersd3925062002-04-16 01:27:44 +0000108 import warnings
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000109 eq = self.assertEquals
110 eq(repr(xrange(1)), 'xrange(1)')
111 eq(repr(xrange(1, 2)), 'xrange(1, 2)')
112 eq(repr(xrange(1, 2, 3)), 'xrange(1, 4, 3)')
113 # Turn off warnings for deprecated multiplication
Tim Petersd3925062002-04-16 01:27:44 +0000114 warnings.filterwarnings('ignore',
115 r'xrange object multiplication is deprecated',
116 DeprecationWarning, module=ReprTests.__module__)
117 warnings.filterwarnings('ignore',
118 r"PyRange_New's 'repetitions' argument is deprecated",
119 DeprecationWarning, module=ReprTests.__module__)
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000120 eq(repr(xrange(1) * 3), '(xrange(1) * 3)')
121
Fred Drake8e6669a2001-07-19 22:27:56 +0000122 def test_nesting(self):
123 eq = self.assertEquals
124 # everything is meant to give up after 6 levels.
125 eq(r([[[[[[[]]]]]]]), "[[[[[[[]]]]]]]")
126 eq(r([[[[[[[[]]]]]]]]), "[[[[[[[...]]]]]]]")
127
128 eq(r(nestedTuple(6)), "(((((((),),),),),),)")
129 eq(r(nestedTuple(7)), "(((((((...),),),),),),)")
130
131 eq(r({ nestedTuple(5) : nestedTuple(5) }),
132 "{((((((),),),),),): ((((((),),),),),)}")
133 eq(r({ nestedTuple(6) : nestedTuple(6) }),
134 "{((((((...),),),),),): ((((((...),),),),),)}")
135
136 eq(r([[[[[[{}]]]]]]), "[[[[[[{}]]]]]]")
137 eq(r([[[[[[[{}]]]]]]]), "[[[[[[[...]]]]]]]")
138
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000139 def test_buffer(self):
140 # XXX doesn't test buffers with no b_base or read-write buffers (see
141 # bufferobject.c). The test is fairly incomplete too. Sigh.
142 x = buffer('foo')
143 self.failUnless(repr(x).startswith('<read-only buffer for 0x'))
144
145 def test_cell(self):
146 # XXX Hmm? How to get at a cell object?
147 pass
148
149 def test_descriptors(self):
150 eq = self.assertEquals
151 # method descriptors
Tim Petersa427a2b2001-10-29 22:25:45 +0000152 eq(repr(dict.items), "<method 'items' of 'dict' objects>")
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000153 # XXX member descriptors
154 # XXX attribute descriptors
155 # XXX slot descriptors
156 # static and class methods
157 class C:
158 def foo(cls): pass
159 x = staticmethod(C.foo)
160 self.failUnless(repr(x).startswith('<staticmethod object at 0x'))
161 x = classmethod(C.foo)
162 self.failUnless(repr(x).startswith('<classmethod object at 0x'))
163
164def touch(path, text=''):
165 fp = open(path, 'w')
166 fp.write(text)
167 fp.close()
168
169def zap(actions, dirname, names):
170 for name in names:
171 actions.append(os.path.join(dirname, name))
172
173class LongReprTest(unittest.TestCase):
174 def setUp(self):
175 longname = 'areallylongpackageandmodulenametotestreprtruncation'
176 self.pkgname = os.path.join(longname)
177 self.subpkgname = os.path.join(longname, longname)
178 # Make the package and subpackage
179 os.mkdir(self.pkgname)
Guido van Rossume2ae77b2001-10-24 20:42:55 +0000180 touch(os.path.join(self.pkgname, '__init__'+os.extsep+'py'))
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000181 os.mkdir(self.subpkgname)
Guido van Rossume2ae77b2001-10-24 20:42:55 +0000182 touch(os.path.join(self.subpkgname, '__init__'+os.extsep+'py'))
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000183 # Remember where we are
184 self.here = os.getcwd()
185 sys.path.insert(0, self.here)
186
187 def tearDown(self):
188 actions = []
189 os.path.walk(self.pkgname, zap, actions)
190 actions.append(self.pkgname)
191 actions.sort()
192 actions.reverse()
193 for p in actions:
194 if os.path.isdir(p):
195 os.rmdir(p)
196 else:
197 os.remove(p)
198 del sys.path[0]
199
200 def test_module(self):
201 eq = self.assertEquals
Guido van Rossume2ae77b2001-10-24 20:42:55 +0000202 touch(os.path.join(self.subpkgname, self.pkgname + os.extsep + 'py'))
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000203 from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import areallylongpackageandmodulenametotestreprtruncation
204 eq(repr(areallylongpackageandmodulenametotestreprtruncation),
205 "<module 'areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation' from '%s'>" % areallylongpackageandmodulenametotestreprtruncation.__file__)
Neal Norwitz70769012001-12-29 00:25:42 +0000206 eq(repr(sys), "<module 'sys' (built-in)>")
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000207
208 def test_type(self):
209 eq = self.assertEquals
Guido van Rossume2ae77b2001-10-24 20:42:55 +0000210 touch(os.path.join(self.subpkgname, 'foo'+os.extsep+'py'), '''\
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000211class foo(object):
212 pass
213''')
214 from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import foo
215 eq(repr(foo.foo),
Guido van Rossuma4cb7882001-09-25 03:56:29 +0000216 "<class 'areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation.foo.foo'>")
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000217
218 def test_object(self):
219 # XXX Test the repr of a type with a really long tp_name but with no
220 # tp_repr. WIBNI we had ::Inline? :)
221 pass
222
223 def test_class(self):
Guido van Rossume2ae77b2001-10-24 20:42:55 +0000224 touch(os.path.join(self.subpkgname, 'bar'+os.extsep+'py'), '''\
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000225class bar:
226 pass
227''')
228 from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import bar
229 self.failUnless(repr(bar.bar).startswith(
230 "<class areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation.bar.bar at 0x"))
231
232 def test_instance(self):
Guido van Rossume2ae77b2001-10-24 20:42:55 +0000233 touch(os.path.join(self.subpkgname, 'baz'+os.extsep+'py'), '''\
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000234class baz:
235 pass
236''')
237 from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import baz
238 ibaz = baz.baz()
239 self.failUnless(repr(ibaz).startswith(
240 "<areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation.baz.baz instance at 0x"))
241
242 def test_method(self):
243 eq = self.assertEquals
Guido van Rossume2ae77b2001-10-24 20:42:55 +0000244 touch(os.path.join(self.subpkgname, 'qux'+os.extsep+'py'), '''\
Barry Warsaw0bcf6d82001-08-24 18:37:32 +0000245class aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:
246 def amethod(self): pass
247''')
248 from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import qux
249 # Unbound methods first
250 eq(repr(qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod),
251 '<unbound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod>')
252 # Bound method next
253 iqux = qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()
254 self.failUnless(repr(iqux.amethod).startswith(
255 '<bound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod of <areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation.qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa instance at 0x'))
256
257 def test_builtin_function(self):
258 # XXX test built-in functions and methods with really long names
259 pass
Fred Drake8e6669a2001-07-19 22:27:56 +0000260
261class ClassWithRepr:
262 def __init__(self, s):
263 self.s = s
264 def __repr__(self):
265 return "ClassWithLongRepr(%r)" % self.s
266
267
268class ClassWithFailingRepr:
269 def __repr__(self):
270 raise Exception("This should be caught by Repr.repr_instance")
271
272
Fred Drake2e2be372001-09-20 21:33:42 +0000273def test_main():
274 run_unittest(ReprTests)
275 if os.name != 'mac':
276 run_unittest(LongReprTest)
277
278
279if __name__ == "__main__":
280 test_main()