This commit was manufactured by cvs2svn to create tag 'r234c1'.
[python/dscho.git] / Lib / test / test_repr.py
blob0a032ea258f14cc178f586fcf8918c4e0746338e
1 """
2 Test cases for the repr module
3 Nick Mathewson
4 """
6 import sys
7 import os
8 import unittest
10 from test.test_support import run_unittest
11 from repr import repr as r # Don't shadow builtin repr
14 def nestedTuple(nesting):
15 t = ()
16 for i in range(nesting):
17 t = (t,)
18 return t
20 class ReprTests(unittest.TestCase):
22 def test_string(self):
23 eq = self.assertEquals
24 eq(r("abc"), "'abc'")
25 eq(r("abcdefghijklmnop"),"'abcdefghijklmnop'")
27 s = "a"*30+"b"*30
28 expected = `s`[:13] + "..." + `s`[-14:]
29 eq(r(s), expected)
31 eq(r("\"'"), repr("\"'"))
32 s = "\""*30+"'"*100
33 expected = `s`[:13] + "..." + `s`[-14:]
34 eq(r(s), expected)
36 def test_container(self):
37 from array import array
39 eq = self.assertEquals
40 # Tuples give up after 6 elements
41 eq(r(()), "()")
42 eq(r((1,)), "(1,)")
43 eq(r((1, 2, 3)), "(1, 2, 3)")
44 eq(r((1, 2, 3, 4, 5, 6)), "(1, 2, 3, 4, 5, 6)")
45 eq(r((1, 2, 3, 4, 5, 6, 7)), "(1, 2, 3, 4, 5, 6, ...)")
47 # Lists give up after 6 as well
48 eq(r([]), "[]")
49 eq(r([1]), "[1]")
50 eq(r([1, 2, 3]), "[1, 2, 3]")
51 eq(r([1, 2, 3, 4, 5, 6]), "[1, 2, 3, 4, 5, 6]")
52 eq(r([1, 2, 3, 4, 5, 6, 7]), "[1, 2, 3, 4, 5, 6, ...]")
54 # Dictionaries give up after 4.
55 eq(r({}), "{}")
56 d = {'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4}
57 eq(r(d), "{'alice': 1, 'bob': 2, 'charles': 3, 'dave': 4}")
58 d['arthur'] = 1
59 eq(r(d), "{'alice': 1, 'arthur': 1, 'bob': 2, 'charles': 3, ...}")
61 # array.array after 5.
62 eq(r(array('i')), "array('i', [])")
63 eq(r(array('i', [1])), "array('i', [1])")
64 eq(r(array('i', [1, 2])), "array('i', [1, 2])")
65 eq(r(array('i', [1, 2, 3])), "array('i', [1, 2, 3])")
66 eq(r(array('i', [1, 2, 3, 4])), "array('i', [1, 2, 3, 4])")
67 eq(r(array('i', [1, 2, 3, 4, 5])), "array('i', [1, 2, 3, 4, 5])")
68 eq(r(array('i', [1, 2, 3, 4, 5, 6])),
69 "array('i', [1, 2, 3, 4, 5, ...])")
71 def test_numbers(self):
72 eq = self.assertEquals
73 eq(r(123), repr(123))
74 eq(r(123L), repr(123L))
75 eq(r(1.0/3), repr(1.0/3))
77 n = 10L**100
78 expected = `n`[:18] + "..." + `n`[-19:]
79 eq(r(n), expected)
81 def test_instance(self):
82 eq = self.assertEquals
83 i1 = ClassWithRepr("a")
84 eq(r(i1), repr(i1))
86 i2 = ClassWithRepr("x"*1000)
87 expected = `i2`[:13] + "..." + `i2`[-14:]
88 eq(r(i2), expected)
90 i3 = ClassWithFailingRepr()
91 # On some systems (RH10) id() can be a negative number.
92 # work around this.
93 MAX = 2L*sys.maxint+1
94 eq(r(i3), ("<ClassWithFailingRepr instance at %x>"%(id(i3)&MAX)))
96 s = r(ClassWithFailingRepr)
97 self.failUnless(s.startswith("<class "))
98 self.failUnless(s.endswith(">"))
99 self.failUnless(s.find("...") == 8)
101 def test_file(self):
102 fp = open(unittest.__file__)
103 self.failUnless(repr(fp).startswith(
104 "<open file '%s', mode 'r' at 0x" % unittest.__file__))
105 fp.close()
106 self.failUnless(repr(fp).startswith(
107 "<closed file '%s', mode 'r' at 0x" % unittest.__file__))
109 def test_lambda(self):
110 self.failUnless(repr(lambda x: x).startswith(
111 "<function <lambda"))
112 # XXX anonymous functions? see func_repr
114 def test_builtin_function(self):
115 eq = self.assertEquals
116 # Functions
117 eq(repr(hash), '<built-in function hash>')
118 # Methods
119 self.failUnless(repr(''.split).startswith(
120 '<built-in method split of str object at 0x'))
122 def test_xrange(self):
123 import warnings
124 eq = self.assertEquals
125 eq(repr(xrange(1)), 'xrange(1)')
126 eq(repr(xrange(1, 2)), 'xrange(1, 2)')
127 eq(repr(xrange(1, 2, 3)), 'xrange(1, 4, 3)')
129 def test_nesting(self):
130 eq = self.assertEquals
131 # everything is meant to give up after 6 levels.
132 eq(r([[[[[[[]]]]]]]), "[[[[[[[]]]]]]]")
133 eq(r([[[[[[[[]]]]]]]]), "[[[[[[[...]]]]]]]")
135 eq(r(nestedTuple(6)), "(((((((),),),),),),)")
136 eq(r(nestedTuple(7)), "(((((((...),),),),),),)")
138 eq(r({ nestedTuple(5) : nestedTuple(5) }),
139 "{((((((),),),),),): ((((((),),),),),)}")
140 eq(r({ nestedTuple(6) : nestedTuple(6) }),
141 "{((((((...),),),),),): ((((((...),),),),),)}")
143 eq(r([[[[[[{}]]]]]]), "[[[[[[{}]]]]]]")
144 eq(r([[[[[[[{}]]]]]]]), "[[[[[[[...]]]]]]]")
146 def test_buffer(self):
147 # XXX doesn't test buffers with no b_base or read-write buffers (see
148 # bufferobject.c). The test is fairly incomplete too. Sigh.
149 x = buffer('foo')
150 self.failUnless(repr(x).startswith('<read-only buffer for 0x'))
152 def test_cell(self):
153 # XXX Hmm? How to get at a cell object?
154 pass
156 def test_descriptors(self):
157 eq = self.assertEquals
158 # method descriptors
159 eq(repr(dict.items), "<method 'items' of 'dict' objects>")
160 # XXX member descriptors
161 # XXX attribute descriptors
162 # XXX slot descriptors
163 # static and class methods
164 class C:
165 def foo(cls): pass
166 x = staticmethod(C.foo)
167 self.failUnless(repr(x).startswith('<staticmethod object at 0x'))
168 x = classmethod(C.foo)
169 self.failUnless(repr(x).startswith('<classmethod object at 0x'))
171 def touch(path, text=''):
172 fp = open(path, 'w')
173 fp.write(text)
174 fp.close()
176 def zap(actions, dirname, names):
177 for name in names:
178 actions.append(os.path.join(dirname, name))
180 class LongReprTest(unittest.TestCase):
181 def setUp(self):
182 longname = 'areallylongpackageandmodulenametotestreprtruncation'
183 self.pkgname = os.path.join(longname)
184 self.subpkgname = os.path.join(longname, longname)
185 # Make the package and subpackage
186 os.mkdir(self.pkgname)
187 touch(os.path.join(self.pkgname, '__init__'+os.extsep+'py'))
188 os.mkdir(self.subpkgname)
189 touch(os.path.join(self.subpkgname, '__init__'+os.extsep+'py'))
190 # Remember where we are
191 self.here = os.getcwd()
192 sys.path.insert(0, self.here)
194 def tearDown(self):
195 actions = []
196 os.path.walk(self.pkgname, zap, actions)
197 actions.append(self.pkgname)
198 actions.sort()
199 actions.reverse()
200 for p in actions:
201 if os.path.isdir(p):
202 os.rmdir(p)
203 else:
204 os.remove(p)
205 del sys.path[0]
207 def test_module(self):
208 eq = self.assertEquals
209 touch(os.path.join(self.subpkgname, self.pkgname + os.extsep + 'py'))
210 from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import areallylongpackageandmodulenametotestreprtruncation
211 eq(repr(areallylongpackageandmodulenametotestreprtruncation),
212 "<module '%s' from '%s'>" % (areallylongpackageandmodulenametotestreprtruncation.__name__, areallylongpackageandmodulenametotestreprtruncation.__file__))
213 eq(repr(sys), "<module 'sys' (built-in)>")
215 def test_type(self):
216 eq = self.assertEquals
217 touch(os.path.join(self.subpkgname, 'foo'+os.extsep+'py'), '''\
218 class foo(object):
219 pass
220 ''')
221 from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import foo
222 eq(repr(foo.foo),
223 "<class '%s.foo'>" % foo.__name__)
225 def test_object(self):
226 # XXX Test the repr of a type with a really long tp_name but with no
227 # tp_repr. WIBNI we had ::Inline? :)
228 pass
230 def test_class(self):
231 touch(os.path.join(self.subpkgname, 'bar'+os.extsep+'py'), '''\
232 class bar:
233 pass
234 ''')
235 from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import bar
236 # Module name may be prefixed with "test.", depending on how run.
237 self.failUnless(repr(bar.bar).startswith(
238 "<class %s.bar at 0x" % bar.__name__))
240 def test_instance(self):
241 touch(os.path.join(self.subpkgname, 'baz'+os.extsep+'py'), '''\
242 class baz:
243 pass
244 ''')
245 from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import baz
246 ibaz = baz.baz()
247 self.failUnless(repr(ibaz).startswith(
248 "<%s.baz instance at 0x" % baz.__name__))
250 def test_method(self):
251 eq = self.assertEquals
252 touch(os.path.join(self.subpkgname, 'qux'+os.extsep+'py'), '''\
253 class aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:
254 def amethod(self): pass
255 ''')
256 from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import qux
257 # Unbound methods first
258 eq(repr(qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod),
259 '<unbound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod>')
260 # Bound method next
261 iqux = qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()
262 self.failUnless(repr(iqux.amethod).startswith(
263 '<bound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod of <%s.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa instance at 0x' \
264 % (qux.__name__,) ))
266 def test_builtin_function(self):
267 # XXX test built-in functions and methods with really long names
268 pass
270 class ClassWithRepr:
271 def __init__(self, s):
272 self.s = s
273 def __repr__(self):
274 return "ClassWithLongRepr(%r)" % self.s
277 class ClassWithFailingRepr:
278 def __repr__(self):
279 raise Exception("This should be caught by Repr.repr_instance")
282 def test_main():
283 run_unittest(ReprTests)
284 if os.name != 'mac':
285 run_unittest(LongReprTest)
288 if __name__ == "__main__":
289 test_main()