blob: fe4eaeae8855e679b2d79e4b497f998778f490a5 [file] [log] [blame]
Benjamin Petersond4d400c2009-04-18 20:12:47 +00001import __builtin__
Armin Rigo9790a272007-05-02 19:23:31 +00002import types
Georg Brandl48545522008-02-02 10:12:36 +00003import unittest
4import warnings
Tim Peters4d9b4662002-04-16 01:59:17 +00005
Georg Brandl48545522008-02-02 10:12:36 +00006from copy import deepcopy
7from test import test_support
Tim Peters6d6c1a32001-08-02 04:15:00 +00008
Guido van Rossum875eeaa2001-10-11 18:33:53 +00009
Georg Brandl48545522008-02-02 10:12:36 +000010class OperatorsTest(unittest.TestCase):
Tim Peters6d6c1a32001-08-02 04:15:00 +000011
Georg Brandl48545522008-02-02 10:12:36 +000012 def __init__(self, *args, **kwargs):
13 unittest.TestCase.__init__(self, *args, **kwargs)
14 self.binops = {
15 'add': '+',
16 'sub': '-',
17 'mul': '*',
18 'div': '/',
19 'divmod': 'divmod',
20 'pow': '**',
21 'lshift': '<<',
22 'rshift': '>>',
23 'and': '&',
24 'xor': '^',
25 'or': '|',
26 'cmp': 'cmp',
27 'lt': '<',
28 'le': '<=',
29 'eq': '==',
30 'ne': '!=',
31 'gt': '>',
32 'ge': '>=',
33 }
Tim Peters3caca232001-12-06 06:23:26 +000034
Georg Brandl48545522008-02-02 10:12:36 +000035 for name, expr in self.binops.items():
36 if expr.islower():
37 expr = expr + "(a, b)"
38 else:
39 expr = 'a %s b' % expr
40 self.binops[name] = expr
Tim Peters3caca232001-12-06 06:23:26 +000041
Georg Brandl48545522008-02-02 10:12:36 +000042 self.unops = {
43 'pos': '+',
44 'neg': '-',
45 'abs': 'abs',
46 'invert': '~',
47 'int': 'int',
48 'long': 'long',
49 'float': 'float',
50 'oct': 'oct',
51 'hex': 'hex',
52 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000053
Georg Brandl48545522008-02-02 10:12:36 +000054 for name, expr in self.unops.items():
55 if expr.islower():
56 expr = expr + "(a)"
57 else:
58 expr = '%s a' % expr
59 self.unops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000060
Georg Brandl48545522008-02-02 10:12:36 +000061 def setUp(self):
62 self.original_filters = warnings.filters[:]
63 warnings.filterwarnings("ignore",
64 r'complex divmod\(\), // and % are deprecated$',
65 DeprecationWarning, r'(<string>|%s)$' % __name__)
Tim Peters6d6c1a32001-08-02 04:15:00 +000066
Georg Brandl48545522008-02-02 10:12:36 +000067 def tearDown(self):
68 warnings.filters = self.original_filters
Tim Peters6d6c1a32001-08-02 04:15:00 +000069
Georg Brandl48545522008-02-02 10:12:36 +000070 def unop_test(self, a, res, expr="len(a)", meth="__len__"):
71 d = {'a': a}
72 self.assertEqual(eval(expr, d), res)
73 t = type(a)
74 m = getattr(t, meth)
Tim Peters6d6c1a32001-08-02 04:15:00 +000075
Georg Brandl48545522008-02-02 10:12:36 +000076 # Find method in parent class
77 while meth not in t.__dict__:
78 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +000079 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
80 # method object; the getattr() below obtains its underlying function.
81 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +000082 self.assertEqual(m(a), res)
83 bm = getattr(a, meth)
84 self.assertEqual(bm(), res)
Tim Peters2f93e282001-10-04 05:27:00 +000085
Georg Brandl48545522008-02-02 10:12:36 +000086 def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
87 d = {'a': a, 'b': b}
Tim Peters2f93e282001-10-04 05:27:00 +000088
Georg Brandl48545522008-02-02 10:12:36 +000089 # XXX Hack so this passes before 2.3 when -Qnew is specified.
90 if meth == "__div__" and 1/2 == 0.5:
91 meth = "__truediv__"
Tim Peters2f93e282001-10-04 05:27:00 +000092
Georg Brandl48545522008-02-02 10:12:36 +000093 if meth == '__divmod__': pass
Tim Peters2f93e282001-10-04 05:27:00 +000094
Georg Brandl48545522008-02-02 10:12:36 +000095 self.assertEqual(eval(expr, d), res)
96 t = type(a)
97 m = getattr(t, meth)
98 while meth not in t.__dict__:
99 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000100 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
101 # method object; the getattr() below obtains its underlying function.
102 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000103 self.assertEqual(m(a, b), res)
104 bm = getattr(a, meth)
105 self.assertEqual(bm(b), res)
Tim Peters2f93e282001-10-04 05:27:00 +0000106
Georg Brandl48545522008-02-02 10:12:36 +0000107 def ternop_test(self, a, b, c, res, expr="a[b:c]", meth="__getslice__"):
108 d = {'a': a, 'b': b, 'c': c}
109 self.assertEqual(eval(expr, d), res)
110 t = type(a)
111 m = getattr(t, meth)
112 while meth not in t.__dict__:
113 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000114 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
115 # method object; the getattr() below obtains its underlying function.
116 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000117 self.assertEqual(m(a, b, c), res)
118 bm = getattr(a, meth)
119 self.assertEqual(bm(b, c), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000120
Georg Brandl48545522008-02-02 10:12:36 +0000121 def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
122 d = {'a': deepcopy(a), 'b': b}
123 exec stmt in d
124 self.assertEqual(d['a'], res)
125 t = type(a)
126 m = getattr(t, meth)
127 while meth not in t.__dict__:
128 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000129 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
130 # method object; the getattr() below obtains its underlying function.
131 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000132 d['a'] = deepcopy(a)
133 m(d['a'], b)
134 self.assertEqual(d['a'], res)
135 d['a'] = deepcopy(a)
136 bm = getattr(d['a'], meth)
137 bm(b)
138 self.assertEqual(d['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000139
Georg Brandl48545522008-02-02 10:12:36 +0000140 def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
141 d = {'a': deepcopy(a), 'b': b, 'c': c}
142 exec stmt in d
143 self.assertEqual(d['a'], res)
144 t = type(a)
145 m = getattr(t, meth)
146 while meth not in t.__dict__:
147 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000148 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
149 # method object; the getattr() below obtains its underlying function.
150 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000151 d['a'] = deepcopy(a)
152 m(d['a'], b, c)
153 self.assertEqual(d['a'], res)
154 d['a'] = deepcopy(a)
155 bm = getattr(d['a'], meth)
156 bm(b, c)
157 self.assertEqual(d['a'], res)
158
159 def set3op_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
160 dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
161 exec stmt in dictionary
162 self.assertEqual(dictionary['a'], res)
163 t = type(a)
164 while meth not in t.__dict__:
165 t = t.__bases__[0]
166 m = getattr(t, meth)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000167 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
168 # method object; the getattr() below obtains its underlying function.
169 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl48545522008-02-02 10:12:36 +0000170 dictionary['a'] = deepcopy(a)
171 m(dictionary['a'], b, c, d)
172 self.assertEqual(dictionary['a'], res)
173 dictionary['a'] = deepcopy(a)
174 bm = getattr(dictionary['a'], meth)
175 bm(b, c, d)
176 self.assertEqual(dictionary['a'], res)
177
178 def test_lists(self):
179 # Testing list operations...
180 # Asserts are within individual test methods
181 self.binop_test([1], [2], [1,2], "a+b", "__add__")
182 self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
183 self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
184 self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
185 self.ternop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
186 self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
187 self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
188 self.unop_test([1,2,3], 3, "len(a)", "__len__")
189 self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
190 self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
191 self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
192 self.set3op_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
193 "__setslice__")
194
195 def test_dicts(self):
196 # Testing dict operations...
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000197 if hasattr(dict, '__cmp__'): # PyPy has only rich comparison on dicts
198 self.binop_test({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
199 else:
200 self.binop_test({1:2}, {2:1}, True, "a < b", "__lt__")
Georg Brandl48545522008-02-02 10:12:36 +0000201 self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
202 self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
203 self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
204
205 d = {1:2, 3:4}
206 l1 = []
207 for i in d.keys():
208 l1.append(i)
209 l = []
210 for i in iter(d):
211 l.append(i)
212 self.assertEqual(l, l1)
213 l = []
214 for i in d.__iter__():
215 l.append(i)
216 self.assertEqual(l, l1)
217 l = []
218 for i in dict.__iter__(d):
219 l.append(i)
220 self.assertEqual(l, l1)
221 d = {1:2, 3:4}
222 self.unop_test(d, 2, "len(a)", "__len__")
223 self.assertEqual(eval(repr(d), {}), d)
224 self.assertEqual(eval(d.__repr__(), {}), d)
225 self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
226 "__setitem__")
227
228 # Tests for unary and binary operators
229 def number_operators(self, a, b, skip=[]):
230 dict = {'a': a, 'b': b}
231
232 for name, expr in self.binops.items():
233 if name not in skip:
234 name = "__%s__" % name
235 if hasattr(a, name):
236 res = eval(expr, dict)
237 self.binop_test(a, b, res, expr, name)
238
239 for name, expr in self.unops.items():
240 if name not in skip:
241 name = "__%s__" % name
242 if hasattr(a, name):
243 res = eval(expr, dict)
244 self.unop_test(a, res, expr, name)
245
246 def test_ints(self):
247 # Testing int operations...
248 self.number_operators(100, 3)
249 # The following crashes in Python 2.2
250 self.assertEqual((1).__nonzero__(), 1)
251 self.assertEqual((0).__nonzero__(), 0)
252 # This returns 'NotImplemented' in Python 2.2
253 class C(int):
254 def __add__(self, other):
255 return NotImplemented
256 self.assertEqual(C(5L), 5)
Tim Peters25786c02001-09-02 08:22:48 +0000257 try:
Georg Brandl48545522008-02-02 10:12:36 +0000258 C() + ""
Tim Peters25786c02001-09-02 08:22:48 +0000259 except TypeError:
260 pass
261 else:
Georg Brandl48545522008-02-02 10:12:36 +0000262 self.fail("NotImplemented should have caused TypeError")
263 import sys
Tim Peters1fc240e2001-10-26 05:06:50 +0000264 try:
Georg Brandl48545522008-02-02 10:12:36 +0000265 C(sys.maxint+1)
266 except OverflowError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000267 pass
268 else:
Georg Brandl48545522008-02-02 10:12:36 +0000269 self.fail("should have raised OverflowError")
Tim Peters1fc240e2001-10-26 05:06:50 +0000270
Georg Brandl48545522008-02-02 10:12:36 +0000271 def test_longs(self):
272 # Testing long operations...
273 self.number_operators(100L, 3L)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000274
Georg Brandl48545522008-02-02 10:12:36 +0000275 def test_floats(self):
276 # Testing float operations...
277 self.number_operators(100.0, 3.0)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000278
Georg Brandl48545522008-02-02 10:12:36 +0000279 def test_complexes(self):
280 # Testing complex operations...
281 self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
282 'int', 'long', 'float'])
Tim Peters5d2b77c2001-09-03 05:47:38 +0000283
Georg Brandl48545522008-02-02 10:12:36 +0000284 class Number(complex):
285 __slots__ = ['prec']
286 def __new__(cls, *args, **kwds):
287 result = complex.__new__(cls, *args)
288 result.prec = kwds.get('prec', 12)
289 return result
290 def __repr__(self):
291 prec = self.prec
292 if self.imag == 0.0:
293 return "%.*g" % (prec, self.real)
294 if self.real == 0.0:
295 return "%.*gj" % (prec, self.imag)
296 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
297 __str__ = __repr__
Tim Peters5d2b77c2001-09-03 05:47:38 +0000298
Georg Brandl48545522008-02-02 10:12:36 +0000299 a = Number(3.14, prec=6)
300 self.assertEqual(repr(a), "3.14")
301 self.assertEqual(a.prec, 6)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000302
Georg Brandl48545522008-02-02 10:12:36 +0000303 a = Number(a, prec=2)
304 self.assertEqual(repr(a), "3.1")
305 self.assertEqual(a.prec, 2)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000306
Georg Brandl48545522008-02-02 10:12:36 +0000307 a = Number(234.5)
308 self.assertEqual(repr(a), "234.5")
309 self.assertEqual(a.prec, 12)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000310
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000311 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +0000312 def test_spam_lists(self):
313 # Testing spamlist operations...
314 import copy, xxsubtype as spam
Tim Peters37a309d2001-09-04 01:20:04 +0000315
Georg Brandl48545522008-02-02 10:12:36 +0000316 def spamlist(l, memo=None):
317 import xxsubtype as spam
318 return spam.spamlist(l)
Tim Peters37a309d2001-09-04 01:20:04 +0000319
Georg Brandl48545522008-02-02 10:12:36 +0000320 # This is an ugly hack:
321 copy._deepcopy_dispatch[spam.spamlist] = spamlist
Tim Peters37a309d2001-09-04 01:20:04 +0000322
Georg Brandl48545522008-02-02 10:12:36 +0000323 self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
324 "__add__")
325 self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
326 self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
327 self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
328 self.ternop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
329 "__getslice__")
330 self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
331 "__iadd__")
332 self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
333 "__imul__")
334 self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
335 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
336 "__mul__")
337 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
338 "__rmul__")
339 self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
340 "__setitem__")
341 self.set3op_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
342 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
343 # Test subclassing
344 class C(spam.spamlist):
345 def foo(self): return 1
346 a = C()
347 self.assertEqual(a, [])
348 self.assertEqual(a.foo(), 1)
349 a.append(100)
350 self.assertEqual(a, [100])
351 self.assertEqual(a.getstate(), 0)
352 a.setstate(42)
353 self.assertEqual(a.getstate(), 42)
Tim Peters37a309d2001-09-04 01:20:04 +0000354
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000355 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +0000356 def test_spam_dicts(self):
357 # Testing spamdict operations...
358 import copy, xxsubtype as spam
359 def spamdict(d, memo=None):
360 import xxsubtype as spam
361 sd = spam.spamdict()
362 for k, v in d.items():
363 sd[k] = v
364 return sd
365 # This is an ugly hack:
366 copy._deepcopy_dispatch[spam.spamdict] = spamdict
Tim Peters37a309d2001-09-04 01:20:04 +0000367
Georg Brandl48545522008-02-02 10:12:36 +0000368 self.binop_test(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)",
369 "__cmp__")
370 self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
371 self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
372 self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
373 d = spamdict({1:2,3:4})
374 l1 = []
375 for i in d.keys():
376 l1.append(i)
377 l = []
378 for i in iter(d):
379 l.append(i)
380 self.assertEqual(l, l1)
381 l = []
382 for i in d.__iter__():
383 l.append(i)
384 self.assertEqual(l, l1)
385 l = []
386 for i in type(spamdict({})).__iter__(d):
387 l.append(i)
388 self.assertEqual(l, l1)
389 straightd = {1:2, 3:4}
390 spamd = spamdict(straightd)
391 self.unop_test(spamd, 2, "len(a)", "__len__")
392 self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
393 self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
394 "a[b]=c", "__setitem__")
395 # Test subclassing
396 class C(spam.spamdict):
397 def foo(self): return 1
398 a = C()
399 self.assertEqual(a.items(), [])
400 self.assertEqual(a.foo(), 1)
401 a['foo'] = 'bar'
402 self.assertEqual(a.items(), [('foo', 'bar')])
403 self.assertEqual(a.getstate(), 0)
404 a.setstate(100)
405 self.assertEqual(a.getstate(), 100)
Tim Peters37a309d2001-09-04 01:20:04 +0000406
Georg Brandl48545522008-02-02 10:12:36 +0000407class ClassPropertiesAndMethods(unittest.TestCase):
Tim Peters37a309d2001-09-04 01:20:04 +0000408
Georg Brandl48545522008-02-02 10:12:36 +0000409 def test_python_dicts(self):
410 # Testing Python subclass of dict...
411 self.assert_(issubclass(dict, dict))
412 self.assert_(isinstance({}, dict))
413 d = dict()
414 self.assertEqual(d, {})
415 self.assert_(d.__class__ is dict)
416 self.assert_(isinstance(d, dict))
417 class C(dict):
418 state = -1
419 def __init__(self_local, *a, **kw):
420 if a:
421 self.assertEqual(len(a), 1)
422 self_local.state = a[0]
423 if kw:
424 for k, v in kw.items():
425 self_local[v] = k
426 def __getitem__(self, key):
427 return self.get(key, 0)
428 def __setitem__(self_local, key, value):
429 self.assert_(isinstance(key, type(0)))
430 dict.__setitem__(self_local, key, value)
431 def setstate(self, state):
432 self.state = state
433 def getstate(self):
434 return self.state
435 self.assert_(issubclass(C, dict))
436 a1 = C(12)
437 self.assertEqual(a1.state, 12)
438 a2 = C(foo=1, bar=2)
439 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
440 a = C()
441 self.assertEqual(a.state, -1)
442 self.assertEqual(a.getstate(), -1)
443 a.setstate(0)
444 self.assertEqual(a.state, 0)
445 self.assertEqual(a.getstate(), 0)
446 a.setstate(10)
447 self.assertEqual(a.state, 10)
448 self.assertEqual(a.getstate(), 10)
449 self.assertEqual(a[42], 0)
450 a[42] = 24
451 self.assertEqual(a[42], 24)
452 N = 50
453 for i in range(N):
454 a[i] = C()
455 for j in range(N):
456 a[i][j] = i*j
457 for i in range(N):
458 for j in range(N):
459 self.assertEqual(a[i][j], i*j)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000460
Georg Brandl48545522008-02-02 10:12:36 +0000461 def test_python_lists(self):
462 # Testing Python subclass of list...
463 class C(list):
464 def __getitem__(self, i):
465 return list.__getitem__(self, i) + 100
466 def __getslice__(self, i, j):
467 return (i, j)
468 a = C()
469 a.extend([0,1,2])
470 self.assertEqual(a[0], 100)
471 self.assertEqual(a[1], 101)
472 self.assertEqual(a[2], 102)
473 self.assertEqual(a[100:200], (100,200))
Tim Peterscaaff8d2001-09-10 23:12:14 +0000474
Georg Brandl48545522008-02-02 10:12:36 +0000475 def test_metaclass(self):
476 # Testing __metaclass__...
477 class C:
Guido van Rossume54616c2001-12-14 04:19:56 +0000478 __metaclass__ = type
Georg Brandl48545522008-02-02 10:12:36 +0000479 def __init__(self):
480 self.__state = 0
481 def getstate(self):
482 return self.__state
483 def setstate(self, state):
484 self.__state = state
485 a = C()
486 self.assertEqual(a.getstate(), 0)
487 a.setstate(10)
488 self.assertEqual(a.getstate(), 10)
489 class D:
490 class __metaclass__(type):
491 def myself(cls): return cls
492 self.assertEqual(D.myself(), D)
493 d = D()
494 self.assertEqual(d.__class__, D)
495 class M1(type):
496 def __new__(cls, name, bases, dict):
497 dict['__spam__'] = 1
498 return type.__new__(cls, name, bases, dict)
499 class C:
500 __metaclass__ = M1
501 self.assertEqual(C.__spam__, 1)
502 c = C()
503 self.assertEqual(c.__spam__, 1)
Guido van Rossume54616c2001-12-14 04:19:56 +0000504
Georg Brandl48545522008-02-02 10:12:36 +0000505 class _instance(object):
506 pass
507 class M2(object):
508 @staticmethod
509 def __new__(cls, name, bases, dict):
510 self = object.__new__(cls)
511 self.name = name
512 self.bases = bases
513 self.dict = dict
514 return self
515 def __call__(self):
516 it = _instance()
517 # Early binding of methods
518 for key in self.dict:
519 if key.startswith("__"):
520 continue
521 setattr(it, key, self.dict[key].__get__(it, self))
522 return it
523 class C:
524 __metaclass__ = M2
525 def spam(self):
526 return 42
527 self.assertEqual(C.name, 'C')
528 self.assertEqual(C.bases, ())
529 self.assert_('spam' in C.dict)
530 c = C()
531 self.assertEqual(c.spam(), 42)
Guido van Rossum9a818922002-11-14 19:50:14 +0000532
Georg Brandl48545522008-02-02 10:12:36 +0000533 # More metaclass examples
Guido van Rossum9a818922002-11-14 19:50:14 +0000534
Georg Brandl48545522008-02-02 10:12:36 +0000535 class autosuper(type):
536 # Automatically add __super to the class
537 # This trick only works for dynamic classes
538 def __new__(metaclass, name, bases, dict):
539 cls = super(autosuper, metaclass).__new__(metaclass,
540 name, bases, dict)
541 # Name mangling for __super removes leading underscores
542 while name[:1] == "_":
543 name = name[1:]
544 if name:
545 name = "_%s__super" % name
546 else:
547 name = "__super"
548 setattr(cls, name, super(cls))
549 return cls
550 class A:
551 __metaclass__ = autosuper
552 def meth(self):
553 return "A"
554 class B(A):
555 def meth(self):
556 return "B" + self.__super.meth()
557 class C(A):
558 def meth(self):
559 return "C" + self.__super.meth()
560 class D(C, B):
561 def meth(self):
562 return "D" + self.__super.meth()
563 self.assertEqual(D().meth(), "DCBA")
564 class E(B, C):
565 def meth(self):
566 return "E" + self.__super.meth()
567 self.assertEqual(E().meth(), "EBCA")
Guido van Rossum9a818922002-11-14 19:50:14 +0000568
Georg Brandl48545522008-02-02 10:12:36 +0000569 class autoproperty(type):
570 # Automatically create property attributes when methods
571 # named _get_x and/or _set_x are found
572 def __new__(metaclass, name, bases, dict):
573 hits = {}
574 for key, val in dict.iteritems():
575 if key.startswith("_get_"):
576 key = key[5:]
577 get, set = hits.get(key, (None, None))
578 get = val
579 hits[key] = get, set
580 elif key.startswith("_set_"):
581 key = key[5:]
582 get, set = hits.get(key, (None, None))
583 set = val
584 hits[key] = get, set
585 for key, (get, set) in hits.iteritems():
586 dict[key] = property(get, set)
587 return super(autoproperty, metaclass).__new__(metaclass,
588 name, bases, dict)
589 class A:
590 __metaclass__ = autoproperty
591 def _get_x(self):
592 return -self.__x
593 def _set_x(self, x):
594 self.__x = -x
595 a = A()
596 self.assert_(not hasattr(a, "x"))
597 a.x = 12
598 self.assertEqual(a.x, 12)
599 self.assertEqual(a._A__x, -12)
Guido van Rossum9a818922002-11-14 19:50:14 +0000600
Georg Brandl48545522008-02-02 10:12:36 +0000601 class multimetaclass(autoproperty, autosuper):
602 # Merge of multiple cooperating metaclasses
603 pass
604 class A:
605 __metaclass__ = multimetaclass
606 def _get_x(self):
607 return "A"
608 class B(A):
609 def _get_x(self):
610 return "B" + self.__super._get_x()
611 class C(A):
612 def _get_x(self):
613 return "C" + self.__super._get_x()
614 class D(C, B):
615 def _get_x(self):
616 return "D" + self.__super._get_x()
617 self.assertEqual(D().x, "DCBA")
Guido van Rossum9a818922002-11-14 19:50:14 +0000618
Georg Brandl48545522008-02-02 10:12:36 +0000619 # Make sure type(x) doesn't call x.__class__.__init__
620 class T(type):
621 counter = 0
622 def __init__(self, *args):
623 T.counter += 1
624 class C:
625 __metaclass__ = T
626 self.assertEqual(T.counter, 1)
627 a = C()
628 self.assertEqual(type(a), C)
629 self.assertEqual(T.counter, 1)
Guido van Rossum9a818922002-11-14 19:50:14 +0000630
Georg Brandl48545522008-02-02 10:12:36 +0000631 class C(object): pass
632 c = C()
633 try: c()
634 except TypeError: pass
635 else: self.fail("calling object w/o call method should raise "
636 "TypeError")
Guido van Rossum9a818922002-11-14 19:50:14 +0000637
Georg Brandl48545522008-02-02 10:12:36 +0000638 # Testing code to find most derived baseclass
639 class A(type):
640 def __new__(*args, **kwargs):
641 return type.__new__(*args, **kwargs)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000642
Georg Brandl48545522008-02-02 10:12:36 +0000643 class B(object):
644 pass
645
646 class C(object):
647 __metaclass__ = A
648
649 # The most derived metaclass of D is A rather than type.
650 class D(B, C):
651 pass
652
653 def test_module_subclasses(self):
654 # Testing Python subclass of module...
655 log = []
656 import types, sys
657 MT = type(sys)
658 class MM(MT):
659 def __init__(self, name):
660 MT.__init__(self, name)
661 def __getattribute__(self, name):
662 log.append(("getattr", name))
663 return MT.__getattribute__(self, name)
664 def __setattr__(self, name, value):
665 log.append(("setattr", name, value))
666 MT.__setattr__(self, name, value)
667 def __delattr__(self, name):
668 log.append(("delattr", name))
669 MT.__delattr__(self, name)
670 a = MM("a")
671 a.foo = 12
672 x = a.foo
673 del a.foo
674 self.assertEqual(log, [("setattr", "foo", 12),
675 ("getattr", "foo"),
676 ("delattr", "foo")])
677
678 # http://python.org/sf/1174712
679 try:
680 class Module(types.ModuleType, str):
681 pass
682 except TypeError:
683 pass
684 else:
685 self.fail("inheriting from ModuleType and str at the same time "
686 "should fail")
687
688 def test_multiple_inheritence(self):
689 # Testing multiple inheritance...
690 class C(object):
691 def __init__(self):
692 self.__state = 0
693 def getstate(self):
694 return self.__state
695 def setstate(self, state):
696 self.__state = state
697 a = C()
698 self.assertEqual(a.getstate(), 0)
699 a.setstate(10)
700 self.assertEqual(a.getstate(), 10)
701 class D(dict, C):
702 def __init__(self):
703 type({}).__init__(self)
704 C.__init__(self)
705 d = D()
706 self.assertEqual(d.keys(), [])
707 d["hello"] = "world"
708 self.assertEqual(d.items(), [("hello", "world")])
709 self.assertEqual(d["hello"], "world")
710 self.assertEqual(d.getstate(), 0)
711 d.setstate(10)
712 self.assertEqual(d.getstate(), 10)
713 self.assertEqual(D.__mro__, (D, dict, C, object))
714
715 # SF bug #442833
716 class Node(object):
717 def __int__(self):
718 return int(self.foo())
719 def foo(self):
720 return "23"
721 class Frag(Node, list):
722 def foo(self):
723 return "42"
724 self.assertEqual(Node().__int__(), 23)
725 self.assertEqual(int(Node()), 23)
726 self.assertEqual(Frag().__int__(), 42)
727 self.assertEqual(int(Frag()), 42)
728
729 # MI mixing classic and new-style classes.
730
731 class A:
732 x = 1
733
734 class B(A):
735 pass
736
737 class C(A):
738 x = 2
739
740 class D(B, C):
741 pass
742 self.assertEqual(D.x, 1)
743
744 # Classic MRO is preserved for a classic base class.
745 class E(D, object):
746 pass
747 self.assertEqual(E.__mro__, (E, D, B, A, C, object))
748 self.assertEqual(E.x, 1)
749
750 # But with a mix of classic bases, their MROs are combined using
751 # new-style MRO.
752 class F(B, C, object):
753 pass
754 self.assertEqual(F.__mro__, (F, B, C, A, object))
755 self.assertEqual(F.x, 2)
756
757 # Try something else.
758 class C:
759 def cmethod(self):
760 return "C a"
761 def all_method(self):
762 return "C b"
763
764 class M1(C, object):
765 def m1method(self):
766 return "M1 a"
767 def all_method(self):
768 return "M1 b"
769
770 self.assertEqual(M1.__mro__, (M1, C, object))
771 m = M1()
772 self.assertEqual(m.cmethod(), "C a")
773 self.assertEqual(m.m1method(), "M1 a")
774 self.assertEqual(m.all_method(), "M1 b")
775
776 class D(C):
777 def dmethod(self):
778 return "D a"
779 def all_method(self):
780 return "D b"
781
782 class M2(D, object):
783 def m2method(self):
784 return "M2 a"
785 def all_method(self):
786 return "M2 b"
787
788 self.assertEqual(M2.__mro__, (M2, D, C, object))
789 m = M2()
790 self.assertEqual(m.cmethod(), "C a")
791 self.assertEqual(m.dmethod(), "D a")
792 self.assertEqual(m.m2method(), "M2 a")
793 self.assertEqual(m.all_method(), "M2 b")
794
795 class M3(M1, M2, object):
796 def m3method(self):
797 return "M3 a"
798 def all_method(self):
799 return "M3 b"
800 self.assertEqual(M3.__mro__, (M3, M1, M2, D, C, object))
801 m = M3()
802 self.assertEqual(m.cmethod(), "C a")
803 self.assertEqual(m.dmethod(), "D a")
804 self.assertEqual(m.m1method(), "M1 a")
805 self.assertEqual(m.m2method(), "M2 a")
806 self.assertEqual(m.m3method(), "M3 a")
807 self.assertEqual(m.all_method(), "M3 b")
808
809 class Classic:
810 pass
811 try:
812 class New(Classic):
813 __metaclass__ = type
814 except TypeError:
815 pass
816 else:
817 self.fail("new class with only classic bases - shouldn't be")
818
819 def test_diamond_inheritence(self):
820 # Testing multiple inheritance special cases...
821 class A(object):
822 def spam(self): return "A"
823 self.assertEqual(A().spam(), "A")
824 class B(A):
825 def boo(self): return "B"
826 def spam(self): return "B"
827 self.assertEqual(B().spam(), "B")
828 self.assertEqual(B().boo(), "B")
829 class C(A):
830 def boo(self): return "C"
831 self.assertEqual(C().spam(), "A")
832 self.assertEqual(C().boo(), "C")
833 class D(B, C): pass
834 self.assertEqual(D().spam(), "B")
835 self.assertEqual(D().boo(), "B")
836 self.assertEqual(D.__mro__, (D, B, C, A, object))
837 class E(C, B): pass
838 self.assertEqual(E().spam(), "B")
839 self.assertEqual(E().boo(), "C")
840 self.assertEqual(E.__mro__, (E, C, B, A, object))
841 # MRO order disagreement
842 try:
843 class F(D, E): pass
844 except TypeError:
845 pass
846 else:
847 self.fail("expected MRO order disagreement (F)")
848 try:
849 class G(E, D): pass
850 except TypeError:
851 pass
852 else:
853 self.fail("expected MRO order disagreement (G)")
854
855 # see thread python-dev/2002-October/029035.html
856 def test_ex5_from_c3_switch(self):
857 # Testing ex5 from C3 switch discussion...
858 class A(object): pass
859 class B(object): pass
860 class C(object): pass
861 class X(A): pass
862 class Y(A): pass
863 class Z(X,B,Y,C): pass
864 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
865
866 # see "A Monotonic Superclass Linearization for Dylan",
867 # by Kim Barrett et al. (OOPSLA 1996)
868 def test_monotonicity(self):
869 # Testing MRO monotonicity...
870 class Boat(object): pass
871 class DayBoat(Boat): pass
872 class WheelBoat(Boat): pass
873 class EngineLess(DayBoat): pass
874 class SmallMultihull(DayBoat): pass
875 class PedalWheelBoat(EngineLess,WheelBoat): pass
876 class SmallCatamaran(SmallMultihull): pass
877 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
878
879 self.assertEqual(PedalWheelBoat.__mro__,
880 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
881 self.assertEqual(SmallCatamaran.__mro__,
882 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
883 self.assertEqual(Pedalo.__mro__,
884 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
885 SmallMultihull, DayBoat, WheelBoat, Boat, object))
886
887 # see "A Monotonic Superclass Linearization for Dylan",
888 # by Kim Barrett et al. (OOPSLA 1996)
889 def test_consistency_with_epg(self):
890 # Testing consistentcy with EPG...
891 class Pane(object): pass
892 class ScrollingMixin(object): pass
893 class EditingMixin(object): pass
894 class ScrollablePane(Pane,ScrollingMixin): pass
895 class EditablePane(Pane,EditingMixin): pass
896 class EditableScrollablePane(ScrollablePane,EditablePane): pass
897
898 self.assertEqual(EditableScrollablePane.__mro__,
899 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
900 ScrollingMixin, EditingMixin, object))
901
902 def test_mro_disagreement(self):
903 # Testing error messages for MRO disagreement...
904 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000905order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000906
Georg Brandl48545522008-02-02 10:12:36 +0000907 def raises(exc, expected, callable, *args):
908 try:
909 callable(*args)
910 except exc, msg:
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000911 # the exact msg is generally considered an impl detail
912 if test_support.check_impl_detail():
913 if not str(msg).startswith(expected):
914 self.fail("Message %r, expected %r" %
915 (str(msg), expected))
Georg Brandl48545522008-02-02 10:12:36 +0000916 else:
917 self.fail("Expected %s" % exc)
918
919 class A(object): pass
920 class B(A): pass
921 class C(object): pass
922
923 # Test some very simple errors
924 raises(TypeError, "duplicate base class A",
925 type, "X", (A, A), {})
926 raises(TypeError, mro_err_msg,
927 type, "X", (A, B), {})
928 raises(TypeError, mro_err_msg,
929 type, "X", (A, C, B), {})
930 # Test a slightly more complex error
931 class GridLayout(object): pass
932 class HorizontalGrid(GridLayout): pass
933 class VerticalGrid(GridLayout): pass
934 class HVGrid(HorizontalGrid, VerticalGrid): pass
935 class VHGrid(VerticalGrid, HorizontalGrid): pass
936 raises(TypeError, mro_err_msg,
937 type, "ConfusedGrid", (HVGrid, VHGrid), {})
938
939 def test_object_class(self):
940 # Testing object class...
941 a = object()
942 self.assertEqual(a.__class__, object)
943 self.assertEqual(type(a), object)
944 b = object()
945 self.assertNotEqual(a, b)
946 self.assertFalse(hasattr(a, "foo"))
Guido van Rossumd32047f2002-11-25 21:38:52 +0000947 try:
Georg Brandl48545522008-02-02 10:12:36 +0000948 a.foo = 12
949 except (AttributeError, TypeError):
950 pass
Guido van Rossumd32047f2002-11-25 21:38:52 +0000951 else:
Georg Brandl48545522008-02-02 10:12:36 +0000952 self.fail("object() should not allow setting a foo attribute")
953 self.assertFalse(hasattr(object(), "__dict__"))
Guido van Rossumd32047f2002-11-25 21:38:52 +0000954
Georg Brandl48545522008-02-02 10:12:36 +0000955 class Cdict(object):
956 pass
957 x = Cdict()
958 self.assertEqual(x.__dict__, {})
959 x.foo = 1
960 self.assertEqual(x.foo, 1)
961 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossum37202612001-08-09 19:45:21 +0000962
Georg Brandl48545522008-02-02 10:12:36 +0000963 def test_slots(self):
964 # Testing __slots__...
965 class C0(object):
966 __slots__ = []
967 x = C0()
968 self.assertFalse(hasattr(x, "__dict__"))
969 self.assertFalse(hasattr(x, "foo"))
Guido van Rossum37202612001-08-09 19:45:21 +0000970
Georg Brandl48545522008-02-02 10:12:36 +0000971 class C1(object):
972 __slots__ = ['a']
973 x = C1()
974 self.assertFalse(hasattr(x, "__dict__"))
975 self.assertFalse(hasattr(x, "a"))
976 x.a = 1
977 self.assertEqual(x.a, 1)
978 x.a = None
979 self.assertEqual(x.a, None)
980 del x.a
981 self.assertFalse(hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000982
Georg Brandl48545522008-02-02 10:12:36 +0000983 class C3(object):
984 __slots__ = ['a', 'b', 'c']
985 x = C3()
986 self.assertFalse(hasattr(x, "__dict__"))
987 self.assertFalse(hasattr(x, 'a'))
988 self.assertFalse(hasattr(x, 'b'))
989 self.assertFalse(hasattr(x, 'c'))
990 x.a = 1
991 x.b = 2
992 x.c = 3
993 self.assertEqual(x.a, 1)
994 self.assertEqual(x.b, 2)
995 self.assertEqual(x.c, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000996
Georg Brandl48545522008-02-02 10:12:36 +0000997 class C4(object):
998 """Validate name mangling"""
999 __slots__ = ['__a']
1000 def __init__(self, value):
1001 self.__a = value
1002 def get(self):
1003 return self.__a
1004 x = C4(5)
1005 self.assertFalse(hasattr(x, '__dict__'))
1006 self.assertFalse(hasattr(x, '__a'))
1007 self.assertEqual(x.get(), 5)
1008 try:
1009 x.__a = 6
1010 except AttributeError:
1011 pass
1012 else:
1013 self.fail("Double underscored names not mangled")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001014
Georg Brandl48545522008-02-02 10:12:36 +00001015 # Make sure slot names are proper identifiers
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001016 try:
1017 class C(object):
Georg Brandl48545522008-02-02 10:12:36 +00001018 __slots__ = [None]
Guido van Rossum843daa82001-09-18 20:04:26 +00001019 except TypeError:
1020 pass
1021 else:
Georg Brandl48545522008-02-02 10:12:36 +00001022 self.fail("[None] slots not caught")
Tim Peters66c1a522001-09-24 21:17:50 +00001023 try:
Georg Brandl48545522008-02-02 10:12:36 +00001024 class C(object):
1025 __slots__ = ["foo bar"]
1026 except TypeError:
Georg Brandl533ff6f2006-03-08 18:09:27 +00001027 pass
Georg Brandl48545522008-02-02 10:12:36 +00001028 else:
1029 self.fail("['foo bar'] slots not caught")
1030 try:
1031 class C(object):
1032 __slots__ = ["foo\0bar"]
1033 except TypeError:
1034 pass
1035 else:
1036 self.fail("['foo\\0bar'] slots not caught")
1037 try:
1038 class C(object):
1039 __slots__ = ["1"]
1040 except TypeError:
1041 pass
1042 else:
1043 self.fail("['1'] slots not caught")
1044 try:
1045 class C(object):
1046 __slots__ = [""]
1047 except TypeError:
1048 pass
1049 else:
1050 self.fail("[''] slots not caught")
1051 class C(object):
1052 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1053 # XXX(nnorwitz): was there supposed to be something tested
1054 # from the class above?
Georg Brandl533ff6f2006-03-08 18:09:27 +00001055
Georg Brandl48545522008-02-02 10:12:36 +00001056 # Test a single string is not expanded as a sequence.
1057 class C(object):
1058 __slots__ = "abc"
1059 c = C()
1060 c.abc = 5
1061 self.assertEqual(c.abc, 5)
Georg Brandle9462c72006-08-04 18:03:37 +00001062
Georg Brandl48545522008-02-02 10:12:36 +00001063 # Test unicode slot names
1064 try:
1065 unicode
1066 except NameError:
1067 pass
1068 else:
1069 # Test a single unicode string is not expanded as a sequence.
1070 class C(object):
1071 __slots__ = unicode("abc")
1072 c = C()
1073 c.abc = 5
1074 self.assertEqual(c.abc, 5)
Georg Brandle9462c72006-08-04 18:03:37 +00001075
Georg Brandl48545522008-02-02 10:12:36 +00001076 # _unicode_to_string used to modify slots in certain circumstances
1077 slots = (unicode("foo"), unicode("bar"))
1078 class C(object):
1079 __slots__ = slots
1080 x = C()
1081 x.foo = 5
1082 self.assertEqual(x.foo, 5)
1083 self.assertEqual(type(slots[0]), unicode)
1084 # this used to leak references
Guido van Rossumd1ef7892007-11-10 22:12:24 +00001085 try:
Georg Brandl48545522008-02-02 10:12:36 +00001086 class C(object):
1087 __slots__ = [unichr(128)]
1088 except (TypeError, UnicodeEncodeError):
Guido van Rossumd1ef7892007-11-10 22:12:24 +00001089 pass
Tim Peters8fa45672001-09-13 21:01:29 +00001090 else:
Georg Brandl48545522008-02-02 10:12:36 +00001091 self.fail("[unichr(128)] slots not caught")
Tim Peters8fa45672001-09-13 21:01:29 +00001092
Georg Brandl48545522008-02-02 10:12:36 +00001093 # Test leaks
1094 class Counted(object):
1095 counter = 0 # counts the number of instances alive
1096 def __init__(self):
1097 Counted.counter += 1
1098 def __del__(self):
1099 Counted.counter -= 1
1100 class C(object):
1101 __slots__ = ['a', 'b', 'c']
Guido van Rossum8c842552002-03-14 23:05:54 +00001102 x = C()
Georg Brandl48545522008-02-02 10:12:36 +00001103 x.a = Counted()
1104 x.b = Counted()
1105 x.c = Counted()
1106 self.assertEqual(Counted.counter, 3)
1107 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001108 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001109 self.assertEqual(Counted.counter, 0)
1110 class D(C):
1111 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00001112 x = D()
Georg Brandl48545522008-02-02 10:12:36 +00001113 x.a = Counted()
1114 x.z = Counted()
1115 self.assertEqual(Counted.counter, 2)
1116 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001117 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001118 self.assertEqual(Counted.counter, 0)
1119 class E(D):
1120 __slots__ = ['e']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00001121 x = E()
Georg Brandl48545522008-02-02 10:12:36 +00001122 x.a = Counted()
1123 x.z = Counted()
1124 x.e = Counted()
1125 self.assertEqual(Counted.counter, 3)
1126 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001127 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001128 self.assertEqual(Counted.counter, 0)
Guido van Rossum8c842552002-03-14 23:05:54 +00001129
Georg Brandl48545522008-02-02 10:12:36 +00001130 # Test cyclical leaks [SF bug 519621]
1131 class F(object):
1132 __slots__ = ['a', 'b']
1133 log = []
1134 s = F()
1135 s.a = [Counted(), s]
1136 self.assertEqual(Counted.counter, 1)
1137 s = None
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001138 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001139 self.assertEqual(Counted.counter, 0)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001140
Georg Brandl48545522008-02-02 10:12:36 +00001141 # Test lookup leaks [SF bug 572567]
1142 import sys,gc
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001143 if hasattr(gc, 'get_objects'):
1144 class G(object):
1145 def __cmp__(self, other):
1146 return 0
1147 __hash__ = None # Silence Py3k warning
1148 g = G()
1149 orig_objects = len(gc.get_objects())
1150 for i in xrange(10):
1151 g==g
1152 new_objects = len(gc.get_objects())
1153 self.assertEqual(orig_objects, new_objects)
1154
Georg Brandl48545522008-02-02 10:12:36 +00001155 class H(object):
1156 __slots__ = ['a', 'b']
1157 def __init__(self):
1158 self.a = 1
1159 self.b = 2
1160 def __del__(self_):
1161 self.assertEqual(self_.a, 1)
1162 self.assertEqual(self_.b, 2)
Armin Rigo581eb1e2008-10-28 17:01:21 +00001163 with test_support.captured_output('stderr') as s:
1164 h = H()
Georg Brandl48545522008-02-02 10:12:36 +00001165 del h
Armin Rigo581eb1e2008-10-28 17:01:21 +00001166 self.assertEqual(s.getvalue(), '')
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001167
Georg Brandl48545522008-02-02 10:12:36 +00001168 def test_slots_special(self):
1169 # Testing __dict__ and __weakref__ in __slots__...
1170 class D(object):
1171 __slots__ = ["__dict__"]
1172 a = D()
1173 self.assert_(hasattr(a, "__dict__"))
1174 self.assertFalse(hasattr(a, "__weakref__"))
1175 a.foo = 42
1176 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001177
Georg Brandl48545522008-02-02 10:12:36 +00001178 class W(object):
1179 __slots__ = ["__weakref__"]
1180 a = W()
1181 self.assert_(hasattr(a, "__weakref__"))
1182 self.assertFalse(hasattr(a, "__dict__"))
1183 try:
1184 a.foo = 42
1185 except AttributeError:
1186 pass
1187 else:
1188 self.fail("shouldn't be allowed to set a.foo")
1189
1190 class C1(W, D):
1191 __slots__ = []
1192 a = C1()
1193 self.assert_(hasattr(a, "__dict__"))
1194 self.assert_(hasattr(a, "__weakref__"))
1195 a.foo = 42
1196 self.assertEqual(a.__dict__, {"foo": 42})
1197
1198 class C2(D, W):
1199 __slots__ = []
1200 a = C2()
1201 self.assert_(hasattr(a, "__dict__"))
1202 self.assert_(hasattr(a, "__weakref__"))
1203 a.foo = 42
1204 self.assertEqual(a.__dict__, {"foo": 42})
1205
Amaury Forgeot d'Arc60d6c7f2008-02-15 21:22:45 +00001206 def test_slots_descriptor(self):
1207 # Issue2115: slot descriptors did not correctly check
1208 # the type of the given object
1209 import abc
1210 class MyABC:
1211 __metaclass__ = abc.ABCMeta
1212 __slots__ = "a"
1213
1214 class Unrelated(object):
1215 pass
1216 MyABC.register(Unrelated)
1217
1218 u = Unrelated()
1219 self.assert_(isinstance(u, MyABC))
1220
1221 # This used to crash
1222 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1223
Georg Brandl48545522008-02-02 10:12:36 +00001224 def test_dynamics(self):
1225 # Testing class attribute propagation...
1226 class D(object):
1227 pass
1228 class E(D):
1229 pass
1230 class F(D):
1231 pass
1232 D.foo = 1
1233 self.assertEqual(D.foo, 1)
1234 # Test that dynamic attributes are inherited
1235 self.assertEqual(E.foo, 1)
1236 self.assertEqual(F.foo, 1)
1237 # Test dynamic instances
1238 class C(object):
1239 pass
1240 a = C()
1241 self.assertFalse(hasattr(a, "foobar"))
1242 C.foobar = 2
1243 self.assertEqual(a.foobar, 2)
1244 C.method = lambda self: 42
1245 self.assertEqual(a.method(), 42)
1246 C.__repr__ = lambda self: "C()"
1247 self.assertEqual(repr(a), "C()")
1248 C.__int__ = lambda self: 100
1249 self.assertEqual(int(a), 100)
1250 self.assertEqual(a.foobar, 2)
1251 self.assertFalse(hasattr(a, "spam"))
1252 def mygetattr(self, name):
1253 if name == "spam":
1254 return "spam"
1255 raise AttributeError
1256 C.__getattr__ = mygetattr
1257 self.assertEqual(a.spam, "spam")
1258 a.new = 12
1259 self.assertEqual(a.new, 12)
1260 def mysetattr(self, name, value):
1261 if name == "spam":
1262 raise AttributeError
1263 return object.__setattr__(self, name, value)
1264 C.__setattr__ = mysetattr
1265 try:
1266 a.spam = "not spam"
1267 except AttributeError:
1268 pass
1269 else:
1270 self.fail("expected AttributeError")
1271 self.assertEqual(a.spam, "spam")
1272 class D(C):
1273 pass
1274 d = D()
1275 d.foo = 1
1276 self.assertEqual(d.foo, 1)
1277
1278 # Test handling of int*seq and seq*int
1279 class I(int):
1280 pass
1281 self.assertEqual("a"*I(2), "aa")
1282 self.assertEqual(I(2)*"a", "aa")
1283 self.assertEqual(2*I(3), 6)
1284 self.assertEqual(I(3)*2, 6)
1285 self.assertEqual(I(3)*I(2), 6)
1286
1287 # Test handling of long*seq and seq*long
1288 class L(long):
1289 pass
1290 self.assertEqual("a"*L(2L), "aa")
1291 self.assertEqual(L(2L)*"a", "aa")
1292 self.assertEqual(2*L(3), 6)
1293 self.assertEqual(L(3)*2, 6)
1294 self.assertEqual(L(3)*L(2), 6)
1295
1296 # Test comparison of classes with dynamic metaclasses
1297 class dynamicmetaclass(type):
1298 pass
1299 class someclass:
1300 __metaclass__ = dynamicmetaclass
1301 self.assertNotEqual(someclass, object)
1302
1303 def test_errors(self):
1304 # Testing errors...
1305 try:
1306 class C(list, dict):
1307 pass
1308 except TypeError:
1309 pass
1310 else:
1311 self.fail("inheritance from both list and dict should be illegal")
1312
1313 try:
1314 class C(object, None):
1315 pass
1316 except TypeError:
1317 pass
1318 else:
1319 self.fail("inheritance from non-type should be illegal")
1320 class Classic:
1321 pass
1322
1323 try:
1324 class C(type(len)):
1325 pass
1326 except TypeError:
1327 pass
1328 else:
1329 self.fail("inheritance from CFunction should be illegal")
1330
1331 try:
1332 class C(object):
1333 __slots__ = 1
1334 except TypeError:
1335 pass
1336 else:
1337 self.fail("__slots__ = 1 should be illegal")
1338
1339 try:
1340 class C(object):
1341 __slots__ = [1]
1342 except TypeError:
1343 pass
1344 else:
1345 self.fail("__slots__ = [1] should be illegal")
1346
1347 class M1(type):
1348 pass
1349 class M2(type):
1350 pass
1351 class A1(object):
1352 __metaclass__ = M1
1353 class A2(object):
1354 __metaclass__ = M2
1355 try:
1356 class B(A1, A2):
1357 pass
1358 except TypeError:
1359 pass
1360 else:
1361 self.fail("finding the most derived metaclass should have failed")
1362
1363 def test_classmethods(self):
1364 # Testing class methods...
1365 class C(object):
1366 def foo(*a): return a
1367 goo = classmethod(foo)
1368 c = C()
1369 self.assertEqual(C.goo(1), (C, 1))
1370 self.assertEqual(c.goo(1), (C, 1))
1371 self.assertEqual(c.foo(1), (c, 1))
1372 class D(C):
1373 pass
1374 d = D()
1375 self.assertEqual(D.goo(1), (D, 1))
1376 self.assertEqual(d.goo(1), (D, 1))
1377 self.assertEqual(d.foo(1), (d, 1))
1378 self.assertEqual(D.foo(d, 1), (d, 1))
1379 # Test for a specific crash (SF bug 528132)
1380 def f(cls, arg): return (cls, arg)
1381 ff = classmethod(f)
1382 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1383 self.assertEqual(ff.__get__(0)(42), (int, 42))
1384
1385 # Test super() with classmethods (SF bug 535444)
1386 self.assertEqual(C.goo.im_self, C)
1387 self.assertEqual(D.goo.im_self, D)
1388 self.assertEqual(super(D,D).goo.im_self, D)
1389 self.assertEqual(super(D,d).goo.im_self, D)
1390 self.assertEqual(super(D,D).goo(), (D,))
1391 self.assertEqual(super(D,d).goo(), (D,))
1392
1393 # Verify that argument is checked for callability (SF bug 753451)
1394 try:
1395 classmethod(1).__get__(1)
1396 except TypeError:
1397 pass
1398 else:
1399 self.fail("classmethod should check for callability")
1400
1401 # Verify that classmethod() doesn't allow keyword args
1402 try:
1403 classmethod(f, kw=1)
1404 except TypeError:
1405 pass
1406 else:
1407 self.fail("classmethod shouldn't accept keyword args")
1408
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001409 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +00001410 def test_classmethods_in_c(self):
1411 # Testing C-based class methods...
1412 import xxsubtype as spam
1413 a = (1, 2, 3)
1414 d = {'abc': 123}
1415 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1416 self.assertEqual(x, spam.spamlist)
1417 self.assertEqual(a, a1)
1418 self.assertEqual(d, d1)
1419 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1420 self.assertEqual(x, spam.spamlist)
1421 self.assertEqual(a, a1)
1422 self.assertEqual(d, d1)
1423
1424 def test_staticmethods(self):
1425 # Testing static methods...
1426 class C(object):
1427 def foo(*a): return a
1428 goo = staticmethod(foo)
1429 c = C()
1430 self.assertEqual(C.goo(1), (1,))
1431 self.assertEqual(c.goo(1), (1,))
1432 self.assertEqual(c.foo(1), (c, 1,))
1433 class D(C):
1434 pass
1435 d = D()
1436 self.assertEqual(D.goo(1), (1,))
1437 self.assertEqual(d.goo(1), (1,))
1438 self.assertEqual(d.foo(1), (d, 1))
1439 self.assertEqual(D.foo(d, 1), (d, 1))
1440
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001441 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +00001442 def test_staticmethods_in_c(self):
1443 # Testing C-based static methods...
1444 import xxsubtype as spam
1445 a = (1, 2, 3)
1446 d = {"abc": 123}
1447 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1448 self.assertEqual(x, None)
1449 self.assertEqual(a, a1)
1450 self.assertEqual(d, d1)
1451 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1452 self.assertEqual(x, None)
1453 self.assertEqual(a, a1)
1454 self.assertEqual(d, d1)
1455
1456 def test_classic(self):
1457 # Testing classic classes...
1458 class C:
1459 def foo(*a): return a
1460 goo = classmethod(foo)
1461 c = C()
1462 self.assertEqual(C.goo(1), (C, 1))
1463 self.assertEqual(c.goo(1), (C, 1))
1464 self.assertEqual(c.foo(1), (c, 1))
1465 class D(C):
1466 pass
1467 d = D()
1468 self.assertEqual(D.goo(1), (D, 1))
1469 self.assertEqual(d.goo(1), (D, 1))
1470 self.assertEqual(d.foo(1), (d, 1))
1471 self.assertEqual(D.foo(d, 1), (d, 1))
1472 class E: # *not* subclassing from C
1473 foo = C.foo
1474 self.assertEqual(E().foo, C.foo) # i.e., unbound
1475 self.assert_(repr(C.foo.__get__(C())).startswith("<bound method "))
1476
1477 def test_compattr(self):
1478 # Testing computed attributes...
1479 class C(object):
1480 class computed_attribute(object):
1481 def __init__(self, get, set=None, delete=None):
1482 self.__get = get
1483 self.__set = set
1484 self.__delete = delete
1485 def __get__(self, obj, type=None):
1486 return self.__get(obj)
1487 def __set__(self, obj, value):
1488 return self.__set(obj, value)
1489 def __delete__(self, obj):
1490 return self.__delete(obj)
1491 def __init__(self):
1492 self.__x = 0
1493 def __get_x(self):
1494 x = self.__x
1495 self.__x = x+1
1496 return x
1497 def __set_x(self, x):
1498 self.__x = x
1499 def __delete_x(self):
1500 del self.__x
1501 x = computed_attribute(__get_x, __set_x, __delete_x)
1502 a = C()
1503 self.assertEqual(a.x, 0)
1504 self.assertEqual(a.x, 1)
1505 a.x = 10
1506 self.assertEqual(a.x, 10)
1507 self.assertEqual(a.x, 11)
1508 del a.x
1509 self.assertEqual(hasattr(a, 'x'), 0)
1510
1511 def test_newslots(self):
1512 # Testing __new__ slot override...
1513 class C(list):
1514 def __new__(cls):
1515 self = list.__new__(cls)
1516 self.foo = 1
1517 return self
1518 def __init__(self):
1519 self.foo = self.foo + 2
1520 a = C()
1521 self.assertEqual(a.foo, 3)
1522 self.assertEqual(a.__class__, C)
1523 class D(C):
1524 pass
1525 b = D()
1526 self.assertEqual(b.foo, 3)
1527 self.assertEqual(b.__class__, D)
1528
1529 def test_altmro(self):
1530 # Testing mro() and overriding it...
1531 class A(object):
1532 def f(self): return "A"
1533 class B(A):
1534 pass
1535 class C(A):
1536 def f(self): return "C"
1537 class D(B, C):
1538 pass
1539 self.assertEqual(D.mro(), [D, B, C, A, object])
1540 self.assertEqual(D.__mro__, (D, B, C, A, object))
1541 self.assertEqual(D().f(), "C")
1542
1543 class PerverseMetaType(type):
1544 def mro(cls):
1545 L = type.mro(cls)
1546 L.reverse()
1547 return L
1548 class X(D,B,C,A):
1549 __metaclass__ = PerverseMetaType
1550 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1551 self.assertEqual(X().f(), "A")
1552
1553 try:
1554 class X(object):
1555 class __metaclass__(type):
1556 def mro(self):
1557 return [self, dict, object]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001558 # In CPython, the class creation above already raises
1559 # TypeError, as a protection against the fact that
1560 # instances of X would segfault it. In other Python
1561 # implementations it would be ok to let the class X
1562 # be created, but instead get a clean TypeError on the
1563 # __setitem__ below.
1564 x = object.__new__(X)
1565 x[5] = 6
Georg Brandl48545522008-02-02 10:12:36 +00001566 except TypeError:
1567 pass
1568 else:
1569 self.fail("devious mro() return not caught")
1570
1571 try:
1572 class X(object):
1573 class __metaclass__(type):
1574 def mro(self):
1575 return [1]
1576 except TypeError:
1577 pass
1578 else:
1579 self.fail("non-class mro() return not caught")
1580
1581 try:
1582 class X(object):
1583 class __metaclass__(type):
1584 def mro(self):
1585 return 1
1586 except TypeError:
1587 pass
1588 else:
1589 self.fail("non-sequence mro() return not caught")
1590
1591 def test_overloading(self):
1592 # Testing operator overloading...
1593
1594 class B(object):
1595 "Intermediate class because object doesn't have a __setattr__"
1596
1597 class C(B):
1598 def __getattr__(self, name):
1599 if name == "foo":
1600 return ("getattr", name)
1601 else:
1602 raise AttributeError
1603 def __setattr__(self, name, value):
1604 if name == "foo":
1605 self.setattr = (name, value)
1606 else:
1607 return B.__setattr__(self, name, value)
1608 def __delattr__(self, name):
1609 if name == "foo":
1610 self.delattr = name
1611 else:
1612 return B.__delattr__(self, name)
1613
1614 def __getitem__(self, key):
1615 return ("getitem", key)
1616 def __setitem__(self, key, value):
1617 self.setitem = (key, value)
1618 def __delitem__(self, key):
1619 self.delitem = key
1620
1621 def __getslice__(self, i, j):
1622 return ("getslice", i, j)
1623 def __setslice__(self, i, j, value):
1624 self.setslice = (i, j, value)
1625 def __delslice__(self, i, j):
1626 self.delslice = (i, j)
1627
1628 a = C()
1629 self.assertEqual(a.foo, ("getattr", "foo"))
1630 a.foo = 12
1631 self.assertEqual(a.setattr, ("foo", 12))
1632 del a.foo
1633 self.assertEqual(a.delattr, "foo")
1634
1635 self.assertEqual(a[12], ("getitem", 12))
1636 a[12] = 21
1637 self.assertEqual(a.setitem, (12, 21))
1638 del a[12]
1639 self.assertEqual(a.delitem, 12)
1640
1641 self.assertEqual(a[0:10], ("getslice", 0, 10))
1642 a[0:10] = "foo"
1643 self.assertEqual(a.setslice, (0, 10, "foo"))
1644 del a[0:10]
1645 self.assertEqual(a.delslice, (0, 10))
1646
1647 def test_methods(self):
1648 # Testing methods...
1649 class C(object):
1650 def __init__(self, x):
1651 self.x = x
1652 def foo(self):
1653 return self.x
1654 c1 = C(1)
1655 self.assertEqual(c1.foo(), 1)
1656 class D(C):
1657 boo = C.foo
1658 goo = c1.foo
1659 d2 = D(2)
1660 self.assertEqual(d2.foo(), 2)
1661 self.assertEqual(d2.boo(), 2)
1662 self.assertEqual(d2.goo(), 1)
1663 class E(object):
1664 foo = C.foo
1665 self.assertEqual(E().foo, C.foo) # i.e., unbound
1666 self.assert_(repr(C.foo.__get__(C(1))).startswith("<bound method "))
1667
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001668 def test_special_method_lookup(self):
1669 # The lookup of special methods bypasses __getattr__ and
1670 # __getattribute__, but they still can be descriptors.
1671
1672 def run_context(manager):
1673 with manager:
1674 pass
1675 def iden(self):
1676 return self
1677 def hello(self):
1678 return "hello"
Benjamin Peterson809e2252009-05-09 02:07:04 +00001679 def empty_seq(self):
1680 return []
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001681
1682 # It would be nice to have every special method tested here, but I'm
1683 # only listing the ones I can remember outside of typeobject.c, since it
1684 # does it right.
1685 specials = [
1686 ("__unicode__", unicode, hello),
Benjamin Peterson809e2252009-05-09 02:07:04 +00001687 ("__reversed__", reversed, empty_seq),
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001688 # These two fail because the compiler generates LOAD_ATTR to look
1689 # them up. We'd have to add a new opcode to fix this, and it's
1690 # probably not worth it.
1691 # ("__enter__", run_context, iden),
1692 # ("__exit__", run_context, iden),
1693 ]
1694
1695 class Checker(object):
1696 def __getattr__(self, attr, test=self):
1697 test.fail("__getattr__ called with {0}".format(attr))
1698 def __getattribute__(self, attr, test=self):
1699 test.fail("__getattribute__ called with {0}".format(attr))
1700 class SpecialDescr(object):
1701 def __init__(self, impl):
1702 self.impl = impl
1703 def __get__(self, obj, owner):
1704 record.append(1)
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001705 return self.impl.__get__(obj, owner)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001706
1707
1708 for name, runner, meth_impl in specials:
1709 class X(Checker):
1710 pass
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001711 setattr(X, name, meth_impl)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001712 runner(X())
1713
1714 record = []
1715 class X(Checker):
1716 pass
1717 setattr(X, name, SpecialDescr(meth_impl))
1718 runner(X())
1719 self.assertEqual(record, [1], name)
1720
Georg Brandl48545522008-02-02 10:12:36 +00001721 def test_specials(self):
1722 # Testing special operators...
1723 # Test operators like __hash__ for which a built-in default exists
1724
1725 # Test the default behavior for static classes
1726 class C(object):
1727 def __getitem__(self, i):
1728 if 0 <= i < 10: return i
1729 raise IndexError
1730 c1 = C()
1731 c2 = C()
1732 self.assert_(not not c1) # What?
1733 self.assertNotEqual(id(c1), id(c2))
1734 hash(c1)
1735 hash(c2)
1736 self.assertEqual(cmp(c1, c2), cmp(id(c1), id(c2)))
1737 self.assertEqual(c1, c1)
1738 self.assert_(c1 != c2)
1739 self.assert_(not c1 != c1)
1740 self.assert_(not c1 == c2)
1741 # Note that the module name appears in str/repr, and that varies
1742 # depending on whether this test is run standalone or from a framework.
1743 self.assert_(str(c1).find('C object at ') >= 0)
1744 self.assertEqual(str(c1), repr(c1))
1745 self.assert_(-1 not in c1)
1746 for i in range(10):
1747 self.assert_(i in c1)
1748 self.assertFalse(10 in c1)
1749 # Test the default behavior for dynamic classes
1750 class D(object):
1751 def __getitem__(self, i):
1752 if 0 <= i < 10: return i
1753 raise IndexError
1754 d1 = D()
1755 d2 = D()
1756 self.assert_(not not d1)
1757 self.assertNotEqual(id(d1), id(d2))
1758 hash(d1)
1759 hash(d2)
1760 self.assertEqual(cmp(d1, d2), cmp(id(d1), id(d2)))
1761 self.assertEqual(d1, d1)
1762 self.assertNotEqual(d1, d2)
1763 self.assert_(not d1 != d1)
1764 self.assert_(not d1 == d2)
1765 # Note that the module name appears in str/repr, and that varies
1766 # depending on whether this test is run standalone or from a framework.
1767 self.assert_(str(d1).find('D object at ') >= 0)
1768 self.assertEqual(str(d1), repr(d1))
1769 self.assert_(-1 not in d1)
1770 for i in range(10):
1771 self.assert_(i in d1)
1772 self.assertFalse(10 in d1)
1773 # Test overridden behavior for static classes
1774 class Proxy(object):
1775 def __init__(self, x):
1776 self.x = x
1777 def __nonzero__(self):
1778 return not not self.x
1779 def __hash__(self):
1780 return hash(self.x)
1781 def __eq__(self, other):
1782 return self.x == other
1783 def __ne__(self, other):
1784 return self.x != other
1785 def __cmp__(self, other):
1786 return cmp(self.x, other.x)
1787 def __str__(self):
1788 return "Proxy:%s" % self.x
1789 def __repr__(self):
1790 return "Proxy(%r)" % self.x
1791 def __contains__(self, value):
1792 return value in self.x
1793 p0 = Proxy(0)
1794 p1 = Proxy(1)
1795 p_1 = Proxy(-1)
1796 self.assertFalse(p0)
1797 self.assert_(not not p1)
1798 self.assertEqual(hash(p0), hash(0))
1799 self.assertEqual(p0, p0)
1800 self.assertNotEqual(p0, p1)
1801 self.assert_(not p0 != p0)
1802 self.assertEqual(not p0, p1)
1803 self.assertEqual(cmp(p0, p1), -1)
1804 self.assertEqual(cmp(p0, p0), 0)
1805 self.assertEqual(cmp(p0, p_1), 1)
1806 self.assertEqual(str(p0), "Proxy:0")
1807 self.assertEqual(repr(p0), "Proxy(0)")
1808 p10 = Proxy(range(10))
1809 self.assertFalse(-1 in p10)
1810 for i in range(10):
1811 self.assert_(i in p10)
1812 self.assertFalse(10 in p10)
1813 # Test overridden behavior for dynamic classes
1814 class DProxy(object):
1815 def __init__(self, x):
1816 self.x = x
1817 def __nonzero__(self):
1818 return not not self.x
1819 def __hash__(self):
1820 return hash(self.x)
1821 def __eq__(self, other):
1822 return self.x == other
1823 def __ne__(self, other):
1824 return self.x != other
1825 def __cmp__(self, other):
1826 return cmp(self.x, other.x)
1827 def __str__(self):
1828 return "DProxy:%s" % self.x
1829 def __repr__(self):
1830 return "DProxy(%r)" % self.x
1831 def __contains__(self, value):
1832 return value in self.x
1833 p0 = DProxy(0)
1834 p1 = DProxy(1)
1835 p_1 = DProxy(-1)
1836 self.assertFalse(p0)
1837 self.assert_(not not p1)
1838 self.assertEqual(hash(p0), hash(0))
1839 self.assertEqual(p0, p0)
1840 self.assertNotEqual(p0, p1)
1841 self.assertNotEqual(not p0, p0)
1842 self.assertEqual(not p0, p1)
1843 self.assertEqual(cmp(p0, p1), -1)
1844 self.assertEqual(cmp(p0, p0), 0)
1845 self.assertEqual(cmp(p0, p_1), 1)
1846 self.assertEqual(str(p0), "DProxy:0")
1847 self.assertEqual(repr(p0), "DProxy(0)")
1848 p10 = DProxy(range(10))
1849 self.assertFalse(-1 in p10)
1850 for i in range(10):
1851 self.assert_(i in p10)
1852 self.assertFalse(10 in p10)
1853
1854 # Safety test for __cmp__
1855 def unsafecmp(a, b):
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001856 if not hasattr(a, '__cmp__'):
1857 return # some types don't have a __cmp__ any more (so the
1858 # test doesn't make sense any more), or maybe they
1859 # never had a __cmp__ at all, e.g. in PyPy
Georg Brandl48545522008-02-02 10:12:36 +00001860 try:
1861 a.__class__.__cmp__(a, b)
1862 except TypeError:
1863 pass
Guido van Rossum4bb1e362001-09-28 23:49:48 +00001864 else:
Georg Brandl48545522008-02-02 10:12:36 +00001865 self.fail("shouldn't allow %s.__cmp__(%r, %r)" % (
1866 a.__class__, a, b))
1867
1868 unsafecmp(u"123", "123")
1869 unsafecmp("123", u"123")
1870 unsafecmp(1, 1.0)
1871 unsafecmp(1.0, 1)
1872 unsafecmp(1, 1L)
1873 unsafecmp(1L, 1)
1874
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001875 @test_support.impl_detail("custom logic for printing to real file objects")
1876 def test_recursions_1(self):
Georg Brandl48545522008-02-02 10:12:36 +00001877 # Testing recursion checks ...
1878 class Letter(str):
1879 def __new__(cls, letter):
1880 if letter == 'EPS':
1881 return str.__new__(cls)
1882 return str.__new__(cls, letter)
1883 def __str__(self):
1884 if not self:
1885 return 'EPS'
1886 return self
1887 # sys.stdout needs to be the original to trigger the recursion bug
1888 import sys
1889 test_stdout = sys.stdout
1890 sys.stdout = test_support.get_original_stdout()
1891 try:
1892 # nothing should actually be printed, this should raise an exception
1893 print Letter('w')
1894 except RuntimeError:
1895 pass
1896 else:
1897 self.fail("expected a RuntimeError for print recursion")
1898 finally:
1899 sys.stdout = test_stdout
1900
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001901 def test_recursions_2(self):
Georg Brandl48545522008-02-02 10:12:36 +00001902 # Bug #1202533.
1903 class A(object):
1904 pass
1905 A.__mul__ = types.MethodType(lambda self, x: self * x, None, A)
1906 try:
1907 A()*2
1908 except RuntimeError:
1909 pass
1910 else:
1911 self.fail("expected a RuntimeError")
1912
1913 def test_weakrefs(self):
1914 # Testing weak references...
1915 import weakref
1916 class C(object):
1917 pass
1918 c = C()
1919 r = weakref.ref(c)
1920 self.assertEqual(r(), c)
1921 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001922 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001923 self.assertEqual(r(), None)
1924 del r
1925 class NoWeak(object):
1926 __slots__ = ['foo']
1927 no = NoWeak()
1928 try:
1929 weakref.ref(no)
1930 except TypeError, msg:
1931 self.assert_(str(msg).find("weak reference") >= 0)
1932 else:
1933 self.fail("weakref.ref(no) should be illegal")
1934 class Weak(object):
1935 __slots__ = ['foo', '__weakref__']
1936 yes = Weak()
1937 r = weakref.ref(yes)
1938 self.assertEqual(r(), yes)
1939 del yes
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001940 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001941 self.assertEqual(r(), None)
1942 del r
1943
1944 def test_properties(self):
1945 # Testing property...
1946 class C(object):
1947 def getx(self):
1948 return self.__x
1949 def setx(self, value):
1950 self.__x = value
1951 def delx(self):
1952 del self.__x
1953 x = property(getx, setx, delx, doc="I'm the x property.")
1954 a = C()
1955 self.assertFalse(hasattr(a, "x"))
1956 a.x = 42
1957 self.assertEqual(a._C__x, 42)
1958 self.assertEqual(a.x, 42)
1959 del a.x
1960 self.assertFalse(hasattr(a, "x"))
1961 self.assertFalse(hasattr(a, "_C__x"))
1962 C.x.__set__(a, 100)
1963 self.assertEqual(C.x.__get__(a), 100)
1964 C.x.__delete__(a)
1965 self.assertFalse(hasattr(a, "x"))
1966
1967 raw = C.__dict__['x']
1968 self.assert_(isinstance(raw, property))
1969
1970 attrs = dir(raw)
1971 self.assert_("__doc__" in attrs)
1972 self.assert_("fget" in attrs)
1973 self.assert_("fset" in attrs)
1974 self.assert_("fdel" in attrs)
1975
1976 self.assertEqual(raw.__doc__, "I'm the x property.")
1977 self.assert_(raw.fget is C.__dict__['getx'])
1978 self.assert_(raw.fset is C.__dict__['setx'])
1979 self.assert_(raw.fdel is C.__dict__['delx'])
1980
1981 for attr in "__doc__", "fget", "fset", "fdel":
1982 try:
1983 setattr(raw, attr, 42)
1984 except TypeError, msg:
1985 if str(msg).find('readonly') < 0:
1986 self.fail("when setting readonly attr %r on a property, "
1987 "got unexpected TypeError msg %r" % (attr, str(msg)))
Guido van Rossum4bb1e362001-09-28 23:49:48 +00001988 else:
Georg Brandl48545522008-02-02 10:12:36 +00001989 self.fail("expected TypeError from trying to set readonly %r "
1990 "attr on a property" % attr)
Tim Peters2f93e282001-10-04 05:27:00 +00001991
Georg Brandl48545522008-02-02 10:12:36 +00001992 class D(object):
1993 __getitem__ = property(lambda s: 1/0)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00001994
Georg Brandl48545522008-02-02 10:12:36 +00001995 d = D()
1996 try:
1997 for i in d:
1998 str(i)
1999 except ZeroDivisionError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002000 pass
Georg Brandl48545522008-02-02 10:12:36 +00002001 else:
2002 self.fail("expected ZeroDivisionError from bad property")
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002003
Georg Brandl48545522008-02-02 10:12:36 +00002004 class E(object):
2005 def getter(self):
2006 "getter method"
2007 return 0
2008 def setter(self_, value):
2009 "setter method"
2010 pass
2011 prop = property(getter)
2012 self.assertEqual(prop.__doc__, "getter method")
2013 prop2 = property(fset=setter)
2014 self.assertEqual(prop2.__doc__, None)
2015
2016 # this segfaulted in 2.5b2
2017 try:
2018 import _testcapi
2019 except ImportError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002020 pass
Georg Brandl48545522008-02-02 10:12:36 +00002021 else:
2022 class X(object):
2023 p = property(_testcapi.test_with_docstring)
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002024
Georg Brandl48545522008-02-02 10:12:36 +00002025 def test_properties_plus(self):
2026 class C(object):
2027 foo = property(doc="hello")
2028 @foo.getter
2029 def foo(self):
2030 return self._foo
2031 @foo.setter
2032 def foo(self, value):
2033 self._foo = abs(value)
2034 @foo.deleter
2035 def foo(self):
2036 del self._foo
2037 c = C()
2038 self.assertEqual(C.foo.__doc__, "hello")
2039 self.assertFalse(hasattr(c, "foo"))
2040 c.foo = -42
2041 self.assert_(hasattr(c, '_foo'))
2042 self.assertEqual(c._foo, 42)
2043 self.assertEqual(c.foo, 42)
2044 del c.foo
2045 self.assertFalse(hasattr(c, '_foo'))
2046 self.assertFalse(hasattr(c, "foo"))
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002047
Georg Brandl48545522008-02-02 10:12:36 +00002048 class D(C):
2049 @C.foo.deleter
2050 def foo(self):
2051 try:
2052 del self._foo
2053 except AttributeError:
2054 pass
2055 d = D()
2056 d.foo = 24
2057 self.assertEqual(d.foo, 24)
2058 del d.foo
2059 del d.foo
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00002060
Georg Brandl48545522008-02-02 10:12:36 +00002061 class E(object):
2062 @property
2063 def foo(self):
2064 return self._foo
2065 @foo.setter
2066 def foo(self, value):
2067 raise RuntimeError
2068 @foo.setter
2069 def foo(self, value):
2070 self._foo = abs(value)
2071 @foo.deleter
2072 def foo(self, value=None):
2073 del self._foo
Guido van Rossume8fc6402002-04-16 16:44:51 +00002074
Georg Brandl48545522008-02-02 10:12:36 +00002075 e = E()
2076 e.foo = -42
2077 self.assertEqual(e.foo, 42)
2078 del e.foo
Guido van Rossumd99b3e72002-04-18 00:27:33 +00002079
Georg Brandl48545522008-02-02 10:12:36 +00002080 class F(E):
2081 @E.foo.deleter
2082 def foo(self):
2083 del self._foo
2084 @foo.setter
2085 def foo(self, value):
2086 self._foo = max(0, value)
2087 f = F()
2088 f.foo = -10
2089 self.assertEqual(f.foo, 0)
2090 del f.foo
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00002091
Georg Brandl48545522008-02-02 10:12:36 +00002092 def test_dict_constructors(self):
2093 # Testing dict constructor ...
2094 d = dict()
2095 self.assertEqual(d, {})
2096 d = dict({})
2097 self.assertEqual(d, {})
2098 d = dict({1: 2, 'a': 'b'})
2099 self.assertEqual(d, {1: 2, 'a': 'b'})
2100 self.assertEqual(d, dict(d.items()))
2101 self.assertEqual(d, dict(d.iteritems()))
2102 d = dict({'one':1, 'two':2})
2103 self.assertEqual(d, dict(one=1, two=2))
2104 self.assertEqual(d, dict(**d))
2105 self.assertEqual(d, dict({"one": 1}, two=2))
2106 self.assertEqual(d, dict([("two", 2)], one=1))
2107 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2108 self.assertEqual(d, dict(**d))
Guido van Rossum09638c12002-06-13 19:17:46 +00002109
Georg Brandl48545522008-02-02 10:12:36 +00002110 for badarg in 0, 0L, 0j, "0", [0], (0,):
2111 try:
2112 dict(badarg)
2113 except TypeError:
2114 pass
2115 except ValueError:
2116 if badarg == "0":
2117 # It's a sequence, and its elements are also sequences (gotta
2118 # love strings <wink>), but they aren't of length 2, so this
2119 # one seemed better as a ValueError than a TypeError.
2120 pass
2121 else:
2122 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002123 else:
Georg Brandl48545522008-02-02 10:12:36 +00002124 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002125
Georg Brandl48545522008-02-02 10:12:36 +00002126 try:
2127 dict({}, {})
2128 except TypeError:
2129 pass
2130 else:
2131 self.fail("no TypeError from dict({}, {})")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002132
Georg Brandl48545522008-02-02 10:12:36 +00002133 class Mapping:
2134 # Lacks a .keys() method; will be added later.
2135 dict = {1:2, 3:4, 'a':1j}
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002136
Georg Brandl48545522008-02-02 10:12:36 +00002137 try:
2138 dict(Mapping())
2139 except TypeError:
2140 pass
2141 else:
2142 self.fail("no TypeError from dict(incomplete mapping)")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002143
Georg Brandl48545522008-02-02 10:12:36 +00002144 Mapping.keys = lambda self: self.dict.keys()
2145 Mapping.__getitem__ = lambda self, i: self.dict[i]
2146 d = dict(Mapping())
2147 self.assertEqual(d, Mapping.dict)
Michael W. Hudsonf3904422006-11-23 13:54:04 +00002148
Georg Brandl48545522008-02-02 10:12:36 +00002149 # Init from sequence of iterable objects, each producing a 2-sequence.
2150 class AddressBookEntry:
2151 def __init__(self, first, last):
2152 self.first = first
2153 self.last = last
2154 def __iter__(self):
2155 return iter([self.first, self.last])
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002156
Georg Brandl48545522008-02-02 10:12:36 +00002157 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2158 AddressBookEntry('Barry', 'Peters'),
2159 AddressBookEntry('Tim', 'Peters'),
2160 AddressBookEntry('Barry', 'Warsaw')])
2161 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00002162
Georg Brandl48545522008-02-02 10:12:36 +00002163 d = dict(zip(range(4), range(1, 5)))
2164 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002165
Georg Brandl48545522008-02-02 10:12:36 +00002166 # Bad sequence lengths.
2167 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2168 try:
2169 dict(bad)
2170 except ValueError:
2171 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00002172 else:
Georg Brandl48545522008-02-02 10:12:36 +00002173 self.fail("no ValueError from dict(%r)" % bad)
2174
2175 def test_dir(self):
2176 # Testing dir() ...
2177 junk = 12
2178 self.assertEqual(dir(), ['junk', 'self'])
2179 del junk
2180
2181 # Just make sure these don't blow up!
2182 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, self.test_dir:
2183 dir(arg)
2184
2185 # Try classic classes.
2186 class C:
2187 Cdata = 1
2188 def Cmethod(self): pass
2189
2190 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
2191 self.assertEqual(dir(C), cstuff)
2192 self.assert_('im_self' in dir(C.Cmethod))
2193
2194 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
2195 self.assertEqual(dir(c), cstuff)
2196
2197 c.cdata = 2
2198 c.cmethod = lambda self: 0
2199 self.assertEqual(dir(c), cstuff + ['cdata', 'cmethod'])
2200 self.assert_('im_self' in dir(c.Cmethod))
2201
2202 class A(C):
2203 Adata = 1
2204 def Amethod(self): pass
2205
2206 astuff = ['Adata', 'Amethod'] + cstuff
2207 self.assertEqual(dir(A), astuff)
2208 self.assert_('im_self' in dir(A.Amethod))
2209 a = A()
2210 self.assertEqual(dir(a), astuff)
2211 self.assert_('im_self' in dir(a.Amethod))
2212 a.adata = 42
2213 a.amethod = lambda self: 3
2214 self.assertEqual(dir(a), astuff + ['adata', 'amethod'])
2215
2216 # The same, but with new-style classes. Since these have object as a
2217 # base class, a lot more gets sucked in.
2218 def interesting(strings):
2219 return [s for s in strings if not s.startswith('_')]
2220
2221 class C(object):
2222 Cdata = 1
2223 def Cmethod(self): pass
2224
2225 cstuff = ['Cdata', 'Cmethod']
2226 self.assertEqual(interesting(dir(C)), cstuff)
2227
2228 c = C()
2229 self.assertEqual(interesting(dir(c)), cstuff)
2230 self.assert_('im_self' in dir(C.Cmethod))
2231
2232 c.cdata = 2
2233 c.cmethod = lambda self: 0
2234 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
2235 self.assert_('im_self' in dir(c.Cmethod))
2236
2237 class A(C):
2238 Adata = 1
2239 def Amethod(self): pass
2240
2241 astuff = ['Adata', 'Amethod'] + cstuff
2242 self.assertEqual(interesting(dir(A)), astuff)
2243 self.assert_('im_self' in dir(A.Amethod))
2244 a = A()
2245 self.assertEqual(interesting(dir(a)), astuff)
2246 a.adata = 42
2247 a.amethod = lambda self: 3
2248 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
2249 self.assert_('im_self' in dir(a.Amethod))
2250
2251 # Try a module subclass.
2252 import sys
2253 class M(type(sys)):
2254 pass
2255 minstance = M("m")
2256 minstance.b = 2
2257 minstance.a = 1
2258 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2259 self.assertEqual(names, ['a', 'b'])
2260
2261 class M2(M):
2262 def getdict(self):
2263 return "Not a dict!"
2264 __dict__ = property(getdict)
2265
2266 m2instance = M2("m2")
2267 m2instance.b = 2
2268 m2instance.a = 1
2269 self.assertEqual(m2instance.__dict__, "Not a dict!")
2270 try:
2271 dir(m2instance)
2272 except TypeError:
2273 pass
2274
2275 # Two essentially featureless objects, just inheriting stuff from
2276 # object.
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002277 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
2278 if test_support.check_impl_detail():
2279 # None differs in PyPy: it has a __nonzero__
2280 self.assertEqual(dir(None), dir(Ellipsis))
Georg Brandl48545522008-02-02 10:12:36 +00002281
2282 # Nasty test case for proxied objects
2283 class Wrapper(object):
2284 def __init__(self, obj):
2285 self.__obj = obj
2286 def __repr__(self):
2287 return "Wrapper(%s)" % repr(self.__obj)
2288 def __getitem__(self, key):
2289 return Wrapper(self.__obj[key])
2290 def __len__(self):
2291 return len(self.__obj)
2292 def __getattr__(self, name):
2293 return Wrapper(getattr(self.__obj, name))
2294
2295 class C(object):
2296 def __getclass(self):
2297 return Wrapper(type(self))
2298 __class__ = property(__getclass)
2299
2300 dir(C()) # This used to segfault
2301
2302 def test_supers(self):
2303 # Testing super...
2304
2305 class A(object):
2306 def meth(self, a):
2307 return "A(%r)" % a
2308
2309 self.assertEqual(A().meth(1), "A(1)")
2310
2311 class B(A):
2312 def __init__(self):
2313 self.__super = super(B, self)
2314 def meth(self, a):
2315 return "B(%r)" % a + self.__super.meth(a)
2316
2317 self.assertEqual(B().meth(2), "B(2)A(2)")
2318
2319 class C(A):
2320 def meth(self, a):
2321 return "C(%r)" % a + self.__super.meth(a)
2322 C._C__super = super(C)
2323
2324 self.assertEqual(C().meth(3), "C(3)A(3)")
2325
2326 class D(C, B):
2327 def meth(self, a):
2328 return "D(%r)" % a + super(D, self).meth(a)
2329
2330 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2331
2332 # Test for subclassing super
2333
2334 class mysuper(super):
2335 def __init__(self, *args):
2336 return super(mysuper, self).__init__(*args)
2337
2338 class E(D):
2339 def meth(self, a):
2340 return "E(%r)" % a + mysuper(E, self).meth(a)
2341
2342 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2343
2344 class F(E):
2345 def meth(self, a):
2346 s = self.__super # == mysuper(F, self)
2347 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2348 F._F__super = mysuper(F)
2349
2350 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2351
2352 # Make sure certain errors are raised
2353
2354 try:
2355 super(D, 42)
2356 except TypeError:
2357 pass
2358 else:
2359 self.fail("shouldn't allow super(D, 42)")
2360
2361 try:
2362 super(D, C())
2363 except TypeError:
2364 pass
2365 else:
2366 self.fail("shouldn't allow super(D, C())")
2367
2368 try:
2369 super(D).__get__(12)
2370 except TypeError:
2371 pass
2372 else:
2373 self.fail("shouldn't allow super(D).__get__(12)")
2374
2375 try:
2376 super(D).__get__(C())
2377 except TypeError:
2378 pass
2379 else:
2380 self.fail("shouldn't allow super(D).__get__(C())")
2381
2382 # Make sure data descriptors can be overridden and accessed via super
2383 # (new feature in Python 2.3)
2384
2385 class DDbase(object):
2386 def getx(self): return 42
2387 x = property(getx)
2388
2389 class DDsub(DDbase):
2390 def getx(self): return "hello"
2391 x = property(getx)
2392
2393 dd = DDsub()
2394 self.assertEqual(dd.x, "hello")
2395 self.assertEqual(super(DDsub, dd).x, 42)
2396
2397 # Ensure that super() lookup of descriptor from classmethod
2398 # works (SF ID# 743627)
2399
2400 class Base(object):
2401 aProp = property(lambda self: "foo")
2402
2403 class Sub(Base):
2404 @classmethod
2405 def test(klass):
2406 return super(Sub,klass).aProp
2407
2408 self.assertEqual(Sub.test(), Base.aProp)
2409
2410 # Verify that super() doesn't allow keyword args
2411 try:
2412 super(Base, kw=1)
2413 except TypeError:
2414 pass
2415 else:
2416 self.assertEqual("super shouldn't accept keyword args")
2417
2418 def test_basic_inheritance(self):
2419 # Testing inheritance from basic types...
2420
2421 class hexint(int):
2422 def __repr__(self):
2423 return hex(self)
2424 def __add__(self, other):
2425 return hexint(int.__add__(self, other))
2426 # (Note that overriding __radd__ doesn't work,
2427 # because the int type gets first dibs.)
2428 self.assertEqual(repr(hexint(7) + 9), "0x10")
2429 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2430 a = hexint(12345)
2431 self.assertEqual(a, 12345)
2432 self.assertEqual(int(a), 12345)
2433 self.assert_(int(a).__class__ is int)
2434 self.assertEqual(hash(a), hash(12345))
2435 self.assert_((+a).__class__ is int)
2436 self.assert_((a >> 0).__class__ is int)
2437 self.assert_((a << 0).__class__ is int)
2438 self.assert_((hexint(0) << 12).__class__ is int)
2439 self.assert_((hexint(0) >> 12).__class__ is int)
2440
2441 class octlong(long):
2442 __slots__ = []
2443 def __str__(self):
2444 s = oct(self)
2445 if s[-1] == 'L':
2446 s = s[:-1]
2447 return s
2448 def __add__(self, other):
2449 return self.__class__(super(octlong, self).__add__(other))
2450 __radd__ = __add__
2451 self.assertEqual(str(octlong(3) + 5), "010")
2452 # (Note that overriding __radd__ here only seems to work
2453 # because the example uses a short int left argument.)
2454 self.assertEqual(str(5 + octlong(3000)), "05675")
2455 a = octlong(12345)
2456 self.assertEqual(a, 12345L)
2457 self.assertEqual(long(a), 12345L)
2458 self.assertEqual(hash(a), hash(12345L))
2459 self.assert_(long(a).__class__ is long)
2460 self.assert_((+a).__class__ is long)
2461 self.assert_((-a).__class__ is long)
2462 self.assert_((-octlong(0)).__class__ is long)
2463 self.assert_((a >> 0).__class__ is long)
2464 self.assert_((a << 0).__class__ is long)
2465 self.assert_((a - 0).__class__ is long)
2466 self.assert_((a * 1).__class__ is long)
2467 self.assert_((a ** 1).__class__ is long)
2468 self.assert_((a // 1).__class__ is long)
2469 self.assert_((1 * a).__class__ is long)
2470 self.assert_((a | 0).__class__ is long)
2471 self.assert_((a ^ 0).__class__ is long)
2472 self.assert_((a & -1L).__class__ is long)
2473 self.assert_((octlong(0) << 12).__class__ is long)
2474 self.assert_((octlong(0) >> 12).__class__ is long)
2475 self.assert_(abs(octlong(0)).__class__ is long)
2476
2477 # Because octlong overrides __add__, we can't check the absence of +0
2478 # optimizations using octlong.
2479 class longclone(long):
2480 pass
2481 a = longclone(1)
2482 self.assert_((a + 0).__class__ is long)
2483 self.assert_((0 + a).__class__ is long)
2484
2485 # Check that negative clones don't segfault
2486 a = longclone(-1)
2487 self.assertEqual(a.__dict__, {})
2488 self.assertEqual(long(a), -1) # self.assert_ PyNumber_Long() copies the sign bit
2489
2490 class precfloat(float):
2491 __slots__ = ['prec']
2492 def __init__(self, value=0.0, prec=12):
2493 self.prec = int(prec)
2494 def __repr__(self):
2495 return "%.*g" % (self.prec, self)
2496 self.assertEqual(repr(precfloat(1.1)), "1.1")
2497 a = precfloat(12345)
2498 self.assertEqual(a, 12345.0)
2499 self.assertEqual(float(a), 12345.0)
2500 self.assert_(float(a).__class__ is float)
2501 self.assertEqual(hash(a), hash(12345.0))
2502 self.assert_((+a).__class__ is float)
2503
2504 class madcomplex(complex):
2505 def __repr__(self):
2506 return "%.17gj%+.17g" % (self.imag, self.real)
2507 a = madcomplex(-3, 4)
2508 self.assertEqual(repr(a), "4j-3")
2509 base = complex(-3, 4)
2510 self.assertEqual(base.__class__, complex)
2511 self.assertEqual(a, base)
2512 self.assertEqual(complex(a), base)
2513 self.assertEqual(complex(a).__class__, complex)
2514 a = madcomplex(a) # just trying another form of the constructor
2515 self.assertEqual(repr(a), "4j-3")
2516 self.assertEqual(a, base)
2517 self.assertEqual(complex(a), base)
2518 self.assertEqual(complex(a).__class__, complex)
2519 self.assertEqual(hash(a), hash(base))
2520 self.assertEqual((+a).__class__, complex)
2521 self.assertEqual((a + 0).__class__, complex)
2522 self.assertEqual(a + 0, base)
2523 self.assertEqual((a - 0).__class__, complex)
2524 self.assertEqual(a - 0, base)
2525 self.assertEqual((a * 1).__class__, complex)
2526 self.assertEqual(a * 1, base)
2527 self.assertEqual((a / 1).__class__, complex)
2528 self.assertEqual(a / 1, base)
2529
2530 class madtuple(tuple):
2531 _rev = None
2532 def rev(self):
2533 if self._rev is not None:
2534 return self._rev
2535 L = list(self)
2536 L.reverse()
2537 self._rev = self.__class__(L)
2538 return self._rev
2539 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2540 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2541 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2542 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2543 for i in range(512):
2544 t = madtuple(range(i))
2545 u = t.rev()
2546 v = u.rev()
2547 self.assertEqual(v, t)
2548 a = madtuple((1,2,3,4,5))
2549 self.assertEqual(tuple(a), (1,2,3,4,5))
2550 self.assert_(tuple(a).__class__ is tuple)
2551 self.assertEqual(hash(a), hash((1,2,3,4,5)))
2552 self.assert_(a[:].__class__ is tuple)
2553 self.assert_((a * 1).__class__ is tuple)
2554 self.assert_((a * 0).__class__ is tuple)
2555 self.assert_((a + ()).__class__ is tuple)
2556 a = madtuple(())
2557 self.assertEqual(tuple(a), ())
2558 self.assert_(tuple(a).__class__ is tuple)
2559 self.assert_((a + a).__class__ is tuple)
2560 self.assert_((a * 0).__class__ is tuple)
2561 self.assert_((a * 1).__class__ is tuple)
2562 self.assert_((a * 2).__class__ is tuple)
2563 self.assert_(a[:].__class__ is tuple)
2564
2565 class madstring(str):
2566 _rev = None
2567 def rev(self):
2568 if self._rev is not None:
2569 return self._rev
2570 L = list(self)
2571 L.reverse()
2572 self._rev = self.__class__("".join(L))
2573 return self._rev
2574 s = madstring("abcdefghijklmnopqrstuvwxyz")
2575 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2576 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2577 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2578 for i in range(256):
2579 s = madstring("".join(map(chr, range(i))))
2580 t = s.rev()
2581 u = t.rev()
2582 self.assertEqual(u, s)
2583 s = madstring("12345")
2584 self.assertEqual(str(s), "12345")
2585 self.assert_(str(s).__class__ is str)
2586
2587 base = "\x00" * 5
2588 s = madstring(base)
2589 self.assertEqual(s, base)
2590 self.assertEqual(str(s), base)
2591 self.assert_(str(s).__class__ is str)
2592 self.assertEqual(hash(s), hash(base))
2593 self.assertEqual({s: 1}[base], 1)
2594 self.assertEqual({base: 1}[s], 1)
2595 self.assert_((s + "").__class__ is str)
2596 self.assertEqual(s + "", base)
2597 self.assert_(("" + s).__class__ is str)
2598 self.assertEqual("" + s, base)
2599 self.assert_((s * 0).__class__ is str)
2600 self.assertEqual(s * 0, "")
2601 self.assert_((s * 1).__class__ is str)
2602 self.assertEqual(s * 1, base)
2603 self.assert_((s * 2).__class__ is str)
2604 self.assertEqual(s * 2, base + base)
2605 self.assert_(s[:].__class__ is str)
2606 self.assertEqual(s[:], base)
2607 self.assert_(s[0:0].__class__ is str)
2608 self.assertEqual(s[0:0], "")
2609 self.assert_(s.strip().__class__ is str)
2610 self.assertEqual(s.strip(), base)
2611 self.assert_(s.lstrip().__class__ is str)
2612 self.assertEqual(s.lstrip(), base)
2613 self.assert_(s.rstrip().__class__ is str)
2614 self.assertEqual(s.rstrip(), base)
2615 identitytab = ''.join([chr(i) for i in range(256)])
2616 self.assert_(s.translate(identitytab).__class__ is str)
2617 self.assertEqual(s.translate(identitytab), base)
2618 self.assert_(s.translate(identitytab, "x").__class__ is str)
2619 self.assertEqual(s.translate(identitytab, "x"), base)
2620 self.assertEqual(s.translate(identitytab, "\x00"), "")
2621 self.assert_(s.replace("x", "x").__class__ is str)
2622 self.assertEqual(s.replace("x", "x"), base)
2623 self.assert_(s.ljust(len(s)).__class__ is str)
2624 self.assertEqual(s.ljust(len(s)), base)
2625 self.assert_(s.rjust(len(s)).__class__ is str)
2626 self.assertEqual(s.rjust(len(s)), base)
2627 self.assert_(s.center(len(s)).__class__ is str)
2628 self.assertEqual(s.center(len(s)), base)
2629 self.assert_(s.lower().__class__ is str)
2630 self.assertEqual(s.lower(), base)
2631
2632 class madunicode(unicode):
2633 _rev = None
2634 def rev(self):
2635 if self._rev is not None:
2636 return self._rev
2637 L = list(self)
2638 L.reverse()
2639 self._rev = self.__class__(u"".join(L))
2640 return self._rev
2641 u = madunicode("ABCDEF")
2642 self.assertEqual(u, u"ABCDEF")
2643 self.assertEqual(u.rev(), madunicode(u"FEDCBA"))
2644 self.assertEqual(u.rev().rev(), madunicode(u"ABCDEF"))
2645 base = u"12345"
2646 u = madunicode(base)
2647 self.assertEqual(unicode(u), base)
2648 self.assert_(unicode(u).__class__ is unicode)
2649 self.assertEqual(hash(u), hash(base))
2650 self.assertEqual({u: 1}[base], 1)
2651 self.assertEqual({base: 1}[u], 1)
2652 self.assert_(u.strip().__class__ is unicode)
2653 self.assertEqual(u.strip(), base)
2654 self.assert_(u.lstrip().__class__ is unicode)
2655 self.assertEqual(u.lstrip(), base)
2656 self.assert_(u.rstrip().__class__ is unicode)
2657 self.assertEqual(u.rstrip(), base)
2658 self.assert_(u.replace(u"x", u"x").__class__ is unicode)
2659 self.assertEqual(u.replace(u"x", u"x"), base)
2660 self.assert_(u.replace(u"xy", u"xy").__class__ is unicode)
2661 self.assertEqual(u.replace(u"xy", u"xy"), base)
2662 self.assert_(u.center(len(u)).__class__ is unicode)
2663 self.assertEqual(u.center(len(u)), base)
2664 self.assert_(u.ljust(len(u)).__class__ is unicode)
2665 self.assertEqual(u.ljust(len(u)), base)
2666 self.assert_(u.rjust(len(u)).__class__ is unicode)
2667 self.assertEqual(u.rjust(len(u)), base)
2668 self.assert_(u.lower().__class__ is unicode)
2669 self.assertEqual(u.lower(), base)
2670 self.assert_(u.upper().__class__ is unicode)
2671 self.assertEqual(u.upper(), base)
2672 self.assert_(u.capitalize().__class__ is unicode)
2673 self.assertEqual(u.capitalize(), base)
2674 self.assert_(u.title().__class__ is unicode)
2675 self.assertEqual(u.title(), base)
2676 self.assert_((u + u"").__class__ is unicode)
2677 self.assertEqual(u + u"", base)
2678 self.assert_((u"" + u).__class__ is unicode)
2679 self.assertEqual(u"" + u, base)
2680 self.assert_((u * 0).__class__ is unicode)
2681 self.assertEqual(u * 0, u"")
2682 self.assert_((u * 1).__class__ is unicode)
2683 self.assertEqual(u * 1, base)
2684 self.assert_((u * 2).__class__ is unicode)
2685 self.assertEqual(u * 2, base + base)
2686 self.assert_(u[:].__class__ is unicode)
2687 self.assertEqual(u[:], base)
2688 self.assert_(u[0:0].__class__ is unicode)
2689 self.assertEqual(u[0:0], u"")
2690
2691 class sublist(list):
2692 pass
2693 a = sublist(range(5))
2694 self.assertEqual(a, range(5))
2695 a.append("hello")
2696 self.assertEqual(a, range(5) + ["hello"])
2697 a[5] = 5
2698 self.assertEqual(a, range(6))
2699 a.extend(range(6, 20))
2700 self.assertEqual(a, range(20))
2701 a[-5:] = []
2702 self.assertEqual(a, range(15))
2703 del a[10:15]
2704 self.assertEqual(len(a), 10)
2705 self.assertEqual(a, range(10))
2706 self.assertEqual(list(a), range(10))
2707 self.assertEqual(a[0], 0)
2708 self.assertEqual(a[9], 9)
2709 self.assertEqual(a[-10], 0)
2710 self.assertEqual(a[-1], 9)
2711 self.assertEqual(a[:5], range(5))
2712
2713 class CountedInput(file):
2714 """Counts lines read by self.readline().
2715
2716 self.lineno is the 0-based ordinal of the last line read, up to
2717 a maximum of one greater than the number of lines in the file.
2718
2719 self.ateof is true if and only if the final "" line has been read,
2720 at which point self.lineno stops incrementing, and further calls
2721 to readline() continue to return "".
2722 """
2723
2724 lineno = 0
2725 ateof = 0
2726 def readline(self):
2727 if self.ateof:
2728 return ""
2729 s = file.readline(self)
2730 # Next line works too.
2731 # s = super(CountedInput, self).readline()
2732 self.lineno += 1
2733 if s == "":
2734 self.ateof = 1
2735 return s
2736
2737 f = file(name=test_support.TESTFN, mode='w')
2738 lines = ['a\n', 'b\n', 'c\n']
2739 try:
2740 f.writelines(lines)
2741 f.close()
2742 f = CountedInput(test_support.TESTFN)
2743 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2744 got = f.readline()
2745 self.assertEqual(expected, got)
2746 self.assertEqual(f.lineno, i)
2747 self.assertEqual(f.ateof, (i > len(lines)))
2748 f.close()
2749 finally:
2750 try:
2751 f.close()
2752 except:
2753 pass
2754 test_support.unlink(test_support.TESTFN)
2755
2756 def test_keywords(self):
2757 # Testing keyword args to basic type constructors ...
2758 self.assertEqual(int(x=1), 1)
2759 self.assertEqual(float(x=2), 2.0)
2760 self.assertEqual(long(x=3), 3L)
2761 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2762 self.assertEqual(str(object=500), '500')
2763 self.assertEqual(unicode(string='abc', errors='strict'), u'abc')
2764 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2765 self.assertEqual(list(sequence=(0, 1, 2)), range(3))
2766 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2767
2768 for constructor in (int, float, long, complex, str, unicode,
2769 tuple, list, file):
2770 try:
2771 constructor(bogus_keyword_arg=1)
2772 except TypeError:
2773 pass
2774 else:
2775 self.fail("expected TypeError from bogus keyword argument to %r"
2776 % constructor)
2777
2778 def test_str_subclass_as_dict_key(self):
2779 # Testing a str subclass used as dict key ..
2780
2781 class cistr(str):
2782 """Sublcass of str that computes __eq__ case-insensitively.
2783
2784 Also computes a hash code of the string in canonical form.
2785 """
2786
2787 def __init__(self, value):
2788 self.canonical = value.lower()
2789 self.hashcode = hash(self.canonical)
2790
2791 def __eq__(self, other):
2792 if not isinstance(other, cistr):
2793 other = cistr(other)
2794 return self.canonical == other.canonical
2795
2796 def __hash__(self):
2797 return self.hashcode
2798
2799 self.assertEqual(cistr('ABC'), 'abc')
2800 self.assertEqual('aBc', cistr('ABC'))
2801 self.assertEqual(str(cistr('ABC')), 'ABC')
2802
2803 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2804 self.assertEqual(d[cistr('one')], 1)
2805 self.assertEqual(d[cistr('tWo')], 2)
2806 self.assertEqual(d[cistr('THrEE')], 3)
2807 self.assert_(cistr('ONe') in d)
2808 self.assertEqual(d.get(cistr('thrEE')), 3)
2809
2810 def test_classic_comparisons(self):
2811 # Testing classic comparisons...
2812 class classic:
2813 pass
2814
2815 for base in (classic, int, object):
2816 class C(base):
2817 def __init__(self, value):
2818 self.value = int(value)
2819 def __cmp__(self, other):
2820 if isinstance(other, C):
2821 return cmp(self.value, other.value)
2822 if isinstance(other, int) or isinstance(other, long):
2823 return cmp(self.value, other)
2824 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00002825 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002826
2827 c1 = C(1)
2828 c2 = C(2)
2829 c3 = C(3)
2830 self.assertEqual(c1, 1)
2831 c = {1: c1, 2: c2, 3: c3}
2832 for x in 1, 2, 3:
2833 for y in 1, 2, 3:
2834 self.assert_(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2835 for op in "<", "<=", "==", "!=", ">", ">=":
2836 self.assert_(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2837 "x=%d, y=%d" % (x, y))
2838 self.assert_(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2839 self.assert_(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2840
2841 def test_rich_comparisons(self):
2842 # Testing rich comparisons...
2843 class Z(complex):
2844 pass
2845 z = Z(1)
2846 self.assertEqual(z, 1+0j)
2847 self.assertEqual(1+0j, z)
2848 class ZZ(complex):
2849 def __eq__(self, other):
2850 try:
2851 return abs(self - other) <= 1e-6
2852 except:
2853 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00002854 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002855 zz = ZZ(1.0000003)
2856 self.assertEqual(zz, 1+0j)
2857 self.assertEqual(1+0j, zz)
2858
2859 class classic:
2860 pass
2861 for base in (classic, int, object, list):
2862 class C(base):
2863 def __init__(self, value):
2864 self.value = int(value)
2865 def __cmp__(self_, other):
2866 self.fail("shouldn't call __cmp__")
Nick Coghlan48361f52008-08-11 15:45:58 +00002867 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002868 def __eq__(self, other):
2869 if isinstance(other, C):
2870 return self.value == other.value
2871 if isinstance(other, int) or isinstance(other, long):
2872 return self.value == other
2873 return NotImplemented
2874 def __ne__(self, other):
2875 if isinstance(other, C):
2876 return self.value != other.value
2877 if isinstance(other, int) or isinstance(other, long):
2878 return self.value != other
2879 return NotImplemented
2880 def __lt__(self, other):
2881 if isinstance(other, C):
2882 return self.value < other.value
2883 if isinstance(other, int) or isinstance(other, long):
2884 return self.value < other
2885 return NotImplemented
2886 def __le__(self, other):
2887 if isinstance(other, C):
2888 return self.value <= other.value
2889 if isinstance(other, int) or isinstance(other, long):
2890 return self.value <= other
2891 return NotImplemented
2892 def __gt__(self, other):
2893 if isinstance(other, C):
2894 return self.value > other.value
2895 if isinstance(other, int) or isinstance(other, long):
2896 return self.value > other
2897 return NotImplemented
2898 def __ge__(self, other):
2899 if isinstance(other, C):
2900 return self.value >= other.value
2901 if isinstance(other, int) or isinstance(other, long):
2902 return self.value >= other
2903 return NotImplemented
2904 c1 = C(1)
2905 c2 = C(2)
2906 c3 = C(3)
2907 self.assertEqual(c1, 1)
2908 c = {1: c1, 2: c2, 3: c3}
2909 for x in 1, 2, 3:
2910 for y in 1, 2, 3:
2911 for op in "<", "<=", "==", "!=", ">", ">=":
2912 self.assert_(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2913 "x=%d, y=%d" % (x, y))
2914 self.assert_(eval("c[x] %s y" % op) == eval("x %s y" % op),
2915 "x=%d, y=%d" % (x, y))
2916 self.assert_(eval("x %s c[y]" % op) == eval("x %s y" % op),
2917 "x=%d, y=%d" % (x, y))
2918
2919 def test_coercions(self):
2920 # Testing coercions...
2921 class I(int): pass
2922 coerce(I(0), 0)
2923 coerce(0, I(0))
2924 class L(long): pass
2925 coerce(L(0), 0)
2926 coerce(L(0), 0L)
2927 coerce(0, L(0))
2928 coerce(0L, L(0))
2929 class F(float): pass
2930 coerce(F(0), 0)
2931 coerce(F(0), 0L)
2932 coerce(F(0), 0.)
2933 coerce(0, F(0))
2934 coerce(0L, F(0))
2935 coerce(0., F(0))
2936 class C(complex): pass
2937 coerce(C(0), 0)
2938 coerce(C(0), 0L)
2939 coerce(C(0), 0.)
2940 coerce(C(0), 0j)
2941 coerce(0, C(0))
2942 coerce(0L, C(0))
2943 coerce(0., C(0))
2944 coerce(0j, C(0))
2945
2946 def test_descrdoc(self):
2947 # Testing descriptor doc strings...
2948 def check(descr, what):
2949 self.assertEqual(descr.__doc__, what)
2950 check(file.closed, "True if the file is closed") # getset descriptor
2951 check(file.name, "file name") # member descriptor
2952
2953 def test_doc_descriptor(self):
2954 # Testing __doc__ descriptor...
2955 # SF bug 542984
2956 class DocDescr(object):
2957 def __get__(self, object, otype):
2958 if object:
2959 object = object.__class__.__name__ + ' instance'
2960 if otype:
2961 otype = otype.__name__
2962 return 'object=%s; type=%s' % (object, otype)
2963 class OldClass:
2964 __doc__ = DocDescr()
2965 class NewClass(object):
2966 __doc__ = DocDescr()
2967 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
2968 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
2969 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
2970 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
2971
2972 def test_set_class(self):
2973 # Testing __class__ assignment...
2974 class C(object): pass
2975 class D(object): pass
2976 class E(object): pass
2977 class F(D, E): pass
2978 for cls in C, D, E, F:
2979 for cls2 in C, D, E, F:
2980 x = cls()
2981 x.__class__ = cls2
2982 self.assert_(x.__class__ is cls2)
2983 x.__class__ = cls
2984 self.assert_(x.__class__ is cls)
2985 def cant(x, C):
2986 try:
2987 x.__class__ = C
2988 except TypeError:
2989 pass
2990 else:
2991 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
2992 try:
2993 delattr(x, "__class__")
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002994 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00002995 pass
2996 else:
2997 self.fail("shouldn't allow del %r.__class__" % x)
2998 cant(C(), list)
2999 cant(list(), C)
3000 cant(C(), 1)
3001 cant(C(), object)
3002 cant(object(), list)
3003 cant(list(), object)
3004 class Int(int): __slots__ = []
3005 cant(2, Int)
3006 cant(Int(), int)
3007 cant(True, int)
3008 cant(2, bool)
3009 o = object()
3010 cant(o, type(1))
3011 cant(o, type(None))
3012 del o
3013 class G(object):
3014 __slots__ = ["a", "b"]
3015 class H(object):
3016 __slots__ = ["b", "a"]
3017 try:
3018 unicode
3019 except NameError:
3020 class I(object):
3021 __slots__ = ["a", "b"]
3022 else:
3023 class I(object):
3024 __slots__ = [unicode("a"), unicode("b")]
3025 class J(object):
3026 __slots__ = ["c", "b"]
3027 class K(object):
3028 __slots__ = ["a", "b", "d"]
3029 class L(H):
3030 __slots__ = ["e"]
3031 class M(I):
3032 __slots__ = ["e"]
3033 class N(J):
3034 __slots__ = ["__weakref__"]
3035 class P(J):
3036 __slots__ = ["__dict__"]
3037 class Q(J):
3038 pass
3039 class R(J):
3040 __slots__ = ["__dict__", "__weakref__"]
3041
3042 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3043 x = cls()
3044 x.a = 1
3045 x.__class__ = cls2
3046 self.assert_(x.__class__ is cls2,
3047 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3048 self.assertEqual(x.a, 1)
3049 x.__class__ = cls
3050 self.assert_(x.__class__ is cls,
3051 "assigning %r as __class__ for %r silently failed" % (cls, x))
3052 self.assertEqual(x.a, 1)
3053 for cls in G, J, K, L, M, N, P, R, list, Int:
3054 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3055 if cls is cls2:
3056 continue
3057 cant(cls(), cls2)
3058
Benjamin Peterson5083dc52009-04-25 00:41:22 +00003059 # Issue5283: when __class__ changes in __del__, the wrong
3060 # type gets DECREF'd.
3061 class O(object):
3062 pass
3063 class A(object):
3064 def __del__(self):
3065 self.__class__ = O
3066 l = [A() for x in range(100)]
3067 del l
3068
Georg Brandl48545522008-02-02 10:12:36 +00003069 def test_set_dict(self):
3070 # Testing __dict__ assignment...
3071 class C(object): pass
3072 a = C()
3073 a.__dict__ = {'b': 1}
3074 self.assertEqual(a.b, 1)
3075 def cant(x, dict):
3076 try:
3077 x.__dict__ = dict
3078 except (AttributeError, TypeError):
3079 pass
3080 else:
3081 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3082 cant(a, None)
3083 cant(a, [])
3084 cant(a, 1)
3085 del a.__dict__ # Deleting __dict__ is allowed
3086
3087 class Base(object):
3088 pass
3089 def verify_dict_readonly(x):
3090 """
3091 x has to be an instance of a class inheriting from Base.
3092 """
3093 cant(x, {})
3094 try:
3095 del x.__dict__
3096 except (AttributeError, TypeError):
3097 pass
3098 else:
3099 self.fail("shouldn't allow del %r.__dict__" % x)
3100 dict_descr = Base.__dict__["__dict__"]
3101 try:
3102 dict_descr.__set__(x, {})
3103 except (AttributeError, TypeError):
3104 pass
3105 else:
3106 self.fail("dict_descr allowed access to %r's dict" % x)
3107
3108 # Classes don't allow __dict__ assignment and have readonly dicts
3109 class Meta1(type, Base):
3110 pass
3111 class Meta2(Base, type):
3112 pass
3113 class D(object):
3114 __metaclass__ = Meta1
3115 class E(object):
3116 __metaclass__ = Meta2
3117 for cls in C, D, E:
3118 verify_dict_readonly(cls)
3119 class_dict = cls.__dict__
3120 try:
3121 class_dict["spam"] = "eggs"
3122 except TypeError:
3123 pass
3124 else:
3125 self.fail("%r's __dict__ can be modified" % cls)
3126
3127 # Modules also disallow __dict__ assignment
3128 class Module1(types.ModuleType, Base):
3129 pass
3130 class Module2(Base, types.ModuleType):
3131 pass
3132 for ModuleType in Module1, Module2:
3133 mod = ModuleType("spam")
3134 verify_dict_readonly(mod)
3135 mod.__dict__["spam"] = "eggs"
3136
3137 # Exception's __dict__ can be replaced, but not deleted
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003138 # (at least not any more than regular exception's __dict__ can
3139 # be deleted; on CPython it is not the case, whereas on PyPy they
3140 # can, just like any other new-style instance's __dict__.)
3141 def can_delete_dict(e):
3142 try:
3143 del e.__dict__
3144 except (TypeError, AttributeError):
3145 return False
3146 else:
3147 return True
Georg Brandl48545522008-02-02 10:12:36 +00003148 class Exception1(Exception, Base):
3149 pass
3150 class Exception2(Base, Exception):
3151 pass
3152 for ExceptionType in Exception, Exception1, Exception2:
3153 e = ExceptionType()
3154 e.__dict__ = {"a": 1}
3155 self.assertEqual(e.a, 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003156 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl48545522008-02-02 10:12:36 +00003157
3158 def test_pickles(self):
3159 # Testing pickling and copying new-style classes and objects...
3160 import pickle, cPickle
3161
3162 def sorteditems(d):
3163 L = d.items()
3164 L.sort()
3165 return L
3166
3167 global C
3168 class C(object):
3169 def __init__(self, a, b):
3170 super(C, self).__init__()
3171 self.a = a
3172 self.b = b
3173 def __repr__(self):
3174 return "C(%r, %r)" % (self.a, self.b)
3175
3176 global C1
3177 class C1(list):
3178 def __new__(cls, a, b):
3179 return super(C1, cls).__new__(cls)
3180 def __getnewargs__(self):
3181 return (self.a, self.b)
3182 def __init__(self, a, b):
3183 self.a = a
3184 self.b = b
3185 def __repr__(self):
3186 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
3187
3188 global C2
3189 class C2(int):
3190 def __new__(cls, a, b, val=0):
3191 return super(C2, cls).__new__(cls, val)
3192 def __getnewargs__(self):
3193 return (self.a, self.b, int(self))
3194 def __init__(self, a, b, val=0):
3195 self.a = a
3196 self.b = b
3197 def __repr__(self):
3198 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
3199
3200 global C3
3201 class C3(object):
3202 def __init__(self, foo):
3203 self.foo = foo
3204 def __getstate__(self):
3205 return self.foo
3206 def __setstate__(self, foo):
3207 self.foo = foo
3208
3209 global C4classic, C4
3210 class C4classic: # classic
3211 pass
3212 class C4(C4classic, object): # mixed inheritance
3213 pass
3214
3215 for p in pickle, cPickle:
3216 for bin in 0, 1:
3217 for cls in C, C1, C2:
3218 s = p.dumps(cls, bin)
3219 cls2 = p.loads(s)
3220 self.assert_(cls2 is cls)
3221
3222 a = C1(1, 2); a.append(42); a.append(24)
3223 b = C2("hello", "world", 42)
3224 s = p.dumps((a, b), bin)
3225 x, y = p.loads(s)
3226 self.assertEqual(x.__class__, a.__class__)
3227 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3228 self.assertEqual(y.__class__, b.__class__)
3229 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3230 self.assertEqual(repr(x), repr(a))
3231 self.assertEqual(repr(y), repr(b))
3232 # Test for __getstate__ and __setstate__ on new style class
3233 u = C3(42)
3234 s = p.dumps(u, bin)
3235 v = p.loads(s)
3236 self.assertEqual(u.__class__, v.__class__)
3237 self.assertEqual(u.foo, v.foo)
3238 # Test for picklability of hybrid class
3239 u = C4()
3240 u.foo = 42
3241 s = p.dumps(u, bin)
3242 v = p.loads(s)
3243 self.assertEqual(u.__class__, v.__class__)
3244 self.assertEqual(u.foo, v.foo)
3245
3246 # Testing copy.deepcopy()
3247 import copy
3248 for cls in C, C1, C2:
3249 cls2 = copy.deepcopy(cls)
3250 self.assert_(cls2 is cls)
3251
3252 a = C1(1, 2); a.append(42); a.append(24)
3253 b = C2("hello", "world", 42)
3254 x, y = copy.deepcopy((a, b))
3255 self.assertEqual(x.__class__, a.__class__)
3256 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3257 self.assertEqual(y.__class__, b.__class__)
3258 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3259 self.assertEqual(repr(x), repr(a))
3260 self.assertEqual(repr(y), repr(b))
3261
3262 def test_pickle_slots(self):
3263 # Testing pickling of classes with __slots__ ...
3264 import pickle, cPickle
3265 # Pickling of classes with __slots__ but without __getstate__ should fail
3266 global B, C, D, E
3267 class B(object):
3268 pass
3269 for base in [object, B]:
3270 class C(base):
3271 __slots__ = ['a']
3272 class D(C):
3273 pass
3274 try:
3275 pickle.dumps(C())
3276 except TypeError:
3277 pass
3278 else:
3279 self.fail("should fail: pickle C instance - %s" % base)
3280 try:
3281 cPickle.dumps(C())
3282 except TypeError:
3283 pass
3284 else:
3285 self.fail("should fail: cPickle C instance - %s" % base)
3286 try:
3287 pickle.dumps(C())
3288 except TypeError:
3289 pass
3290 else:
3291 self.fail("should fail: pickle D instance - %s" % base)
3292 try:
3293 cPickle.dumps(D())
3294 except TypeError:
3295 pass
3296 else:
3297 self.fail("should fail: cPickle D instance - %s" % base)
3298 # Give C a nice generic __getstate__ and __setstate__
3299 class C(base):
3300 __slots__ = ['a']
3301 def __getstate__(self):
3302 try:
3303 d = self.__dict__.copy()
3304 except AttributeError:
3305 d = {}
3306 for cls in self.__class__.__mro__:
3307 for sn in cls.__dict__.get('__slots__', ()):
3308 try:
3309 d[sn] = getattr(self, sn)
3310 except AttributeError:
3311 pass
3312 return d
3313 def __setstate__(self, d):
3314 for k, v in d.items():
3315 setattr(self, k, v)
3316 class D(C):
3317 pass
3318 # Now it should work
3319 x = C()
3320 y = pickle.loads(pickle.dumps(x))
3321 self.assertEqual(hasattr(y, 'a'), 0)
3322 y = cPickle.loads(cPickle.dumps(x))
3323 self.assertEqual(hasattr(y, 'a'), 0)
3324 x.a = 42
3325 y = pickle.loads(pickle.dumps(x))
3326 self.assertEqual(y.a, 42)
3327 y = cPickle.loads(cPickle.dumps(x))
3328 self.assertEqual(y.a, 42)
3329 x = D()
3330 x.a = 42
3331 x.b = 100
3332 y = pickle.loads(pickle.dumps(x))
3333 self.assertEqual(y.a + y.b, 142)
3334 y = cPickle.loads(cPickle.dumps(x))
3335 self.assertEqual(y.a + y.b, 142)
3336 # A subclass that adds a slot should also work
3337 class E(C):
3338 __slots__ = ['b']
3339 x = E()
3340 x.a = 42
3341 x.b = "foo"
3342 y = pickle.loads(pickle.dumps(x))
3343 self.assertEqual(y.a, x.a)
3344 self.assertEqual(y.b, x.b)
3345 y = cPickle.loads(cPickle.dumps(x))
3346 self.assertEqual(y.a, x.a)
3347 self.assertEqual(y.b, x.b)
3348
3349 def test_binary_operator_override(self):
3350 # Testing overrides of binary operations...
3351 class I(int):
3352 def __repr__(self):
3353 return "I(%r)" % int(self)
3354 def __add__(self, other):
3355 return I(int(self) + int(other))
3356 __radd__ = __add__
3357 def __pow__(self, other, mod=None):
3358 if mod is None:
3359 return I(pow(int(self), int(other)))
3360 else:
3361 return I(pow(int(self), int(other), int(mod)))
3362 def __rpow__(self, other, mod=None):
3363 if mod is None:
3364 return I(pow(int(other), int(self), mod))
3365 else:
3366 return I(pow(int(other), int(self), int(mod)))
3367
3368 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3369 self.assertEqual(repr(I(1) + 2), "I(3)")
3370 self.assertEqual(repr(1 + I(2)), "I(3)")
3371 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3372 self.assertEqual(repr(2 ** I(3)), "I(8)")
3373 self.assertEqual(repr(I(2) ** 3), "I(8)")
3374 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3375 class S(str):
3376 def __eq__(self, other):
3377 return self.lower() == other.lower()
Nick Coghlan48361f52008-08-11 15:45:58 +00003378 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00003379
3380 def test_subclass_propagation(self):
3381 # Testing propagation of slot functions to subclasses...
3382 class A(object):
3383 pass
3384 class B(A):
3385 pass
3386 class C(A):
3387 pass
3388 class D(B, C):
3389 pass
3390 d = D()
3391 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3392 A.__hash__ = lambda self: 42
3393 self.assertEqual(hash(d), 42)
3394 C.__hash__ = lambda self: 314
3395 self.assertEqual(hash(d), 314)
3396 B.__hash__ = lambda self: 144
3397 self.assertEqual(hash(d), 144)
3398 D.__hash__ = lambda self: 100
3399 self.assertEqual(hash(d), 100)
Nick Coghlan53663a62008-07-15 14:27:37 +00003400 D.__hash__ = None
3401 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003402 del D.__hash__
3403 self.assertEqual(hash(d), 144)
Nick Coghlan53663a62008-07-15 14:27:37 +00003404 B.__hash__ = None
3405 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003406 del B.__hash__
3407 self.assertEqual(hash(d), 314)
Nick Coghlan53663a62008-07-15 14:27:37 +00003408 C.__hash__ = None
3409 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003410 del C.__hash__
3411 self.assertEqual(hash(d), 42)
Nick Coghlan53663a62008-07-15 14:27:37 +00003412 A.__hash__ = None
3413 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003414 del A.__hash__
3415 self.assertEqual(hash(d), orig_hash)
3416 d.foo = 42
3417 d.bar = 42
3418 self.assertEqual(d.foo, 42)
3419 self.assertEqual(d.bar, 42)
3420 def __getattribute__(self, name):
3421 if name == "foo":
3422 return 24
3423 return object.__getattribute__(self, name)
3424 A.__getattribute__ = __getattribute__
3425 self.assertEqual(d.foo, 24)
3426 self.assertEqual(d.bar, 42)
3427 def __getattr__(self, name):
3428 if name in ("spam", "foo", "bar"):
3429 return "hello"
3430 raise AttributeError, name
3431 B.__getattr__ = __getattr__
3432 self.assertEqual(d.spam, "hello")
3433 self.assertEqual(d.foo, 24)
3434 self.assertEqual(d.bar, 42)
3435 del A.__getattribute__
3436 self.assertEqual(d.foo, 42)
3437 del d.foo
3438 self.assertEqual(d.foo, "hello")
3439 self.assertEqual(d.bar, 42)
3440 del B.__getattr__
3441 try:
3442 d.foo
3443 except AttributeError:
3444 pass
3445 else:
3446 self.fail("d.foo should be undefined now")
3447
3448 # Test a nasty bug in recurse_down_subclasses()
3449 import gc
3450 class A(object):
3451 pass
3452 class B(A):
3453 pass
3454 del B
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003455 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003456 A.__setitem__ = lambda *a: None # crash
3457
3458 def test_buffer_inheritance(self):
3459 # Testing that buffer interface is inherited ...
3460
3461 import binascii
3462 # SF bug [#470040] ParseTuple t# vs subclasses.
3463
3464 class MyStr(str):
3465 pass
3466 base = 'abc'
3467 m = MyStr(base)
3468 # b2a_hex uses the buffer interface to get its argument's value, via
3469 # PyArg_ParseTuple 't#' code.
3470 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3471
3472 # It's not clear that unicode will continue to support the character
3473 # buffer interface, and this test will fail if that's taken away.
3474 class MyUni(unicode):
3475 pass
3476 base = u'abc'
3477 m = MyUni(base)
3478 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3479
3480 class MyInt(int):
3481 pass
3482 m = MyInt(42)
3483 try:
3484 binascii.b2a_hex(m)
3485 self.fail('subclass of int should not have a buffer interface')
3486 except TypeError:
3487 pass
3488
3489 def test_str_of_str_subclass(self):
3490 # Testing __str__ defined in subclass of str ...
3491 import binascii
3492 import cStringIO
3493
3494 class octetstring(str):
3495 def __str__(self):
3496 return binascii.b2a_hex(self)
3497 def __repr__(self):
3498 return self + " repr"
3499
3500 o = octetstring('A')
3501 self.assertEqual(type(o), octetstring)
3502 self.assertEqual(type(str(o)), str)
3503 self.assertEqual(type(repr(o)), str)
3504 self.assertEqual(ord(o), 0x41)
3505 self.assertEqual(str(o), '41')
3506 self.assertEqual(repr(o), 'A repr')
3507 self.assertEqual(o.__str__(), '41')
3508 self.assertEqual(o.__repr__(), 'A repr')
3509
3510 capture = cStringIO.StringIO()
3511 # Calling str() or not exercises different internal paths.
3512 print >> capture, o
3513 print >> capture, str(o)
3514 self.assertEqual(capture.getvalue(), '41\n41\n')
3515 capture.close()
3516
3517 def test_keyword_arguments(self):
3518 # Testing keyword arguments to __init__, __call__...
3519 def f(a): return a
3520 self.assertEqual(f.__call__(a=42), 42)
3521 a = []
3522 list.__init__(a, sequence=[0, 1, 2])
3523 self.assertEqual(a, [0, 1, 2])
3524
3525 def test_recursive_call(self):
3526 # Testing recursive __call__() by setting to instance of class...
3527 class A(object):
3528 pass
3529
3530 A.__call__ = A()
3531 try:
3532 A()()
3533 except RuntimeError:
3534 pass
3535 else:
3536 self.fail("Recursion limit should have been reached for __call__()")
3537
3538 def test_delete_hook(self):
3539 # Testing __del__ hook...
3540 log = []
3541 class C(object):
3542 def __del__(self):
3543 log.append(1)
3544 c = C()
3545 self.assertEqual(log, [])
3546 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003547 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003548 self.assertEqual(log, [1])
3549
3550 class D(object): pass
3551 d = D()
3552 try: del d[0]
3553 except TypeError: pass
3554 else: self.fail("invalid del() didn't raise TypeError")
3555
3556 def test_hash_inheritance(self):
3557 # Testing hash of mutable subclasses...
3558
3559 class mydict(dict):
3560 pass
3561 d = mydict()
3562 try:
3563 hash(d)
3564 except TypeError:
3565 pass
3566 else:
3567 self.fail("hash() of dict subclass should fail")
3568
3569 class mylist(list):
3570 pass
3571 d = mylist()
3572 try:
3573 hash(d)
3574 except TypeError:
3575 pass
3576 else:
3577 self.fail("hash() of list subclass should fail")
3578
3579 def test_str_operations(self):
3580 try: 'a' + 5
3581 except TypeError: pass
3582 else: self.fail("'' + 5 doesn't raise TypeError")
3583
3584 try: ''.split('')
3585 except ValueError: pass
3586 else: self.fail("''.split('') doesn't raise ValueError")
3587
3588 try: ''.join([0])
3589 except TypeError: pass
3590 else: self.fail("''.join([0]) doesn't raise TypeError")
3591
3592 try: ''.rindex('5')
3593 except ValueError: pass
3594 else: self.fail("''.rindex('5') doesn't raise ValueError")
3595
3596 try: '%(n)s' % None
3597 except TypeError: pass
3598 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3599
3600 try: '%(n' % {}
3601 except ValueError: pass
3602 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3603
3604 try: '%*s' % ('abc')
3605 except TypeError: pass
3606 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3607
3608 try: '%*.*s' % ('abc', 5)
3609 except TypeError: pass
3610 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3611
3612 try: '%s' % (1, 2)
3613 except TypeError: pass
3614 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3615
3616 try: '%' % None
3617 except ValueError: pass
3618 else: self.fail("'%' % None doesn't raise ValueError")
3619
3620 self.assertEqual('534253'.isdigit(), 1)
3621 self.assertEqual('534253x'.isdigit(), 0)
3622 self.assertEqual('%c' % 5, '\x05')
3623 self.assertEqual('%c' % '5', '5')
3624
3625 def test_deepcopy_recursive(self):
3626 # Testing deepcopy of recursive objects...
3627 class Node:
3628 pass
3629 a = Node()
3630 b = Node()
3631 a.b = b
3632 b.a = a
3633 z = deepcopy(a) # This blew up before
3634
3635 def test_unintialized_modules(self):
3636 # Testing uninitialized module objects...
3637 from types import ModuleType as M
3638 m = M.__new__(M)
3639 str(m)
3640 self.assertEqual(hasattr(m, "__name__"), 0)
3641 self.assertEqual(hasattr(m, "__file__"), 0)
3642 self.assertEqual(hasattr(m, "foo"), 0)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003643 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl48545522008-02-02 10:12:36 +00003644 m.foo = 1
3645 self.assertEqual(m.__dict__, {"foo": 1})
3646
3647 def test_funny_new(self):
3648 # Testing __new__ returning something unexpected...
3649 class C(object):
3650 def __new__(cls, arg):
3651 if isinstance(arg, str): return [1, 2, 3]
3652 elif isinstance(arg, int): return object.__new__(D)
3653 else: return object.__new__(cls)
3654 class D(C):
3655 def __init__(self, arg):
3656 self.foo = arg
3657 self.assertEqual(C("1"), [1, 2, 3])
3658 self.assertEqual(D("1"), [1, 2, 3])
3659 d = D(None)
3660 self.assertEqual(d.foo, None)
3661 d = C(1)
3662 self.assertEqual(isinstance(d, D), True)
3663 self.assertEqual(d.foo, 1)
3664 d = D(1)
3665 self.assertEqual(isinstance(d, D), True)
3666 self.assertEqual(d.foo, 1)
3667
3668 def test_imul_bug(self):
3669 # Testing for __imul__ problems...
3670 # SF bug 544647
3671 class C(object):
3672 def __imul__(self, other):
3673 return (self, other)
3674 x = C()
3675 y = x
3676 y *= 1.0
3677 self.assertEqual(y, (x, 1.0))
3678 y = x
3679 y *= 2
3680 self.assertEqual(y, (x, 2))
3681 y = x
3682 y *= 3L
3683 self.assertEqual(y, (x, 3L))
3684 y = x
3685 y *= 1L<<100
3686 self.assertEqual(y, (x, 1L<<100))
3687 y = x
3688 y *= None
3689 self.assertEqual(y, (x, None))
3690 y = x
3691 y *= "foo"
3692 self.assertEqual(y, (x, "foo"))
3693
3694 def test_copy_setstate(self):
3695 # Testing that copy.*copy() correctly uses __setstate__...
3696 import copy
3697 class C(object):
3698 def __init__(self, foo=None):
3699 self.foo = foo
3700 self.__foo = foo
3701 def setfoo(self, foo=None):
3702 self.foo = foo
3703 def getfoo(self):
3704 return self.__foo
3705 def __getstate__(self):
3706 return [self.foo]
3707 def __setstate__(self_, lst):
3708 self.assertEqual(len(lst), 1)
3709 self_.__foo = self_.foo = lst[0]
3710 a = C(42)
3711 a.setfoo(24)
3712 self.assertEqual(a.foo, 24)
3713 self.assertEqual(a.getfoo(), 42)
3714 b = copy.copy(a)
3715 self.assertEqual(b.foo, 24)
3716 self.assertEqual(b.getfoo(), 24)
3717 b = copy.deepcopy(a)
3718 self.assertEqual(b.foo, 24)
3719 self.assertEqual(b.getfoo(), 24)
3720
3721 def test_slices(self):
3722 # Testing cases with slices and overridden __getitem__ ...
3723
3724 # Strings
3725 self.assertEqual("hello"[:4], "hell")
3726 self.assertEqual("hello"[slice(4)], "hell")
3727 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3728 class S(str):
3729 def __getitem__(self, x):
3730 return str.__getitem__(self, x)
3731 self.assertEqual(S("hello")[:4], "hell")
3732 self.assertEqual(S("hello")[slice(4)], "hell")
3733 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3734 # Tuples
3735 self.assertEqual((1,2,3)[:2], (1,2))
3736 self.assertEqual((1,2,3)[slice(2)], (1,2))
3737 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3738 class T(tuple):
3739 def __getitem__(self, x):
3740 return tuple.__getitem__(self, x)
3741 self.assertEqual(T((1,2,3))[:2], (1,2))
3742 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3743 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3744 # Lists
3745 self.assertEqual([1,2,3][:2], [1,2])
3746 self.assertEqual([1,2,3][slice(2)], [1,2])
3747 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3748 class L(list):
3749 def __getitem__(self, x):
3750 return list.__getitem__(self, x)
3751 self.assertEqual(L([1,2,3])[:2], [1,2])
3752 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3753 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3754 # Now do lists and __setitem__
3755 a = L([1,2,3])
3756 a[slice(1, 3)] = [3,2]
3757 self.assertEqual(a, [1,3,2])
3758 a[slice(0, 2, 1)] = [3,1]
3759 self.assertEqual(a, [3,1,2])
3760 a.__setitem__(slice(1, 3), [2,1])
3761 self.assertEqual(a, [3,2,1])
3762 a.__setitem__(slice(0, 2, 1), [2,3])
3763 self.assertEqual(a, [2,3,1])
3764
3765 def test_subtype_resurrection(self):
3766 # Testing resurrection of new-style instance...
3767
3768 class C(object):
3769 container = []
3770
3771 def __del__(self):
3772 # resurrect the instance
3773 C.container.append(self)
3774
3775 c = C()
3776 c.attr = 42
3777
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003778 # The most interesting thing here is whether this blows up, due to
3779 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3780 # bug).
Georg Brandl48545522008-02-02 10:12:36 +00003781 del c
3782
3783 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003784 # the last container slot works: that will attempt to delete c again,
3785 # which will cause c to get appended back to the container again
3786 # "during" the del. (On non-CPython implementations, however, __del__
3787 # is typically not called again.)
3788 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003789 self.assertEqual(len(C.container), 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003790 del C.container[-1]
3791 if test_support.check_impl_detail():
3792 test_support.gc_collect()
3793 self.assertEqual(len(C.container), 1)
3794 self.assertEqual(C.container[-1].attr, 42)
Georg Brandl48545522008-02-02 10:12:36 +00003795
3796 # Make c mortal again, so that the test framework with -l doesn't report
3797 # it as a leak.
3798 del C.__del__
3799
3800 def test_slots_trash(self):
3801 # Testing slot trash...
3802 # Deallocating deeply nested slotted trash caused stack overflows
3803 class trash(object):
3804 __slots__ = ['x']
3805 def __init__(self, x):
3806 self.x = x
3807 o = None
3808 for i in xrange(50000):
3809 o = trash(o)
3810 del o
3811
3812 def test_slots_multiple_inheritance(self):
3813 # SF bug 575229, multiple inheritance w/ slots dumps core
3814 class A(object):
3815 __slots__=()
3816 class B(object):
3817 pass
3818 class C(A,B) :
3819 __slots__=()
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003820 if test_support.check_impl_detail():
3821 self.assertEqual(C.__basicsize__, B.__basicsize__)
Georg Brandl48545522008-02-02 10:12:36 +00003822 self.assert_(hasattr(C, '__dict__'))
3823 self.assert_(hasattr(C, '__weakref__'))
3824 C().x = 2
3825
3826 def test_rmul(self):
3827 # Testing correct invocation of __rmul__...
3828 # SF patch 592646
3829 class C(object):
3830 def __mul__(self, other):
3831 return "mul"
3832 def __rmul__(self, other):
3833 return "rmul"
3834 a = C()
3835 self.assertEqual(a*2, "mul")
3836 self.assertEqual(a*2.2, "mul")
3837 self.assertEqual(2*a, "rmul")
3838 self.assertEqual(2.2*a, "rmul")
3839
3840 def test_ipow(self):
3841 # Testing correct invocation of __ipow__...
3842 # [SF bug 620179]
3843 class C(object):
3844 def __ipow__(self, other):
3845 pass
3846 a = C()
3847 a **= 2
3848
3849 def test_mutable_bases(self):
3850 # Testing mutable bases...
3851
3852 # stuff that should work:
3853 class C(object):
3854 pass
3855 class C2(object):
3856 def __getattribute__(self, attr):
3857 if attr == 'a':
3858 return 2
3859 else:
3860 return super(C2, self).__getattribute__(attr)
3861 def meth(self):
3862 return 1
3863 class D(C):
3864 pass
3865 class E(D):
3866 pass
3867 d = D()
3868 e = E()
3869 D.__bases__ = (C,)
3870 D.__bases__ = (C2,)
3871 self.assertEqual(d.meth(), 1)
3872 self.assertEqual(e.meth(), 1)
3873 self.assertEqual(d.a, 2)
3874 self.assertEqual(e.a, 2)
3875 self.assertEqual(C2.__subclasses__(), [D])
3876
Georg Brandl48545522008-02-02 10:12:36 +00003877 try:
3878 del D.__bases__
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003879 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00003880 pass
3881 else:
3882 self.fail("shouldn't be able to delete .__bases__")
3883
3884 try:
3885 D.__bases__ = ()
3886 except TypeError, msg:
3887 if str(msg) == "a new-style class can't have only classic bases":
3888 self.fail("wrong error message for .__bases__ = ()")
3889 else:
3890 self.fail("shouldn't be able to set .__bases__ to ()")
3891
3892 try:
3893 D.__bases__ = (D,)
3894 except TypeError:
3895 pass
3896 else:
3897 # actually, we'll have crashed by here...
3898 self.fail("shouldn't be able to create inheritance cycles")
3899
3900 try:
3901 D.__bases__ = (C, C)
3902 except TypeError:
3903 pass
3904 else:
3905 self.fail("didn't detect repeated base classes")
3906
3907 try:
3908 D.__bases__ = (E,)
3909 except TypeError:
3910 pass
3911 else:
3912 self.fail("shouldn't be able to create inheritance cycles")
3913
3914 # let's throw a classic class into the mix:
3915 class Classic:
3916 def meth2(self):
3917 return 3
3918
3919 D.__bases__ = (C, Classic)
3920
3921 self.assertEqual(d.meth2(), 3)
3922 self.assertEqual(e.meth2(), 3)
3923 try:
3924 d.a
3925 except AttributeError:
3926 pass
3927 else:
3928 self.fail("attribute should have vanished")
3929
3930 try:
3931 D.__bases__ = (Classic,)
3932 except TypeError:
3933 pass
3934 else:
3935 self.fail("new-style class must have a new-style base")
3936
Benjamin Petersond4d400c2009-04-18 20:12:47 +00003937 def test_builtin_bases(self):
3938 # Make sure all the builtin types can have their base queried without
3939 # segfaulting. See issue #5787.
3940 builtin_types = [tp for tp in __builtin__.__dict__.itervalues()
3941 if isinstance(tp, type)]
3942 for tp in builtin_types:
3943 object.__getattribute__(tp, "__bases__")
3944 if tp is not object:
3945 self.assertEqual(len(tp.__bases__), 1, tp)
3946
Benjamin Petersonaccb3d02009-04-18 21:03:10 +00003947 class L(list):
3948 pass
3949
3950 class C(object):
3951 pass
3952
3953 class D(C):
3954 pass
3955
3956 try:
3957 L.__bases__ = (dict,)
3958 except TypeError:
3959 pass
3960 else:
3961 self.fail("shouldn't turn list subclass into dict subclass")
3962
3963 try:
3964 list.__bases__ = (dict,)
3965 except TypeError:
3966 pass
3967 else:
3968 self.fail("shouldn't be able to assign to list.__bases__")
3969
3970 try:
3971 D.__bases__ = (C, list)
3972 except TypeError:
3973 pass
3974 else:
3975 assert 0, "best_base calculation found wanting"
3976
Benjamin Petersond4d400c2009-04-18 20:12:47 +00003977
Georg Brandl48545522008-02-02 10:12:36 +00003978 def test_mutable_bases_with_failing_mro(self):
3979 # Testing mutable bases with failing mro...
3980 class WorkOnce(type):
3981 def __new__(self, name, bases, ns):
3982 self.flag = 0
3983 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3984 def mro(self):
3985 if self.flag > 0:
3986 raise RuntimeError, "bozo"
3987 else:
3988 self.flag += 1
3989 return type.mro(self)
3990
3991 class WorkAlways(type):
3992 def mro(self):
3993 # this is here to make sure that .mro()s aren't called
3994 # with an exception set (which was possible at one point).
3995 # An error message will be printed in a debug build.
3996 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003997 return type.mro(self)
3998
Georg Brandl48545522008-02-02 10:12:36 +00003999 class C(object):
4000 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004001
Georg Brandl48545522008-02-02 10:12:36 +00004002 class C2(object):
4003 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004004
Georg Brandl48545522008-02-02 10:12:36 +00004005 class D(C):
4006 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004007
Georg Brandl48545522008-02-02 10:12:36 +00004008 class E(D):
4009 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004010
Georg Brandl48545522008-02-02 10:12:36 +00004011 class F(D):
4012 __metaclass__ = WorkOnce
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004013
Georg Brandl48545522008-02-02 10:12:36 +00004014 class G(D):
4015 __metaclass__ = WorkAlways
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004016
Georg Brandl48545522008-02-02 10:12:36 +00004017 # Immediate subclasses have their mro's adjusted in alphabetical
4018 # order, so E's will get adjusted before adjusting F's fails. We
4019 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004020
Georg Brandl48545522008-02-02 10:12:36 +00004021 E_mro_before = E.__mro__
4022 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00004023
Armin Rigofd163f92005-12-29 15:59:19 +00004024 try:
Georg Brandl48545522008-02-02 10:12:36 +00004025 D.__bases__ = (C2,)
4026 except RuntimeError:
4027 self.assertEqual(E.__mro__, E_mro_before)
4028 self.assertEqual(D.__mro__, D_mro_before)
4029 else:
4030 self.fail("exception not propagated")
4031
4032 def test_mutable_bases_catch_mro_conflict(self):
4033 # Testing mutable bases catch mro conflict...
4034 class A(object):
4035 pass
4036
4037 class B(object):
4038 pass
4039
4040 class C(A, B):
4041 pass
4042
4043 class D(A, B):
4044 pass
4045
4046 class E(C, D):
4047 pass
4048
4049 try:
4050 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00004051 except TypeError:
4052 pass
4053 else:
Georg Brandl48545522008-02-02 10:12:36 +00004054 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00004055
Georg Brandl48545522008-02-02 10:12:36 +00004056 def test_mutable_names(self):
4057 # Testing mutable names...
4058 class C(object):
4059 pass
4060
4061 # C.__module__ could be 'test_descr' or '__main__'
4062 mod = C.__module__
4063
4064 C.__name__ = 'D'
4065 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4066
4067 C.__name__ = 'D.E'
4068 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4069
4070 def test_subclass_right_op(self):
4071 # Testing correct dispatch of subclass overloading __r<op>__...
4072
4073 # This code tests various cases where right-dispatch of a subclass
4074 # should be preferred over left-dispatch of a base class.
4075
4076 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4077
4078 class B(int):
4079 def __floordiv__(self, other):
4080 return "B.__floordiv__"
4081 def __rfloordiv__(self, other):
4082 return "B.__rfloordiv__"
4083
4084 self.assertEqual(B(1) // 1, "B.__floordiv__")
4085 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4086
4087 # Case 2: subclass of object; this is just the baseline for case 3
4088
4089 class C(object):
4090 def __floordiv__(self, other):
4091 return "C.__floordiv__"
4092 def __rfloordiv__(self, other):
4093 return "C.__rfloordiv__"
4094
4095 self.assertEqual(C() // 1, "C.__floordiv__")
4096 self.assertEqual(1 // C(), "C.__rfloordiv__")
4097
4098 # Case 3: subclass of new-style class; here it gets interesting
4099
4100 class D(C):
4101 def __floordiv__(self, other):
4102 return "D.__floordiv__"
4103 def __rfloordiv__(self, other):
4104 return "D.__rfloordiv__"
4105
4106 self.assertEqual(D() // C(), "D.__floordiv__")
4107 self.assertEqual(C() // D(), "D.__rfloordiv__")
4108
4109 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4110
4111 class E(C):
4112 pass
4113
4114 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4115
4116 self.assertEqual(E() // 1, "C.__floordiv__")
4117 self.assertEqual(1 // E(), "C.__rfloordiv__")
4118 self.assertEqual(E() // C(), "C.__floordiv__")
4119 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4120
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004121 @test_support.impl_detail("testing an internal kind of method object")
Georg Brandl48545522008-02-02 10:12:36 +00004122 def test_meth_class_get(self):
4123 # Testing __get__ method of METH_CLASS C methods...
4124 # Full coverage of descrobject.c::classmethod_get()
4125
4126 # Baseline
4127 arg = [1, 2, 3]
4128 res = {1: None, 2: None, 3: None}
4129 self.assertEqual(dict.fromkeys(arg), res)
4130 self.assertEqual({}.fromkeys(arg), res)
4131
4132 # Now get the descriptor
4133 descr = dict.__dict__["fromkeys"]
4134
4135 # More baseline using the descriptor directly
4136 self.assertEqual(descr.__get__(None, dict)(arg), res)
4137 self.assertEqual(descr.__get__({})(arg), res)
4138
4139 # Now check various error cases
4140 try:
4141 descr.__get__(None, None)
4142 except TypeError:
4143 pass
4144 else:
4145 self.fail("shouldn't have allowed descr.__get__(None, None)")
4146 try:
4147 descr.__get__(42)
4148 except TypeError:
4149 pass
4150 else:
4151 self.fail("shouldn't have allowed descr.__get__(42)")
4152 try:
4153 descr.__get__(None, 42)
4154 except TypeError:
4155 pass
4156 else:
4157 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4158 try:
4159 descr.__get__(None, int)
4160 except TypeError:
4161 pass
4162 else:
4163 self.fail("shouldn't have allowed descr.__get__(None, int)")
4164
4165 def test_isinst_isclass(self):
4166 # Testing proxy isinstance() and isclass()...
4167 class Proxy(object):
4168 def __init__(self, obj):
4169 self.__obj = obj
4170 def __getattribute__(self, name):
4171 if name.startswith("_Proxy__"):
4172 return object.__getattribute__(self, name)
4173 else:
4174 return getattr(self.__obj, name)
4175 # Test with a classic class
4176 class C:
4177 pass
4178 a = C()
4179 pa = Proxy(a)
4180 self.assert_(isinstance(a, C)) # Baseline
4181 self.assert_(isinstance(pa, C)) # Test
4182 # Test with a classic subclass
4183 class D(C):
4184 pass
4185 a = D()
4186 pa = Proxy(a)
4187 self.assert_(isinstance(a, C)) # Baseline
4188 self.assert_(isinstance(pa, C)) # Test
4189 # Test with a new-style class
4190 class C(object):
4191 pass
4192 a = C()
4193 pa = Proxy(a)
4194 self.assert_(isinstance(a, C)) # Baseline
4195 self.assert_(isinstance(pa, C)) # Test
4196 # Test with a new-style subclass
4197 class D(C):
4198 pass
4199 a = D()
4200 pa = Proxy(a)
4201 self.assert_(isinstance(a, C)) # Baseline
4202 self.assert_(isinstance(pa, C)) # Test
4203
4204 def test_proxy_super(self):
4205 # Testing super() for a proxy object...
4206 class Proxy(object):
4207 def __init__(self, obj):
4208 self.__obj = obj
4209 def __getattribute__(self, name):
4210 if name.startswith("_Proxy__"):
4211 return object.__getattribute__(self, name)
4212 else:
4213 return getattr(self.__obj, name)
4214
4215 class B(object):
4216 def f(self):
4217 return "B.f"
4218
4219 class C(B):
4220 def f(self):
4221 return super(C, self).f() + "->C.f"
4222
4223 obj = C()
4224 p = Proxy(obj)
4225 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4226
4227 def test_carloverre(self):
4228 # Testing prohibition of Carlo Verre's hack...
4229 try:
4230 object.__setattr__(str, "foo", 42)
4231 except TypeError:
4232 pass
4233 else:
4234 self.fail("Carlo Verre __setattr__ suceeded!")
4235 try:
4236 object.__delattr__(str, "lower")
4237 except TypeError:
4238 pass
4239 else:
4240 self.fail("Carlo Verre __delattr__ succeeded!")
4241
4242 def test_weakref_segfault(self):
4243 # Testing weakref segfault...
4244 # SF 742911
4245 import weakref
4246
4247 class Provoker:
4248 def __init__(self, referrent):
4249 self.ref = weakref.ref(referrent)
4250
4251 def __del__(self):
4252 x = self.ref()
4253
4254 class Oops(object):
4255 pass
4256
4257 o = Oops()
4258 o.whatever = Provoker(o)
4259 del o
4260
4261 def test_wrapper_segfault(self):
4262 # SF 927248: deeply nested wrappers could cause stack overflow
4263 f = lambda:None
4264 for i in xrange(1000000):
4265 f = f.__call__
4266 f = None
4267
4268 def test_file_fault(self):
4269 # Testing sys.stdout is changed in getattr...
4270 import sys
4271 class StdoutGuard:
4272 def __getattr__(self, attr):
4273 sys.stdout = sys.__stdout__
4274 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4275 sys.stdout = StdoutGuard()
4276 try:
4277 print "Oops!"
4278 except RuntimeError:
4279 pass
4280
4281 def test_vicious_descriptor_nonsense(self):
4282 # Testing vicious_descriptor_nonsense...
4283
4284 # A potential segfault spotted by Thomas Wouters in mail to
4285 # python-dev 2003-04-17, turned into an example & fixed by Michael
4286 # Hudson just less than four months later...
4287
4288 class Evil(object):
4289 def __hash__(self):
4290 return hash('attr')
4291 def __eq__(self, other):
4292 del C.attr
4293 return 0
4294
4295 class Descr(object):
4296 def __get__(self, ob, type=None):
4297 return 1
4298
4299 class C(object):
4300 attr = Descr()
4301
4302 c = C()
4303 c.__dict__[Evil()] = 0
4304
4305 self.assertEqual(c.attr, 1)
4306 # this makes a crash more likely:
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004307 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00004308 self.assertEqual(hasattr(c, 'attr'), False)
4309
4310 def test_init(self):
4311 # SF 1155938
4312 class Foo(object):
4313 def __init__(self):
4314 return 10
4315 try:
4316 Foo()
4317 except TypeError:
4318 pass
4319 else:
4320 self.fail("did not test __init__() for None return")
4321
4322 def test_method_wrapper(self):
4323 # Testing method-wrapper objects...
4324 # <type 'method-wrapper'> did not support any reflection before 2.5
4325
4326 l = []
4327 self.assertEqual(l.__add__, l.__add__)
4328 self.assertEqual(l.__add__, [].__add__)
4329 self.assert_(l.__add__ != [5].__add__)
4330 self.assert_(l.__add__ != l.__mul__)
4331 self.assert_(l.__add__.__name__ == '__add__')
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004332 if hasattr(l.__add__, '__self__'):
4333 # CPython
4334 self.assert_(l.__add__.__self__ is l)
4335 self.assert_(l.__add__.__objclass__ is list)
4336 else:
4337 # Python implementations where [].__add__ is a normal bound method
4338 self.assert_(l.__add__.im_self is l)
4339 self.assert_(l.__add__.im_class is list)
Georg Brandl48545522008-02-02 10:12:36 +00004340 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4341 try:
4342 hash(l.__add__)
4343 except TypeError:
4344 pass
4345 else:
4346 self.fail("no TypeError from hash([].__add__)")
4347
4348 t = ()
4349 t += (7,)
4350 self.assertEqual(t.__add__, (7,).__add__)
4351 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4352
4353 def test_not_implemented(self):
4354 # Testing NotImplemented...
4355 # all binary methods should be able to return a NotImplemented
4356 import sys
4357 import types
4358 import operator
4359
4360 def specialmethod(self, other):
4361 return NotImplemented
4362
4363 def check(expr, x, y):
4364 try:
4365 exec expr in {'x': x, 'y': y, 'operator': operator}
4366 except TypeError:
4367 pass
Armin Rigofd163f92005-12-29 15:59:19 +00004368 else:
Georg Brandl48545522008-02-02 10:12:36 +00004369 self.fail("no TypeError from %r" % (expr,))
Armin Rigofd163f92005-12-29 15:59:19 +00004370
Georg Brandl48545522008-02-02 10:12:36 +00004371 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of
4372 # TypeErrors
4373 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4374 # ValueErrors instead of TypeErrors
4375 for metaclass in [type, types.ClassType]:
4376 for name, expr, iexpr in [
4377 ('__add__', 'x + y', 'x += y'),
4378 ('__sub__', 'x - y', 'x -= y'),
4379 ('__mul__', 'x * y', 'x *= y'),
4380 ('__truediv__', 'operator.truediv(x, y)', None),
4381 ('__floordiv__', 'operator.floordiv(x, y)', None),
4382 ('__div__', 'x / y', 'x /= y'),
4383 ('__mod__', 'x % y', 'x %= y'),
4384 ('__divmod__', 'divmod(x, y)', None),
4385 ('__pow__', 'x ** y', 'x **= y'),
4386 ('__lshift__', 'x << y', 'x <<= y'),
4387 ('__rshift__', 'x >> y', 'x >>= y'),
4388 ('__and__', 'x & y', 'x &= y'),
4389 ('__or__', 'x | y', 'x |= y'),
4390 ('__xor__', 'x ^ y', 'x ^= y'),
4391 ('__coerce__', 'coerce(x, y)', None)]:
4392 if name == '__coerce__':
4393 rname = name
4394 else:
4395 rname = '__r' + name[2:]
4396 A = metaclass('A', (), {name: specialmethod})
4397 B = metaclass('B', (), {rname: specialmethod})
4398 a = A()
4399 b = B()
4400 check(expr, a, a)
4401 check(expr, a, b)
4402 check(expr, b, a)
4403 check(expr, b, b)
4404 check(expr, a, N1)
4405 check(expr, a, N2)
4406 check(expr, N1, b)
4407 check(expr, N2, b)
4408 if iexpr:
4409 check(iexpr, a, a)
4410 check(iexpr, a, b)
4411 check(iexpr, b, a)
4412 check(iexpr, b, b)
4413 check(iexpr, a, N1)
4414 check(iexpr, a, N2)
4415 iname = '__i' + name[2:]
4416 C = metaclass('C', (), {iname: specialmethod})
4417 c = C()
4418 check(iexpr, c, a)
4419 check(iexpr, c, b)
4420 check(iexpr, c, N1)
4421 check(iexpr, c, N2)
Georg Brandl0fca97a2007-03-05 22:28:08 +00004422
Georg Brandl48545522008-02-02 10:12:36 +00004423 def test_assign_slice(self):
4424 # ceval.c's assign_slice used to check for
4425 # tp->tp_as_sequence->sq_slice instead of
4426 # tp->tp_as_sequence->sq_ass_slice
Georg Brandl0fca97a2007-03-05 22:28:08 +00004427
Georg Brandl48545522008-02-02 10:12:36 +00004428 class C(object):
4429 def __setslice__(self, start, stop, value):
4430 self.value = value
Georg Brandl0fca97a2007-03-05 22:28:08 +00004431
Georg Brandl48545522008-02-02 10:12:36 +00004432 c = C()
4433 c[1:2] = 3
4434 self.assertEqual(c.value, 3)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004435
Benjamin Peterson273c2332008-11-17 22:39:09 +00004436 def test_getattr_hooks(self):
4437 # issue 4230
4438
4439 class Descriptor(object):
4440 counter = 0
4441 def __get__(self, obj, objtype=None):
4442 def getter(name):
4443 self.counter += 1
4444 raise AttributeError(name)
4445 return getter
4446
4447 descr = Descriptor()
4448 class A(object):
4449 __getattribute__ = descr
4450 class B(object):
4451 __getattr__ = descr
4452 class C(object):
4453 __getattribute__ = descr
4454 __getattr__ = descr
4455
4456 self.assertRaises(AttributeError, getattr, A(), "attr")
4457 self.assertEquals(descr.counter, 1)
4458 self.assertRaises(AttributeError, getattr, B(), "attr")
4459 self.assertEquals(descr.counter, 2)
4460 self.assertRaises(AttributeError, getattr, C(), "attr")
4461 self.assertEquals(descr.counter, 4)
4462
4463 import gc
4464 class EvilGetattribute(object):
4465 # This used to segfault
4466 def __getattr__(self, name):
4467 raise AttributeError(name)
4468 def __getattribute__(self, name):
4469 del EvilGetattribute.__getattr__
4470 for i in range(5):
4471 gc.collect()
4472 raise AttributeError(name)
4473
4474 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4475
Guido van Rossum9acc3872008-01-23 23:23:43 +00004476
Georg Brandl48545522008-02-02 10:12:36 +00004477class DictProxyTests(unittest.TestCase):
4478 def setUp(self):
4479 class C(object):
4480 def meth(self):
4481 pass
4482 self.C = C
Guido van Rossum9acc3872008-01-23 23:23:43 +00004483
Georg Brandl48545522008-02-02 10:12:36 +00004484 def test_iter_keys(self):
4485 # Testing dict-proxy iterkeys...
4486 keys = [ key for key in self.C.__dict__.iterkeys() ]
4487 keys.sort()
4488 self.assertEquals(keys, ['__dict__', '__doc__', '__module__',
4489 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004490
Georg Brandl48545522008-02-02 10:12:36 +00004491 def test_iter_values(self):
4492 # Testing dict-proxy itervalues...
4493 values = [ values for values in self.C.__dict__.itervalues() ]
4494 self.assertEqual(len(values), 5)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004495
Georg Brandl48545522008-02-02 10:12:36 +00004496 def test_iter_items(self):
4497 # Testing dict-proxy iteritems...
4498 keys = [ key for (key, value) in self.C.__dict__.iteritems() ]
4499 keys.sort()
4500 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4501 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004502
Georg Brandl48545522008-02-02 10:12:36 +00004503 def test_dict_type_with_metaclass(self):
4504 # Testing type of __dict__ when __metaclass__ set...
4505 class B(object):
4506 pass
4507 class M(type):
4508 pass
4509 class C:
4510 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4511 __metaclass__ = M
4512 self.assertEqual(type(C.__dict__), type(B.__dict__))
Guido van Rossum9acc3872008-01-23 23:23:43 +00004513
Guido van Rossum9acc3872008-01-23 23:23:43 +00004514
Georg Brandl48545522008-02-02 10:12:36 +00004515class PTypesLongInitTest(unittest.TestCase):
4516 # This is in its own TestCase so that it can be run before any other tests.
4517 def test_pytype_long_ready(self):
4518 # Testing SF bug 551412 ...
Guido van Rossum9acc3872008-01-23 23:23:43 +00004519
Georg Brandl48545522008-02-02 10:12:36 +00004520 # This dumps core when SF bug 551412 isn't fixed --
4521 # but only when test_descr.py is run separately.
4522 # (That can't be helped -- as soon as PyType_Ready()
4523 # is called for PyLong_Type, the bug is gone.)
4524 class UserLong(object):
4525 def __pow__(self, *args):
4526 pass
4527 try:
4528 pow(0L, UserLong(), 0L)
4529 except:
4530 pass
Guido van Rossum9acc3872008-01-23 23:23:43 +00004531
Georg Brandl48545522008-02-02 10:12:36 +00004532 # Another segfault only when run early
4533 # (before PyType_Ready(tuple) is called)
4534 type.mro(tuple)
Guido van Rossum37edeab2008-01-24 17:58:05 +00004535
4536
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004537def test_main():
Georg Brandl48545522008-02-02 10:12:36 +00004538 # Run all local test cases, with PTypesLongInitTest first.
4539 test_support.run_unittest(PTypesLongInitTest, OperatorsTest,
4540 ClassPropertiesAndMethods, DictProxyTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004541
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004542if __name__ == "__main__":
4543 test_main()