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