blob: 67e58ca1579ff65aad6b9b20333a2e4ba18c58a8 [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"
1147 with self.assertRaises(AttributeError):
1148 del X().a
1149
Georg Brandl48545522008-02-02 10:12:36 +00001150 def test_slots_special(self):
1151 # Testing __dict__ and __weakref__ in __slots__...
1152 class D(object):
1153 __slots__ = ["__dict__"]
1154 a = D()
1155 self.assert_(hasattr(a, "__dict__"))
1156 self.assertFalse(hasattr(a, "__weakref__"))
1157 a.foo = 42
1158 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001159
Georg Brandl48545522008-02-02 10:12:36 +00001160 class W(object):
1161 __slots__ = ["__weakref__"]
1162 a = W()
1163 self.assert_(hasattr(a, "__weakref__"))
1164 self.assertFalse(hasattr(a, "__dict__"))
1165 try:
1166 a.foo = 42
1167 except AttributeError:
1168 pass
1169 else:
1170 self.fail("shouldn't be allowed to set a.foo")
1171
1172 class C1(W, D):
1173 __slots__ = []
1174 a = C1()
1175 self.assert_(hasattr(a, "__dict__"))
1176 self.assert_(hasattr(a, "__weakref__"))
1177 a.foo = 42
1178 self.assertEqual(a.__dict__, {"foo": 42})
1179
1180 class C2(D, W):
1181 __slots__ = []
1182 a = C2()
1183 self.assert_(hasattr(a, "__dict__"))
1184 self.assert_(hasattr(a, "__weakref__"))
1185 a.foo = 42
1186 self.assertEqual(a.__dict__, {"foo": 42})
1187
Amaury Forgeot d'Arc60d6c7f2008-02-15 21:22:45 +00001188 def test_slots_descriptor(self):
1189 # Issue2115: slot descriptors did not correctly check
1190 # the type of the given object
1191 import abc
1192 class MyABC:
1193 __metaclass__ = abc.ABCMeta
1194 __slots__ = "a"
1195
1196 class Unrelated(object):
1197 pass
1198 MyABC.register(Unrelated)
1199
1200 u = Unrelated()
1201 self.assert_(isinstance(u, MyABC))
1202
1203 # This used to crash
1204 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1205
Benjamin Petersond76e7112009-12-13 16:41:44 +00001206 def test_metaclass_cmp(self):
1207 # See bug 7491.
1208 class M(type):
1209 def __cmp__(self, other):
1210 return -1
1211 class X(object):
1212 __metaclass__ = M
1213 self.assertTrue(X < M)
1214
Georg Brandl48545522008-02-02 10:12:36 +00001215 def test_dynamics(self):
1216 # Testing class attribute propagation...
1217 class D(object):
1218 pass
1219 class E(D):
1220 pass
1221 class F(D):
1222 pass
1223 D.foo = 1
1224 self.assertEqual(D.foo, 1)
1225 # Test that dynamic attributes are inherited
1226 self.assertEqual(E.foo, 1)
1227 self.assertEqual(F.foo, 1)
1228 # Test dynamic instances
1229 class C(object):
1230 pass
1231 a = C()
1232 self.assertFalse(hasattr(a, "foobar"))
1233 C.foobar = 2
1234 self.assertEqual(a.foobar, 2)
1235 C.method = lambda self: 42
1236 self.assertEqual(a.method(), 42)
1237 C.__repr__ = lambda self: "C()"
1238 self.assertEqual(repr(a), "C()")
1239 C.__int__ = lambda self: 100
1240 self.assertEqual(int(a), 100)
1241 self.assertEqual(a.foobar, 2)
1242 self.assertFalse(hasattr(a, "spam"))
1243 def mygetattr(self, name):
1244 if name == "spam":
1245 return "spam"
1246 raise AttributeError
1247 C.__getattr__ = mygetattr
1248 self.assertEqual(a.spam, "spam")
1249 a.new = 12
1250 self.assertEqual(a.new, 12)
1251 def mysetattr(self, name, value):
1252 if name == "spam":
1253 raise AttributeError
1254 return object.__setattr__(self, name, value)
1255 C.__setattr__ = mysetattr
1256 try:
1257 a.spam = "not spam"
1258 except AttributeError:
1259 pass
1260 else:
1261 self.fail("expected AttributeError")
1262 self.assertEqual(a.spam, "spam")
1263 class D(C):
1264 pass
1265 d = D()
1266 d.foo = 1
1267 self.assertEqual(d.foo, 1)
1268
1269 # Test handling of int*seq and seq*int
1270 class I(int):
1271 pass
1272 self.assertEqual("a"*I(2), "aa")
1273 self.assertEqual(I(2)*"a", "aa")
1274 self.assertEqual(2*I(3), 6)
1275 self.assertEqual(I(3)*2, 6)
1276 self.assertEqual(I(3)*I(2), 6)
1277
1278 # Test handling of long*seq and seq*long
1279 class L(long):
1280 pass
1281 self.assertEqual("a"*L(2L), "aa")
1282 self.assertEqual(L(2L)*"a", "aa")
1283 self.assertEqual(2*L(3), 6)
1284 self.assertEqual(L(3)*2, 6)
1285 self.assertEqual(L(3)*L(2), 6)
1286
1287 # Test comparison of classes with dynamic metaclasses
1288 class dynamicmetaclass(type):
1289 pass
1290 class someclass:
1291 __metaclass__ = dynamicmetaclass
1292 self.assertNotEqual(someclass, object)
1293
1294 def test_errors(self):
1295 # Testing errors...
1296 try:
1297 class C(list, dict):
1298 pass
1299 except TypeError:
1300 pass
1301 else:
1302 self.fail("inheritance from both list and dict should be illegal")
1303
1304 try:
1305 class C(object, None):
1306 pass
1307 except TypeError:
1308 pass
1309 else:
1310 self.fail("inheritance from non-type should be illegal")
1311 class Classic:
1312 pass
1313
1314 try:
1315 class C(type(len)):
1316 pass
1317 except TypeError:
1318 pass
1319 else:
1320 self.fail("inheritance from CFunction should be illegal")
1321
1322 try:
1323 class C(object):
1324 __slots__ = 1
1325 except TypeError:
1326 pass
1327 else:
1328 self.fail("__slots__ = 1 should be illegal")
1329
1330 try:
1331 class C(object):
1332 __slots__ = [1]
1333 except TypeError:
1334 pass
1335 else:
1336 self.fail("__slots__ = [1] should be illegal")
1337
1338 class M1(type):
1339 pass
1340 class M2(type):
1341 pass
1342 class A1(object):
1343 __metaclass__ = M1
1344 class A2(object):
1345 __metaclass__ = M2
1346 try:
1347 class B(A1, A2):
1348 pass
1349 except TypeError:
1350 pass
1351 else:
1352 self.fail("finding the most derived metaclass should have failed")
1353
1354 def test_classmethods(self):
1355 # Testing class methods...
1356 class C(object):
1357 def foo(*a): return a
1358 goo = classmethod(foo)
1359 c = C()
1360 self.assertEqual(C.goo(1), (C, 1))
1361 self.assertEqual(c.goo(1), (C, 1))
1362 self.assertEqual(c.foo(1), (c, 1))
1363 class D(C):
1364 pass
1365 d = D()
1366 self.assertEqual(D.goo(1), (D, 1))
1367 self.assertEqual(d.goo(1), (D, 1))
1368 self.assertEqual(d.foo(1), (d, 1))
1369 self.assertEqual(D.foo(d, 1), (d, 1))
1370 # Test for a specific crash (SF bug 528132)
1371 def f(cls, arg): return (cls, arg)
1372 ff = classmethod(f)
1373 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1374 self.assertEqual(ff.__get__(0)(42), (int, 42))
1375
1376 # Test super() with classmethods (SF bug 535444)
1377 self.assertEqual(C.goo.im_self, C)
1378 self.assertEqual(D.goo.im_self, D)
1379 self.assertEqual(super(D,D).goo.im_self, D)
1380 self.assertEqual(super(D,d).goo.im_self, D)
1381 self.assertEqual(super(D,D).goo(), (D,))
1382 self.assertEqual(super(D,d).goo(), (D,))
1383
1384 # Verify that argument is checked for callability (SF bug 753451)
1385 try:
1386 classmethod(1).__get__(1)
1387 except TypeError:
1388 pass
1389 else:
1390 self.fail("classmethod should check for callability")
1391
1392 # Verify that classmethod() doesn't allow keyword args
1393 try:
1394 classmethod(f, kw=1)
1395 except TypeError:
1396 pass
1397 else:
1398 self.fail("classmethod shouldn't accept keyword args")
1399
1400 def test_classmethods_in_c(self):
1401 # Testing C-based class methods...
1402 import xxsubtype as spam
1403 a = (1, 2, 3)
1404 d = {'abc': 123}
1405 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1406 self.assertEqual(x, spam.spamlist)
1407 self.assertEqual(a, a1)
1408 self.assertEqual(d, d1)
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
1414 def test_staticmethods(self):
1415 # Testing static methods...
1416 class C(object):
1417 def foo(*a): return a
1418 goo = staticmethod(foo)
1419 c = C()
1420 self.assertEqual(C.goo(1), (1,))
1421 self.assertEqual(c.goo(1), (1,))
1422 self.assertEqual(c.foo(1), (c, 1,))
1423 class D(C):
1424 pass
1425 d = D()
1426 self.assertEqual(D.goo(1), (1,))
1427 self.assertEqual(d.goo(1), (1,))
1428 self.assertEqual(d.foo(1), (d, 1))
1429 self.assertEqual(D.foo(d, 1), (d, 1))
1430
1431 def test_staticmethods_in_c(self):
1432 # Testing C-based static methods...
1433 import xxsubtype as spam
1434 a = (1, 2, 3)
1435 d = {"abc": 123}
1436 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1437 self.assertEqual(x, None)
1438 self.assertEqual(a, a1)
1439 self.assertEqual(d, d1)
1440 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1441 self.assertEqual(x, None)
1442 self.assertEqual(a, a1)
1443 self.assertEqual(d, d1)
1444
1445 def test_classic(self):
1446 # Testing classic classes...
1447 class C:
1448 def foo(*a): return a
1449 goo = classmethod(foo)
1450 c = C()
1451 self.assertEqual(C.goo(1), (C, 1))
1452 self.assertEqual(c.goo(1), (C, 1))
1453 self.assertEqual(c.foo(1), (c, 1))
1454 class D(C):
1455 pass
1456 d = D()
1457 self.assertEqual(D.goo(1), (D, 1))
1458 self.assertEqual(d.goo(1), (D, 1))
1459 self.assertEqual(d.foo(1), (d, 1))
1460 self.assertEqual(D.foo(d, 1), (d, 1))
1461 class E: # *not* subclassing from C
1462 foo = C.foo
1463 self.assertEqual(E().foo, C.foo) # i.e., unbound
1464 self.assert_(repr(C.foo.__get__(C())).startswith("<bound method "))
1465
1466 def test_compattr(self):
1467 # Testing computed attributes...
1468 class C(object):
1469 class computed_attribute(object):
1470 def __init__(self, get, set=None, delete=None):
1471 self.__get = get
1472 self.__set = set
1473 self.__delete = delete
1474 def __get__(self, obj, type=None):
1475 return self.__get(obj)
1476 def __set__(self, obj, value):
1477 return self.__set(obj, value)
1478 def __delete__(self, obj):
1479 return self.__delete(obj)
1480 def __init__(self):
1481 self.__x = 0
1482 def __get_x(self):
1483 x = self.__x
1484 self.__x = x+1
1485 return x
1486 def __set_x(self, x):
1487 self.__x = x
1488 def __delete_x(self):
1489 del self.__x
1490 x = computed_attribute(__get_x, __set_x, __delete_x)
1491 a = C()
1492 self.assertEqual(a.x, 0)
1493 self.assertEqual(a.x, 1)
1494 a.x = 10
1495 self.assertEqual(a.x, 10)
1496 self.assertEqual(a.x, 11)
1497 del a.x
1498 self.assertEqual(hasattr(a, 'x'), 0)
1499
1500 def test_newslots(self):
1501 # Testing __new__ slot override...
1502 class C(list):
1503 def __new__(cls):
1504 self = list.__new__(cls)
1505 self.foo = 1
1506 return self
1507 def __init__(self):
1508 self.foo = self.foo + 2
1509 a = C()
1510 self.assertEqual(a.foo, 3)
1511 self.assertEqual(a.__class__, C)
1512 class D(C):
1513 pass
1514 b = D()
1515 self.assertEqual(b.foo, 3)
1516 self.assertEqual(b.__class__, D)
1517
1518 def test_altmro(self):
1519 # Testing mro() and overriding it...
1520 class A(object):
1521 def f(self): return "A"
1522 class B(A):
1523 pass
1524 class C(A):
1525 def f(self): return "C"
1526 class D(B, C):
1527 pass
1528 self.assertEqual(D.mro(), [D, B, C, A, object])
1529 self.assertEqual(D.__mro__, (D, B, C, A, object))
1530 self.assertEqual(D().f(), "C")
1531
1532 class PerverseMetaType(type):
1533 def mro(cls):
1534 L = type.mro(cls)
1535 L.reverse()
1536 return L
1537 class X(D,B,C,A):
1538 __metaclass__ = PerverseMetaType
1539 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1540 self.assertEqual(X().f(), "A")
1541
1542 try:
1543 class X(object):
1544 class __metaclass__(type):
1545 def mro(self):
1546 return [self, dict, object]
1547 except TypeError:
1548 pass
1549 else:
1550 self.fail("devious mro() return not caught")
1551
1552 try:
1553 class X(object):
1554 class __metaclass__(type):
1555 def mro(self):
1556 return [1]
1557 except TypeError:
1558 pass
1559 else:
1560 self.fail("non-class mro() return not caught")
1561
1562 try:
1563 class X(object):
1564 class __metaclass__(type):
1565 def mro(self):
1566 return 1
1567 except TypeError:
1568 pass
1569 else:
1570 self.fail("non-sequence mro() return not caught")
1571
1572 def test_overloading(self):
1573 # Testing operator overloading...
1574
1575 class B(object):
1576 "Intermediate class because object doesn't have a __setattr__"
1577
1578 class C(B):
1579 def __getattr__(self, name):
1580 if name == "foo":
1581 return ("getattr", name)
1582 else:
1583 raise AttributeError
1584 def __setattr__(self, name, value):
1585 if name == "foo":
1586 self.setattr = (name, value)
1587 else:
1588 return B.__setattr__(self, name, value)
1589 def __delattr__(self, name):
1590 if name == "foo":
1591 self.delattr = name
1592 else:
1593 return B.__delattr__(self, name)
1594
1595 def __getitem__(self, key):
1596 return ("getitem", key)
1597 def __setitem__(self, key, value):
1598 self.setitem = (key, value)
1599 def __delitem__(self, key):
1600 self.delitem = key
1601
1602 def __getslice__(self, i, j):
1603 return ("getslice", i, j)
1604 def __setslice__(self, i, j, value):
1605 self.setslice = (i, j, value)
1606 def __delslice__(self, i, j):
1607 self.delslice = (i, j)
1608
1609 a = C()
1610 self.assertEqual(a.foo, ("getattr", "foo"))
1611 a.foo = 12
1612 self.assertEqual(a.setattr, ("foo", 12))
1613 del a.foo
1614 self.assertEqual(a.delattr, "foo")
1615
1616 self.assertEqual(a[12], ("getitem", 12))
1617 a[12] = 21
1618 self.assertEqual(a.setitem, (12, 21))
1619 del a[12]
1620 self.assertEqual(a.delitem, 12)
1621
1622 self.assertEqual(a[0:10], ("getslice", 0, 10))
1623 a[0:10] = "foo"
1624 self.assertEqual(a.setslice, (0, 10, "foo"))
1625 del a[0:10]
1626 self.assertEqual(a.delslice, (0, 10))
1627
1628 def test_methods(self):
1629 # Testing methods...
1630 class C(object):
1631 def __init__(self, x):
1632 self.x = x
1633 def foo(self):
1634 return self.x
1635 c1 = C(1)
1636 self.assertEqual(c1.foo(), 1)
1637 class D(C):
1638 boo = C.foo
1639 goo = c1.foo
1640 d2 = D(2)
1641 self.assertEqual(d2.foo(), 2)
1642 self.assertEqual(d2.boo(), 2)
1643 self.assertEqual(d2.goo(), 1)
1644 class E(object):
1645 foo = C.foo
1646 self.assertEqual(E().foo, C.foo) # i.e., unbound
1647 self.assert_(repr(C.foo.__get__(C(1))).startswith("<bound method "))
1648
1649 def test_specials(self):
1650 # Testing special operators...
1651 # Test operators like __hash__ for which a built-in default exists
1652
1653 # Test the default behavior for static classes
1654 class C(object):
1655 def __getitem__(self, i):
1656 if 0 <= i < 10: return i
1657 raise IndexError
1658 c1 = C()
1659 c2 = C()
1660 self.assert_(not not c1) # What?
1661 self.assertNotEqual(id(c1), id(c2))
1662 hash(c1)
1663 hash(c2)
1664 self.assertEqual(cmp(c1, c2), cmp(id(c1), id(c2)))
1665 self.assertEqual(c1, c1)
1666 self.assert_(c1 != c2)
1667 self.assert_(not c1 != c1)
1668 self.assert_(not c1 == c2)
1669 # Note that the module name appears in str/repr, and that varies
1670 # depending on whether this test is run standalone or from a framework.
1671 self.assert_(str(c1).find('C object at ') >= 0)
1672 self.assertEqual(str(c1), repr(c1))
1673 self.assert_(-1 not in c1)
1674 for i in range(10):
1675 self.assert_(i in c1)
1676 self.assertFalse(10 in c1)
1677 # Test the default behavior for dynamic classes
1678 class D(object):
1679 def __getitem__(self, i):
1680 if 0 <= i < 10: return i
1681 raise IndexError
1682 d1 = D()
1683 d2 = D()
1684 self.assert_(not not d1)
1685 self.assertNotEqual(id(d1), id(d2))
1686 hash(d1)
1687 hash(d2)
1688 self.assertEqual(cmp(d1, d2), cmp(id(d1), id(d2)))
1689 self.assertEqual(d1, d1)
1690 self.assertNotEqual(d1, d2)
1691 self.assert_(not d1 != d1)
1692 self.assert_(not d1 == d2)
1693 # Note that the module name appears in str/repr, and that varies
1694 # depending on whether this test is run standalone or from a framework.
1695 self.assert_(str(d1).find('D object at ') >= 0)
1696 self.assertEqual(str(d1), repr(d1))
1697 self.assert_(-1 not in d1)
1698 for i in range(10):
1699 self.assert_(i in d1)
1700 self.assertFalse(10 in d1)
1701 # Test overridden behavior for static classes
1702 class Proxy(object):
1703 def __init__(self, x):
1704 self.x = x
1705 def __nonzero__(self):
1706 return not not self.x
1707 def __hash__(self):
1708 return hash(self.x)
1709 def __eq__(self, other):
1710 return self.x == other
1711 def __ne__(self, other):
1712 return self.x != other
1713 def __cmp__(self, other):
1714 return cmp(self.x, other.x)
1715 def __str__(self):
1716 return "Proxy:%s" % self.x
1717 def __repr__(self):
1718 return "Proxy(%r)" % self.x
1719 def __contains__(self, value):
1720 return value in self.x
1721 p0 = Proxy(0)
1722 p1 = Proxy(1)
1723 p_1 = Proxy(-1)
1724 self.assertFalse(p0)
1725 self.assert_(not not p1)
1726 self.assertEqual(hash(p0), hash(0))
1727 self.assertEqual(p0, p0)
1728 self.assertNotEqual(p0, p1)
1729 self.assert_(not p0 != p0)
1730 self.assertEqual(not p0, p1)
1731 self.assertEqual(cmp(p0, p1), -1)
1732 self.assertEqual(cmp(p0, p0), 0)
1733 self.assertEqual(cmp(p0, p_1), 1)
1734 self.assertEqual(str(p0), "Proxy:0")
1735 self.assertEqual(repr(p0), "Proxy(0)")
1736 p10 = Proxy(range(10))
1737 self.assertFalse(-1 in p10)
1738 for i in range(10):
1739 self.assert_(i in p10)
1740 self.assertFalse(10 in p10)
1741 # Test overridden behavior for dynamic classes
1742 class DProxy(object):
1743 def __init__(self, x):
1744 self.x = x
1745 def __nonzero__(self):
1746 return not not self.x
1747 def __hash__(self):
1748 return hash(self.x)
1749 def __eq__(self, other):
1750 return self.x == other
1751 def __ne__(self, other):
1752 return self.x != other
1753 def __cmp__(self, other):
1754 return cmp(self.x, other.x)
1755 def __str__(self):
1756 return "DProxy:%s" % self.x
1757 def __repr__(self):
1758 return "DProxy(%r)" % self.x
1759 def __contains__(self, value):
1760 return value in self.x
1761 p0 = DProxy(0)
1762 p1 = DProxy(1)
1763 p_1 = DProxy(-1)
1764 self.assertFalse(p0)
1765 self.assert_(not not p1)
1766 self.assertEqual(hash(p0), hash(0))
1767 self.assertEqual(p0, p0)
1768 self.assertNotEqual(p0, p1)
1769 self.assertNotEqual(not p0, p0)
1770 self.assertEqual(not p0, p1)
1771 self.assertEqual(cmp(p0, p1), -1)
1772 self.assertEqual(cmp(p0, p0), 0)
1773 self.assertEqual(cmp(p0, p_1), 1)
1774 self.assertEqual(str(p0), "DProxy:0")
1775 self.assertEqual(repr(p0), "DProxy(0)")
1776 p10 = DProxy(range(10))
1777 self.assertFalse(-1 in p10)
1778 for i in range(10):
1779 self.assert_(i in p10)
1780 self.assertFalse(10 in p10)
1781
1782 # Safety test for __cmp__
1783 def unsafecmp(a, b):
Benjamin Peterson4b32dd72009-12-16 04:27:27 +00001784 if not hasattr(a.__class__, "__cmp__"):
1785 return
Georg Brandl48545522008-02-02 10:12:36 +00001786 try:
1787 a.__class__.__cmp__(a, b)
1788 except TypeError:
1789 pass
Guido van Rossum4bb1e362001-09-28 23:49:48 +00001790 else:
Georg Brandl48545522008-02-02 10:12:36 +00001791 self.fail("shouldn't allow %s.__cmp__(%r, %r)" % (
1792 a.__class__, a, b))
1793
1794 unsafecmp(u"123", "123")
1795 unsafecmp("123", u"123")
1796 unsafecmp(1, 1.0)
1797 unsafecmp(1.0, 1)
1798 unsafecmp(1, 1L)
1799 unsafecmp(1L, 1)
1800
1801 def test_recursions(self):
1802 # Testing recursion checks ...
1803 class Letter(str):
1804 def __new__(cls, letter):
1805 if letter == 'EPS':
1806 return str.__new__(cls)
1807 return str.__new__(cls, letter)
1808 def __str__(self):
1809 if not self:
1810 return 'EPS'
1811 return self
1812 # sys.stdout needs to be the original to trigger the recursion bug
1813 import sys
1814 test_stdout = sys.stdout
1815 sys.stdout = test_support.get_original_stdout()
1816 try:
1817 # nothing should actually be printed, this should raise an exception
1818 print Letter('w')
1819 except RuntimeError:
1820 pass
1821 else:
1822 self.fail("expected a RuntimeError for print recursion")
1823 finally:
1824 sys.stdout = test_stdout
1825
1826 # Bug #1202533.
1827 class A(object):
1828 pass
1829 A.__mul__ = types.MethodType(lambda self, x: self * x, None, A)
1830 try:
1831 A()*2
1832 except RuntimeError:
1833 pass
1834 else:
1835 self.fail("expected a RuntimeError")
1836
1837 def test_weakrefs(self):
1838 # Testing weak references...
1839 import weakref
1840 class C(object):
1841 pass
1842 c = C()
1843 r = weakref.ref(c)
1844 self.assertEqual(r(), c)
1845 del c
1846 self.assertEqual(r(), None)
1847 del r
1848 class NoWeak(object):
1849 __slots__ = ['foo']
1850 no = NoWeak()
1851 try:
1852 weakref.ref(no)
1853 except TypeError, msg:
1854 self.assert_(str(msg).find("weak reference") >= 0)
1855 else:
1856 self.fail("weakref.ref(no) should be illegal")
1857 class Weak(object):
1858 __slots__ = ['foo', '__weakref__']
1859 yes = Weak()
1860 r = weakref.ref(yes)
1861 self.assertEqual(r(), yes)
1862 del yes
1863 self.assertEqual(r(), None)
1864 del r
1865
1866 def test_properties(self):
1867 # Testing property...
1868 class C(object):
1869 def getx(self):
1870 return self.__x
1871 def setx(self, value):
1872 self.__x = value
1873 def delx(self):
1874 del self.__x
1875 x = property(getx, setx, delx, doc="I'm the x property.")
1876 a = C()
1877 self.assertFalse(hasattr(a, "x"))
1878 a.x = 42
1879 self.assertEqual(a._C__x, 42)
1880 self.assertEqual(a.x, 42)
1881 del a.x
1882 self.assertFalse(hasattr(a, "x"))
1883 self.assertFalse(hasattr(a, "_C__x"))
1884 C.x.__set__(a, 100)
1885 self.assertEqual(C.x.__get__(a), 100)
1886 C.x.__delete__(a)
1887 self.assertFalse(hasattr(a, "x"))
1888
1889 raw = C.__dict__['x']
1890 self.assert_(isinstance(raw, property))
1891
1892 attrs = dir(raw)
1893 self.assert_("__doc__" in attrs)
1894 self.assert_("fget" in attrs)
1895 self.assert_("fset" in attrs)
1896 self.assert_("fdel" in attrs)
1897
1898 self.assertEqual(raw.__doc__, "I'm the x property.")
1899 self.assert_(raw.fget is C.__dict__['getx'])
1900 self.assert_(raw.fset is C.__dict__['setx'])
1901 self.assert_(raw.fdel is C.__dict__['delx'])
1902
1903 for attr in "__doc__", "fget", "fset", "fdel":
1904 try:
1905 setattr(raw, attr, 42)
1906 except TypeError, msg:
1907 if str(msg).find('readonly') < 0:
1908 self.fail("when setting readonly attr %r on a property, "
1909 "got unexpected TypeError msg %r" % (attr, str(msg)))
Guido van Rossum4bb1e362001-09-28 23:49:48 +00001910 else:
Georg Brandl48545522008-02-02 10:12:36 +00001911 self.fail("expected TypeError from trying to set readonly %r "
1912 "attr on a property" % attr)
Tim Peters2f93e282001-10-04 05:27:00 +00001913
Georg Brandl48545522008-02-02 10:12:36 +00001914 class D(object):
1915 __getitem__ = property(lambda s: 1/0)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00001916
Georg Brandl48545522008-02-02 10:12:36 +00001917 d = D()
1918 try:
1919 for i in d:
1920 str(i)
1921 except ZeroDivisionError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00001922 pass
Georg Brandl48545522008-02-02 10:12:36 +00001923 else:
1924 self.fail("expected ZeroDivisionError from bad property")
Walter Dörwalddbd2d252002-03-25 18:36:32 +00001925
Georg Brandl48545522008-02-02 10:12:36 +00001926 class E(object):
1927 def getter(self):
1928 "getter method"
1929 return 0
1930 def setter(self_, value):
1931 "setter method"
1932 pass
1933 prop = property(getter)
1934 self.assertEqual(prop.__doc__, "getter method")
1935 prop2 = property(fset=setter)
1936 self.assertEqual(prop2.__doc__, None)
1937
1938 # this segfaulted in 2.5b2
1939 try:
1940 import _testcapi
1941 except ImportError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00001942 pass
Georg Brandl48545522008-02-02 10:12:36 +00001943 else:
1944 class X(object):
1945 p = property(_testcapi.test_with_docstring)
Walter Dörwalddbd2d252002-03-25 18:36:32 +00001946
Georg Brandl48545522008-02-02 10:12:36 +00001947 def test_properties_plus(self):
1948 class C(object):
1949 foo = property(doc="hello")
1950 @foo.getter
1951 def foo(self):
1952 return self._foo
1953 @foo.setter
1954 def foo(self, value):
1955 self._foo = abs(value)
1956 @foo.deleter
1957 def foo(self):
1958 del self._foo
1959 c = C()
1960 self.assertEqual(C.foo.__doc__, "hello")
1961 self.assertFalse(hasattr(c, "foo"))
1962 c.foo = -42
1963 self.assert_(hasattr(c, '_foo'))
1964 self.assertEqual(c._foo, 42)
1965 self.assertEqual(c.foo, 42)
1966 del c.foo
1967 self.assertFalse(hasattr(c, '_foo'))
1968 self.assertFalse(hasattr(c, "foo"))
Walter Dörwalddbd2d252002-03-25 18:36:32 +00001969
Georg Brandl48545522008-02-02 10:12:36 +00001970 class D(C):
1971 @C.foo.deleter
1972 def foo(self):
1973 try:
1974 del self._foo
1975 except AttributeError:
1976 pass
1977 d = D()
1978 d.foo = 24
1979 self.assertEqual(d.foo, 24)
1980 del d.foo
1981 del d.foo
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00001982
Georg Brandl48545522008-02-02 10:12:36 +00001983 class E(object):
1984 @property
1985 def foo(self):
1986 return self._foo
1987 @foo.setter
1988 def foo(self, value):
1989 raise RuntimeError
1990 @foo.setter
1991 def foo(self, value):
1992 self._foo = abs(value)
1993 @foo.deleter
1994 def foo(self, value=None):
1995 del self._foo
Guido van Rossume8fc6402002-04-16 16:44:51 +00001996
Georg Brandl48545522008-02-02 10:12:36 +00001997 e = E()
1998 e.foo = -42
1999 self.assertEqual(e.foo, 42)
2000 del e.foo
Guido van Rossumd99b3e72002-04-18 00:27:33 +00002001
Georg Brandl48545522008-02-02 10:12:36 +00002002 class F(E):
2003 @E.foo.deleter
2004 def foo(self):
2005 del self._foo
2006 @foo.setter
2007 def foo(self, value):
2008 self._foo = max(0, value)
2009 f = F()
2010 f.foo = -10
2011 self.assertEqual(f.foo, 0)
2012 del f.foo
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00002013
Georg Brandl48545522008-02-02 10:12:36 +00002014 def test_dict_constructors(self):
2015 # Testing dict constructor ...
2016 d = dict()
2017 self.assertEqual(d, {})
2018 d = dict({})
2019 self.assertEqual(d, {})
2020 d = dict({1: 2, 'a': 'b'})
2021 self.assertEqual(d, {1: 2, 'a': 'b'})
2022 self.assertEqual(d, dict(d.items()))
2023 self.assertEqual(d, dict(d.iteritems()))
2024 d = dict({'one':1, 'two':2})
2025 self.assertEqual(d, dict(one=1, two=2))
2026 self.assertEqual(d, dict(**d))
2027 self.assertEqual(d, dict({"one": 1}, two=2))
2028 self.assertEqual(d, dict([("two", 2)], one=1))
2029 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2030 self.assertEqual(d, dict(**d))
Guido van Rossum09638c12002-06-13 19:17:46 +00002031
Georg Brandl48545522008-02-02 10:12:36 +00002032 for badarg in 0, 0L, 0j, "0", [0], (0,):
2033 try:
2034 dict(badarg)
2035 except TypeError:
2036 pass
2037 except ValueError:
2038 if badarg == "0":
2039 # It's a sequence, and its elements are also sequences (gotta
2040 # love strings <wink>), but they aren't of length 2, so this
2041 # one seemed better as a ValueError than a TypeError.
2042 pass
2043 else:
2044 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002045 else:
Georg Brandl48545522008-02-02 10:12:36 +00002046 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002047
Georg Brandl48545522008-02-02 10:12:36 +00002048 try:
2049 dict({}, {})
2050 except TypeError:
2051 pass
2052 else:
2053 self.fail("no TypeError from dict({}, {})")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002054
Georg Brandl48545522008-02-02 10:12:36 +00002055 class Mapping:
2056 # Lacks a .keys() method; will be added later.
2057 dict = {1:2, 3:4, 'a':1j}
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002058
Georg Brandl48545522008-02-02 10:12:36 +00002059 try:
2060 dict(Mapping())
2061 except TypeError:
2062 pass
2063 else:
2064 self.fail("no TypeError from dict(incomplete mapping)")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002065
Georg Brandl48545522008-02-02 10:12:36 +00002066 Mapping.keys = lambda self: self.dict.keys()
2067 Mapping.__getitem__ = lambda self, i: self.dict[i]
2068 d = dict(Mapping())
2069 self.assertEqual(d, Mapping.dict)
Michael W. Hudsonf3904422006-11-23 13:54:04 +00002070
Georg Brandl48545522008-02-02 10:12:36 +00002071 # Init from sequence of iterable objects, each producing a 2-sequence.
2072 class AddressBookEntry:
2073 def __init__(self, first, last):
2074 self.first = first
2075 self.last = last
2076 def __iter__(self):
2077 return iter([self.first, self.last])
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002078
Georg Brandl48545522008-02-02 10:12:36 +00002079 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2080 AddressBookEntry('Barry', 'Peters'),
2081 AddressBookEntry('Tim', 'Peters'),
2082 AddressBookEntry('Barry', 'Warsaw')])
2083 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00002084
Georg Brandl48545522008-02-02 10:12:36 +00002085 d = dict(zip(range(4), range(1, 5)))
2086 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002087
Georg Brandl48545522008-02-02 10:12:36 +00002088 # Bad sequence lengths.
2089 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2090 try:
2091 dict(bad)
2092 except ValueError:
2093 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00002094 else:
Georg Brandl48545522008-02-02 10:12:36 +00002095 self.fail("no ValueError from dict(%r)" % bad)
2096
2097 def test_dir(self):
2098 # Testing dir() ...
2099 junk = 12
2100 self.assertEqual(dir(), ['junk', 'self'])
2101 del junk
2102
2103 # Just make sure these don't blow up!
2104 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, self.test_dir:
2105 dir(arg)
2106
2107 # Try classic classes.
2108 class C:
2109 Cdata = 1
2110 def Cmethod(self): pass
2111
2112 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
2113 self.assertEqual(dir(C), cstuff)
2114 self.assert_('im_self' in dir(C.Cmethod))
2115
2116 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
2117 self.assertEqual(dir(c), cstuff)
2118
2119 c.cdata = 2
2120 c.cmethod = lambda self: 0
2121 self.assertEqual(dir(c), cstuff + ['cdata', 'cmethod'])
2122 self.assert_('im_self' in dir(c.Cmethod))
2123
2124 class A(C):
2125 Adata = 1
2126 def Amethod(self): pass
2127
2128 astuff = ['Adata', 'Amethod'] + cstuff
2129 self.assertEqual(dir(A), astuff)
2130 self.assert_('im_self' in dir(A.Amethod))
2131 a = A()
2132 self.assertEqual(dir(a), astuff)
2133 self.assert_('im_self' in dir(a.Amethod))
2134 a.adata = 42
2135 a.amethod = lambda self: 3
2136 self.assertEqual(dir(a), astuff + ['adata', 'amethod'])
2137
2138 # The same, but with new-style classes. Since these have object as a
2139 # base class, a lot more gets sucked in.
2140 def interesting(strings):
2141 return [s for s in strings if not s.startswith('_')]
2142
2143 class C(object):
2144 Cdata = 1
2145 def Cmethod(self): pass
2146
2147 cstuff = ['Cdata', 'Cmethod']
2148 self.assertEqual(interesting(dir(C)), cstuff)
2149
2150 c = C()
2151 self.assertEqual(interesting(dir(c)), cstuff)
2152 self.assert_('im_self' in dir(C.Cmethod))
2153
2154 c.cdata = 2
2155 c.cmethod = lambda self: 0
2156 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
2157 self.assert_('im_self' in dir(c.Cmethod))
2158
2159 class A(C):
2160 Adata = 1
2161 def Amethod(self): pass
2162
2163 astuff = ['Adata', 'Amethod'] + cstuff
2164 self.assertEqual(interesting(dir(A)), astuff)
2165 self.assert_('im_self' in dir(A.Amethod))
2166 a = A()
2167 self.assertEqual(interesting(dir(a)), astuff)
2168 a.adata = 42
2169 a.amethod = lambda self: 3
2170 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
2171 self.assert_('im_self' in dir(a.Amethod))
2172
2173 # Try a module subclass.
2174 import sys
2175 class M(type(sys)):
2176 pass
2177 minstance = M("m")
2178 minstance.b = 2
2179 minstance.a = 1
2180 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2181 self.assertEqual(names, ['a', 'b'])
2182
2183 class M2(M):
2184 def getdict(self):
2185 return "Not a dict!"
2186 __dict__ = property(getdict)
2187
2188 m2instance = M2("m2")
2189 m2instance.b = 2
2190 m2instance.a = 1
2191 self.assertEqual(m2instance.__dict__, "Not a dict!")
2192 try:
2193 dir(m2instance)
2194 except TypeError:
2195 pass
2196
2197 # Two essentially featureless objects, just inheriting stuff from
2198 # object.
2199 self.assertEqual(dir(None), dir(Ellipsis))
2200
2201 # Nasty test case for proxied objects
2202 class Wrapper(object):
2203 def __init__(self, obj):
2204 self.__obj = obj
2205 def __repr__(self):
2206 return "Wrapper(%s)" % repr(self.__obj)
2207 def __getitem__(self, key):
2208 return Wrapper(self.__obj[key])
2209 def __len__(self):
2210 return len(self.__obj)
2211 def __getattr__(self, name):
2212 return Wrapper(getattr(self.__obj, name))
2213
2214 class C(object):
2215 def __getclass(self):
2216 return Wrapper(type(self))
2217 __class__ = property(__getclass)
2218
2219 dir(C()) # This used to segfault
2220
2221 def test_supers(self):
2222 # Testing super...
2223
2224 class A(object):
2225 def meth(self, a):
2226 return "A(%r)" % a
2227
2228 self.assertEqual(A().meth(1), "A(1)")
2229
2230 class B(A):
2231 def __init__(self):
2232 self.__super = super(B, self)
2233 def meth(self, a):
2234 return "B(%r)" % a + self.__super.meth(a)
2235
2236 self.assertEqual(B().meth(2), "B(2)A(2)")
2237
2238 class C(A):
2239 def meth(self, a):
2240 return "C(%r)" % a + self.__super.meth(a)
2241 C._C__super = super(C)
2242
2243 self.assertEqual(C().meth(3), "C(3)A(3)")
2244
2245 class D(C, B):
2246 def meth(self, a):
2247 return "D(%r)" % a + super(D, self).meth(a)
2248
2249 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2250
2251 # Test for subclassing super
2252
2253 class mysuper(super):
2254 def __init__(self, *args):
2255 return super(mysuper, self).__init__(*args)
2256
2257 class E(D):
2258 def meth(self, a):
2259 return "E(%r)" % a + mysuper(E, self).meth(a)
2260
2261 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2262
2263 class F(E):
2264 def meth(self, a):
2265 s = self.__super # == mysuper(F, self)
2266 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2267 F._F__super = mysuper(F)
2268
2269 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2270
2271 # Make sure certain errors are raised
2272
2273 try:
2274 super(D, 42)
2275 except TypeError:
2276 pass
2277 else:
2278 self.fail("shouldn't allow super(D, 42)")
2279
2280 try:
2281 super(D, C())
2282 except TypeError:
2283 pass
2284 else:
2285 self.fail("shouldn't allow super(D, C())")
2286
2287 try:
2288 super(D).__get__(12)
2289 except TypeError:
2290 pass
2291 else:
2292 self.fail("shouldn't allow super(D).__get__(12)")
2293
2294 try:
2295 super(D).__get__(C())
2296 except TypeError:
2297 pass
2298 else:
2299 self.fail("shouldn't allow super(D).__get__(C())")
2300
2301 # Make sure data descriptors can be overridden and accessed via super
2302 # (new feature in Python 2.3)
2303
2304 class DDbase(object):
2305 def getx(self): return 42
2306 x = property(getx)
2307
2308 class DDsub(DDbase):
2309 def getx(self): return "hello"
2310 x = property(getx)
2311
2312 dd = DDsub()
2313 self.assertEqual(dd.x, "hello")
2314 self.assertEqual(super(DDsub, dd).x, 42)
2315
2316 # Ensure that super() lookup of descriptor from classmethod
2317 # works (SF ID# 743627)
2318
2319 class Base(object):
2320 aProp = property(lambda self: "foo")
2321
2322 class Sub(Base):
2323 @classmethod
2324 def test(klass):
2325 return super(Sub,klass).aProp
2326
2327 self.assertEqual(Sub.test(), Base.aProp)
2328
2329 # Verify that super() doesn't allow keyword args
2330 try:
2331 super(Base, kw=1)
2332 except TypeError:
2333 pass
2334 else:
2335 self.assertEqual("super shouldn't accept keyword args")
2336
2337 def test_basic_inheritance(self):
2338 # Testing inheritance from basic types...
2339
2340 class hexint(int):
2341 def __repr__(self):
2342 return hex(self)
2343 def __add__(self, other):
2344 return hexint(int.__add__(self, other))
2345 # (Note that overriding __radd__ doesn't work,
2346 # because the int type gets first dibs.)
2347 self.assertEqual(repr(hexint(7) + 9), "0x10")
2348 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2349 a = hexint(12345)
2350 self.assertEqual(a, 12345)
2351 self.assertEqual(int(a), 12345)
2352 self.assert_(int(a).__class__ is int)
2353 self.assertEqual(hash(a), hash(12345))
2354 self.assert_((+a).__class__ is int)
2355 self.assert_((a >> 0).__class__ is int)
2356 self.assert_((a << 0).__class__ is int)
2357 self.assert_((hexint(0) << 12).__class__ is int)
2358 self.assert_((hexint(0) >> 12).__class__ is int)
2359
2360 class octlong(long):
2361 __slots__ = []
2362 def __str__(self):
2363 s = oct(self)
2364 if s[-1] == 'L':
2365 s = s[:-1]
2366 return s
2367 def __add__(self, other):
2368 return self.__class__(super(octlong, self).__add__(other))
2369 __radd__ = __add__
2370 self.assertEqual(str(octlong(3) + 5), "010")
2371 # (Note that overriding __radd__ here only seems to work
2372 # because the example uses a short int left argument.)
2373 self.assertEqual(str(5 + octlong(3000)), "05675")
2374 a = octlong(12345)
2375 self.assertEqual(a, 12345L)
2376 self.assertEqual(long(a), 12345L)
2377 self.assertEqual(hash(a), hash(12345L))
2378 self.assert_(long(a).__class__ is long)
2379 self.assert_((+a).__class__ is long)
2380 self.assert_((-a).__class__ is long)
2381 self.assert_((-octlong(0)).__class__ is long)
2382 self.assert_((a >> 0).__class__ is long)
2383 self.assert_((a << 0).__class__ is long)
2384 self.assert_((a - 0).__class__ is long)
2385 self.assert_((a * 1).__class__ is long)
2386 self.assert_((a ** 1).__class__ is long)
2387 self.assert_((a // 1).__class__ is long)
2388 self.assert_((1 * a).__class__ is long)
2389 self.assert_((a | 0).__class__ is long)
2390 self.assert_((a ^ 0).__class__ is long)
2391 self.assert_((a & -1L).__class__ is long)
2392 self.assert_((octlong(0) << 12).__class__ is long)
2393 self.assert_((octlong(0) >> 12).__class__ is long)
2394 self.assert_(abs(octlong(0)).__class__ is long)
2395
2396 # Because octlong overrides __add__, we can't check the absence of +0
2397 # optimizations using octlong.
2398 class longclone(long):
2399 pass
2400 a = longclone(1)
2401 self.assert_((a + 0).__class__ is long)
2402 self.assert_((0 + a).__class__ is long)
2403
2404 # Check that negative clones don't segfault
2405 a = longclone(-1)
2406 self.assertEqual(a.__dict__, {})
2407 self.assertEqual(long(a), -1) # self.assert_ PyNumber_Long() copies the sign bit
2408
2409 class precfloat(float):
2410 __slots__ = ['prec']
2411 def __init__(self, value=0.0, prec=12):
2412 self.prec = int(prec)
2413 def __repr__(self):
2414 return "%.*g" % (self.prec, self)
2415 self.assertEqual(repr(precfloat(1.1)), "1.1")
2416 a = precfloat(12345)
2417 self.assertEqual(a, 12345.0)
2418 self.assertEqual(float(a), 12345.0)
2419 self.assert_(float(a).__class__ is float)
2420 self.assertEqual(hash(a), hash(12345.0))
2421 self.assert_((+a).__class__ is float)
2422
2423 class madcomplex(complex):
2424 def __repr__(self):
2425 return "%.17gj%+.17g" % (self.imag, self.real)
2426 a = madcomplex(-3, 4)
2427 self.assertEqual(repr(a), "4j-3")
2428 base = complex(-3, 4)
2429 self.assertEqual(base.__class__, complex)
2430 self.assertEqual(a, base)
2431 self.assertEqual(complex(a), base)
2432 self.assertEqual(complex(a).__class__, complex)
2433 a = madcomplex(a) # just trying another form of the constructor
2434 self.assertEqual(repr(a), "4j-3")
2435 self.assertEqual(a, base)
2436 self.assertEqual(complex(a), base)
2437 self.assertEqual(complex(a).__class__, complex)
2438 self.assertEqual(hash(a), hash(base))
2439 self.assertEqual((+a).__class__, complex)
2440 self.assertEqual((a + 0).__class__, complex)
2441 self.assertEqual(a + 0, base)
2442 self.assertEqual((a - 0).__class__, complex)
2443 self.assertEqual(a - 0, base)
2444 self.assertEqual((a * 1).__class__, complex)
2445 self.assertEqual(a * 1, base)
2446 self.assertEqual((a / 1).__class__, complex)
2447 self.assertEqual(a / 1, base)
2448
2449 class madtuple(tuple):
2450 _rev = None
2451 def rev(self):
2452 if self._rev is not None:
2453 return self._rev
2454 L = list(self)
2455 L.reverse()
2456 self._rev = self.__class__(L)
2457 return self._rev
2458 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2459 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2460 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2461 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2462 for i in range(512):
2463 t = madtuple(range(i))
2464 u = t.rev()
2465 v = u.rev()
2466 self.assertEqual(v, t)
2467 a = madtuple((1,2,3,4,5))
2468 self.assertEqual(tuple(a), (1,2,3,4,5))
2469 self.assert_(tuple(a).__class__ is tuple)
2470 self.assertEqual(hash(a), hash((1,2,3,4,5)))
2471 self.assert_(a[:].__class__ is tuple)
2472 self.assert_((a * 1).__class__ is tuple)
2473 self.assert_((a * 0).__class__ is tuple)
2474 self.assert_((a + ()).__class__ is tuple)
2475 a = madtuple(())
2476 self.assertEqual(tuple(a), ())
2477 self.assert_(tuple(a).__class__ is tuple)
2478 self.assert_((a + a).__class__ is tuple)
2479 self.assert_((a * 0).__class__ is tuple)
2480 self.assert_((a * 1).__class__ is tuple)
2481 self.assert_((a * 2).__class__ is tuple)
2482 self.assert_(a[:].__class__ is tuple)
2483
2484 class madstring(str):
2485 _rev = None
2486 def rev(self):
2487 if self._rev is not None:
2488 return self._rev
2489 L = list(self)
2490 L.reverse()
2491 self._rev = self.__class__("".join(L))
2492 return self._rev
2493 s = madstring("abcdefghijklmnopqrstuvwxyz")
2494 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2495 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2496 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2497 for i in range(256):
2498 s = madstring("".join(map(chr, range(i))))
2499 t = s.rev()
2500 u = t.rev()
2501 self.assertEqual(u, s)
2502 s = madstring("12345")
2503 self.assertEqual(str(s), "12345")
2504 self.assert_(str(s).__class__ is str)
2505
2506 base = "\x00" * 5
2507 s = madstring(base)
2508 self.assertEqual(s, base)
2509 self.assertEqual(str(s), base)
2510 self.assert_(str(s).__class__ is str)
2511 self.assertEqual(hash(s), hash(base))
2512 self.assertEqual({s: 1}[base], 1)
2513 self.assertEqual({base: 1}[s], 1)
2514 self.assert_((s + "").__class__ is str)
2515 self.assertEqual(s + "", base)
2516 self.assert_(("" + s).__class__ is str)
2517 self.assertEqual("" + s, base)
2518 self.assert_((s * 0).__class__ is str)
2519 self.assertEqual(s * 0, "")
2520 self.assert_((s * 1).__class__ is str)
2521 self.assertEqual(s * 1, base)
2522 self.assert_((s * 2).__class__ is str)
2523 self.assertEqual(s * 2, base + base)
2524 self.assert_(s[:].__class__ is str)
2525 self.assertEqual(s[:], base)
2526 self.assert_(s[0:0].__class__ is str)
2527 self.assertEqual(s[0:0], "")
2528 self.assert_(s.strip().__class__ is str)
2529 self.assertEqual(s.strip(), base)
2530 self.assert_(s.lstrip().__class__ is str)
2531 self.assertEqual(s.lstrip(), base)
2532 self.assert_(s.rstrip().__class__ is str)
2533 self.assertEqual(s.rstrip(), base)
2534 identitytab = ''.join([chr(i) for i in range(256)])
2535 self.assert_(s.translate(identitytab).__class__ is str)
2536 self.assertEqual(s.translate(identitytab), base)
2537 self.assert_(s.translate(identitytab, "x").__class__ is str)
2538 self.assertEqual(s.translate(identitytab, "x"), base)
2539 self.assertEqual(s.translate(identitytab, "\x00"), "")
2540 self.assert_(s.replace("x", "x").__class__ is str)
2541 self.assertEqual(s.replace("x", "x"), base)
2542 self.assert_(s.ljust(len(s)).__class__ is str)
2543 self.assertEqual(s.ljust(len(s)), base)
2544 self.assert_(s.rjust(len(s)).__class__ is str)
2545 self.assertEqual(s.rjust(len(s)), base)
2546 self.assert_(s.center(len(s)).__class__ is str)
2547 self.assertEqual(s.center(len(s)), base)
2548 self.assert_(s.lower().__class__ is str)
2549 self.assertEqual(s.lower(), base)
2550
2551 class madunicode(unicode):
2552 _rev = None
2553 def rev(self):
2554 if self._rev is not None:
2555 return self._rev
2556 L = list(self)
2557 L.reverse()
2558 self._rev = self.__class__(u"".join(L))
2559 return self._rev
2560 u = madunicode("ABCDEF")
2561 self.assertEqual(u, u"ABCDEF")
2562 self.assertEqual(u.rev(), madunicode(u"FEDCBA"))
2563 self.assertEqual(u.rev().rev(), madunicode(u"ABCDEF"))
2564 base = u"12345"
2565 u = madunicode(base)
2566 self.assertEqual(unicode(u), base)
2567 self.assert_(unicode(u).__class__ is unicode)
2568 self.assertEqual(hash(u), hash(base))
2569 self.assertEqual({u: 1}[base], 1)
2570 self.assertEqual({base: 1}[u], 1)
2571 self.assert_(u.strip().__class__ is unicode)
2572 self.assertEqual(u.strip(), base)
2573 self.assert_(u.lstrip().__class__ is unicode)
2574 self.assertEqual(u.lstrip(), base)
2575 self.assert_(u.rstrip().__class__ is unicode)
2576 self.assertEqual(u.rstrip(), base)
2577 self.assert_(u.replace(u"x", u"x").__class__ is unicode)
2578 self.assertEqual(u.replace(u"x", u"x"), base)
2579 self.assert_(u.replace(u"xy", u"xy").__class__ is unicode)
2580 self.assertEqual(u.replace(u"xy", u"xy"), base)
2581 self.assert_(u.center(len(u)).__class__ is unicode)
2582 self.assertEqual(u.center(len(u)), base)
2583 self.assert_(u.ljust(len(u)).__class__ is unicode)
2584 self.assertEqual(u.ljust(len(u)), base)
2585 self.assert_(u.rjust(len(u)).__class__ is unicode)
2586 self.assertEqual(u.rjust(len(u)), base)
2587 self.assert_(u.lower().__class__ is unicode)
2588 self.assertEqual(u.lower(), base)
2589 self.assert_(u.upper().__class__ is unicode)
2590 self.assertEqual(u.upper(), base)
2591 self.assert_(u.capitalize().__class__ is unicode)
2592 self.assertEqual(u.capitalize(), base)
2593 self.assert_(u.title().__class__ is unicode)
2594 self.assertEqual(u.title(), base)
2595 self.assert_((u + u"").__class__ is unicode)
2596 self.assertEqual(u + u"", base)
2597 self.assert_((u"" + u).__class__ is unicode)
2598 self.assertEqual(u"" + u, base)
2599 self.assert_((u * 0).__class__ is unicode)
2600 self.assertEqual(u * 0, u"")
2601 self.assert_((u * 1).__class__ is unicode)
2602 self.assertEqual(u * 1, base)
2603 self.assert_((u * 2).__class__ is unicode)
2604 self.assertEqual(u * 2, base + base)
2605 self.assert_(u[:].__class__ is unicode)
2606 self.assertEqual(u[:], base)
2607 self.assert_(u[0:0].__class__ is unicode)
2608 self.assertEqual(u[0:0], u"")
2609
2610 class sublist(list):
2611 pass
2612 a = sublist(range(5))
2613 self.assertEqual(a, range(5))
2614 a.append("hello")
2615 self.assertEqual(a, range(5) + ["hello"])
2616 a[5] = 5
2617 self.assertEqual(a, range(6))
2618 a.extend(range(6, 20))
2619 self.assertEqual(a, range(20))
2620 a[-5:] = []
2621 self.assertEqual(a, range(15))
2622 del a[10:15]
2623 self.assertEqual(len(a), 10)
2624 self.assertEqual(a, range(10))
2625 self.assertEqual(list(a), range(10))
2626 self.assertEqual(a[0], 0)
2627 self.assertEqual(a[9], 9)
2628 self.assertEqual(a[-10], 0)
2629 self.assertEqual(a[-1], 9)
2630 self.assertEqual(a[:5], range(5))
2631
2632 class CountedInput(file):
2633 """Counts lines read by self.readline().
2634
2635 self.lineno is the 0-based ordinal of the last line read, up to
2636 a maximum of one greater than the number of lines in the file.
2637
2638 self.ateof is true if and only if the final "" line has been read,
2639 at which point self.lineno stops incrementing, and further calls
2640 to readline() continue to return "".
2641 """
2642
2643 lineno = 0
2644 ateof = 0
2645 def readline(self):
2646 if self.ateof:
2647 return ""
2648 s = file.readline(self)
2649 # Next line works too.
2650 # s = super(CountedInput, self).readline()
2651 self.lineno += 1
2652 if s == "":
2653 self.ateof = 1
2654 return s
2655
2656 f = file(name=test_support.TESTFN, mode='w')
2657 lines = ['a\n', 'b\n', 'c\n']
2658 try:
2659 f.writelines(lines)
2660 f.close()
2661 f = CountedInput(test_support.TESTFN)
2662 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2663 got = f.readline()
2664 self.assertEqual(expected, got)
2665 self.assertEqual(f.lineno, i)
2666 self.assertEqual(f.ateof, (i > len(lines)))
2667 f.close()
2668 finally:
2669 try:
2670 f.close()
2671 except:
2672 pass
2673 test_support.unlink(test_support.TESTFN)
2674
2675 def test_keywords(self):
2676 # Testing keyword args to basic type constructors ...
2677 self.assertEqual(int(x=1), 1)
2678 self.assertEqual(float(x=2), 2.0)
2679 self.assertEqual(long(x=3), 3L)
2680 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2681 self.assertEqual(str(object=500), '500')
2682 self.assertEqual(unicode(string='abc', errors='strict'), u'abc')
2683 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2684 self.assertEqual(list(sequence=(0, 1, 2)), range(3))
2685 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2686
2687 for constructor in (int, float, long, complex, str, unicode,
2688 tuple, list, file):
2689 try:
2690 constructor(bogus_keyword_arg=1)
2691 except TypeError:
2692 pass
2693 else:
2694 self.fail("expected TypeError from bogus keyword argument to %r"
2695 % constructor)
2696
2697 def test_str_subclass_as_dict_key(self):
2698 # Testing a str subclass used as dict key ..
2699
2700 class cistr(str):
2701 """Sublcass of str that computes __eq__ case-insensitively.
2702
2703 Also computes a hash code of the string in canonical form.
2704 """
2705
2706 def __init__(self, value):
2707 self.canonical = value.lower()
2708 self.hashcode = hash(self.canonical)
2709
2710 def __eq__(self, other):
2711 if not isinstance(other, cistr):
2712 other = cistr(other)
2713 return self.canonical == other.canonical
2714
2715 def __hash__(self):
2716 return self.hashcode
2717
2718 self.assertEqual(cistr('ABC'), 'abc')
2719 self.assertEqual('aBc', cistr('ABC'))
2720 self.assertEqual(str(cistr('ABC')), 'ABC')
2721
2722 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2723 self.assertEqual(d[cistr('one')], 1)
2724 self.assertEqual(d[cistr('tWo')], 2)
2725 self.assertEqual(d[cistr('THrEE')], 3)
2726 self.assert_(cistr('ONe') in d)
2727 self.assertEqual(d.get(cistr('thrEE')), 3)
2728
2729 def test_classic_comparisons(self):
2730 # Testing classic comparisons...
2731 class classic:
2732 pass
2733
2734 for base in (classic, int, object):
2735 class C(base):
2736 def __init__(self, value):
2737 self.value = int(value)
2738 def __cmp__(self, other):
2739 if isinstance(other, C):
2740 return cmp(self.value, other.value)
2741 if isinstance(other, int) or isinstance(other, long):
2742 return cmp(self.value, other)
2743 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00002744 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002745
2746 c1 = C(1)
2747 c2 = C(2)
2748 c3 = C(3)
2749 self.assertEqual(c1, 1)
2750 c = {1: c1, 2: c2, 3: c3}
2751 for x in 1, 2, 3:
2752 for y in 1, 2, 3:
2753 self.assert_(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2754 for op in "<", "<=", "==", "!=", ">", ">=":
2755 self.assert_(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2756 "x=%d, y=%d" % (x, y))
2757 self.assert_(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2758 self.assert_(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2759
2760 def test_rich_comparisons(self):
2761 # Testing rich comparisons...
2762 class Z(complex):
2763 pass
2764 z = Z(1)
2765 self.assertEqual(z, 1+0j)
2766 self.assertEqual(1+0j, z)
2767 class ZZ(complex):
2768 def __eq__(self, other):
2769 try:
2770 return abs(self - other) <= 1e-6
2771 except:
2772 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00002773 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002774 zz = ZZ(1.0000003)
2775 self.assertEqual(zz, 1+0j)
2776 self.assertEqual(1+0j, zz)
2777
2778 class classic:
2779 pass
2780 for base in (classic, int, object, list):
2781 class C(base):
2782 def __init__(self, value):
2783 self.value = int(value)
2784 def __cmp__(self_, other):
2785 self.fail("shouldn't call __cmp__")
Nick Coghlan48361f52008-08-11 15:45:58 +00002786 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002787 def __eq__(self, other):
2788 if isinstance(other, C):
2789 return self.value == other.value
2790 if isinstance(other, int) or isinstance(other, long):
2791 return self.value == other
2792 return NotImplemented
2793 def __ne__(self, other):
2794 if isinstance(other, C):
2795 return self.value != other.value
2796 if isinstance(other, int) or isinstance(other, long):
2797 return self.value != other
2798 return NotImplemented
2799 def __lt__(self, other):
2800 if isinstance(other, C):
2801 return self.value < other.value
2802 if isinstance(other, int) or isinstance(other, long):
2803 return self.value < other
2804 return NotImplemented
2805 def __le__(self, other):
2806 if isinstance(other, C):
2807 return self.value <= other.value
2808 if isinstance(other, int) or isinstance(other, long):
2809 return self.value <= other
2810 return NotImplemented
2811 def __gt__(self, other):
2812 if isinstance(other, C):
2813 return self.value > other.value
2814 if isinstance(other, int) or isinstance(other, long):
2815 return self.value > other
2816 return NotImplemented
2817 def __ge__(self, other):
2818 if isinstance(other, C):
2819 return self.value >= other.value
2820 if isinstance(other, int) or isinstance(other, long):
2821 return self.value >= other
2822 return NotImplemented
2823 c1 = C(1)
2824 c2 = C(2)
2825 c3 = C(3)
2826 self.assertEqual(c1, 1)
2827 c = {1: c1, 2: c2, 3: c3}
2828 for x in 1, 2, 3:
2829 for y in 1, 2, 3:
2830 for op in "<", "<=", "==", "!=", ">", ">=":
2831 self.assert_(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2832 "x=%d, y=%d" % (x, y))
2833 self.assert_(eval("c[x] %s y" % op) == eval("x %s y" % op),
2834 "x=%d, y=%d" % (x, y))
2835 self.assert_(eval("x %s c[y]" % op) == eval("x %s y" % op),
2836 "x=%d, y=%d" % (x, y))
2837
2838 def test_coercions(self):
2839 # Testing coercions...
2840 class I(int): pass
2841 coerce(I(0), 0)
2842 coerce(0, I(0))
2843 class L(long): pass
2844 coerce(L(0), 0)
2845 coerce(L(0), 0L)
2846 coerce(0, L(0))
2847 coerce(0L, L(0))
2848 class F(float): pass
2849 coerce(F(0), 0)
2850 coerce(F(0), 0L)
2851 coerce(F(0), 0.)
2852 coerce(0, F(0))
2853 coerce(0L, F(0))
2854 coerce(0., F(0))
2855 class C(complex): pass
2856 coerce(C(0), 0)
2857 coerce(C(0), 0L)
2858 coerce(C(0), 0.)
2859 coerce(C(0), 0j)
2860 coerce(0, C(0))
2861 coerce(0L, C(0))
2862 coerce(0., C(0))
2863 coerce(0j, C(0))
2864
2865 def test_descrdoc(self):
2866 # Testing descriptor doc strings...
2867 def check(descr, what):
2868 self.assertEqual(descr.__doc__, what)
2869 check(file.closed, "True if the file is closed") # getset descriptor
2870 check(file.name, "file name") # member descriptor
2871
2872 def test_doc_descriptor(self):
2873 # Testing __doc__ descriptor...
2874 # SF bug 542984
2875 class DocDescr(object):
2876 def __get__(self, object, otype):
2877 if object:
2878 object = object.__class__.__name__ + ' instance'
2879 if otype:
2880 otype = otype.__name__
2881 return 'object=%s; type=%s' % (object, otype)
2882 class OldClass:
2883 __doc__ = DocDescr()
2884 class NewClass(object):
2885 __doc__ = DocDescr()
2886 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
2887 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
2888 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
2889 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
2890
2891 def test_set_class(self):
2892 # Testing __class__ assignment...
2893 class C(object): pass
2894 class D(object): pass
2895 class E(object): pass
2896 class F(D, E): pass
2897 for cls in C, D, E, F:
2898 for cls2 in C, D, E, F:
2899 x = cls()
2900 x.__class__ = cls2
2901 self.assert_(x.__class__ is cls2)
2902 x.__class__ = cls
2903 self.assert_(x.__class__ is cls)
2904 def cant(x, C):
2905 try:
2906 x.__class__ = C
2907 except TypeError:
2908 pass
2909 else:
2910 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
2911 try:
2912 delattr(x, "__class__")
2913 except TypeError:
2914 pass
2915 else:
2916 self.fail("shouldn't allow del %r.__class__" % x)
2917 cant(C(), list)
2918 cant(list(), C)
2919 cant(C(), 1)
2920 cant(C(), object)
2921 cant(object(), list)
2922 cant(list(), object)
2923 class Int(int): __slots__ = []
2924 cant(2, Int)
2925 cant(Int(), int)
2926 cant(True, int)
2927 cant(2, bool)
2928 o = object()
2929 cant(o, type(1))
2930 cant(o, type(None))
2931 del o
2932 class G(object):
2933 __slots__ = ["a", "b"]
2934 class H(object):
2935 __slots__ = ["b", "a"]
2936 try:
2937 unicode
2938 except NameError:
2939 class I(object):
2940 __slots__ = ["a", "b"]
2941 else:
2942 class I(object):
2943 __slots__ = [unicode("a"), unicode("b")]
2944 class J(object):
2945 __slots__ = ["c", "b"]
2946 class K(object):
2947 __slots__ = ["a", "b", "d"]
2948 class L(H):
2949 __slots__ = ["e"]
2950 class M(I):
2951 __slots__ = ["e"]
2952 class N(J):
2953 __slots__ = ["__weakref__"]
2954 class P(J):
2955 __slots__ = ["__dict__"]
2956 class Q(J):
2957 pass
2958 class R(J):
2959 __slots__ = ["__dict__", "__weakref__"]
2960
2961 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
2962 x = cls()
2963 x.a = 1
2964 x.__class__ = cls2
2965 self.assert_(x.__class__ is cls2,
2966 "assigning %r as __class__ for %r silently failed" % (cls2, x))
2967 self.assertEqual(x.a, 1)
2968 x.__class__ = cls
2969 self.assert_(x.__class__ is cls,
2970 "assigning %r as __class__ for %r silently failed" % (cls, x))
2971 self.assertEqual(x.a, 1)
2972 for cls in G, J, K, L, M, N, P, R, list, Int:
2973 for cls2 in G, J, K, L, M, N, P, R, list, Int:
2974 if cls is cls2:
2975 continue
2976 cant(cls(), cls2)
2977
Benjamin Petersonaf75a5f2009-04-25 00:44:44 +00002978 # Issue5283: when __class__ changes in __del__, the wrong
2979 # type gets DECREF'd.
2980 class O(object):
2981 pass
2982 class A(object):
2983 def __del__(self):
2984 self.__class__ = O
2985 l = [A() for x in range(100)]
2986 del l
2987
Georg Brandl48545522008-02-02 10:12:36 +00002988 def test_set_dict(self):
2989 # Testing __dict__ assignment...
2990 class C(object): pass
2991 a = C()
2992 a.__dict__ = {'b': 1}
2993 self.assertEqual(a.b, 1)
2994 def cant(x, dict):
2995 try:
2996 x.__dict__ = dict
2997 except (AttributeError, TypeError):
2998 pass
2999 else:
3000 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3001 cant(a, None)
3002 cant(a, [])
3003 cant(a, 1)
3004 del a.__dict__ # Deleting __dict__ is allowed
3005
3006 class Base(object):
3007 pass
3008 def verify_dict_readonly(x):
3009 """
3010 x has to be an instance of a class inheriting from Base.
3011 """
3012 cant(x, {})
3013 try:
3014 del x.__dict__
3015 except (AttributeError, TypeError):
3016 pass
3017 else:
3018 self.fail("shouldn't allow del %r.__dict__" % x)
3019 dict_descr = Base.__dict__["__dict__"]
3020 try:
3021 dict_descr.__set__(x, {})
3022 except (AttributeError, TypeError):
3023 pass
3024 else:
3025 self.fail("dict_descr allowed access to %r's dict" % x)
3026
3027 # Classes don't allow __dict__ assignment and have readonly dicts
3028 class Meta1(type, Base):
3029 pass
3030 class Meta2(Base, type):
3031 pass
3032 class D(object):
3033 __metaclass__ = Meta1
3034 class E(object):
3035 __metaclass__ = Meta2
3036 for cls in C, D, E:
3037 verify_dict_readonly(cls)
3038 class_dict = cls.__dict__
3039 try:
3040 class_dict["spam"] = "eggs"
3041 except TypeError:
3042 pass
3043 else:
3044 self.fail("%r's __dict__ can be modified" % cls)
3045
3046 # Modules also disallow __dict__ assignment
3047 class Module1(types.ModuleType, Base):
3048 pass
3049 class Module2(Base, types.ModuleType):
3050 pass
3051 for ModuleType in Module1, Module2:
3052 mod = ModuleType("spam")
3053 verify_dict_readonly(mod)
3054 mod.__dict__["spam"] = "eggs"
3055
3056 # Exception's __dict__ can be replaced, but not deleted
3057 class Exception1(Exception, Base):
3058 pass
3059 class Exception2(Base, Exception):
3060 pass
3061 for ExceptionType in Exception, Exception1, Exception2:
3062 e = ExceptionType()
3063 e.__dict__ = {"a": 1}
3064 self.assertEqual(e.a, 1)
3065 try:
3066 del e.__dict__
3067 except (TypeError, AttributeError):
3068 pass
3069 else:
3070 self.fail("%r's __dict__ can be deleted" % e)
3071
3072 def test_pickles(self):
3073 # Testing pickling and copying new-style classes and objects...
3074 import pickle, cPickle
3075
3076 def sorteditems(d):
3077 L = d.items()
3078 L.sort()
3079 return L
3080
3081 global C
3082 class C(object):
3083 def __init__(self, a, b):
3084 super(C, self).__init__()
3085 self.a = a
3086 self.b = b
3087 def __repr__(self):
3088 return "C(%r, %r)" % (self.a, self.b)
3089
3090 global C1
3091 class C1(list):
3092 def __new__(cls, a, b):
3093 return super(C1, cls).__new__(cls)
3094 def __getnewargs__(self):
3095 return (self.a, self.b)
3096 def __init__(self, a, b):
3097 self.a = a
3098 self.b = b
3099 def __repr__(self):
3100 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
3101
3102 global C2
3103 class C2(int):
3104 def __new__(cls, a, b, val=0):
3105 return super(C2, cls).__new__(cls, val)
3106 def __getnewargs__(self):
3107 return (self.a, self.b, int(self))
3108 def __init__(self, a, b, val=0):
3109 self.a = a
3110 self.b = b
3111 def __repr__(self):
3112 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
3113
3114 global C3
3115 class C3(object):
3116 def __init__(self, foo):
3117 self.foo = foo
3118 def __getstate__(self):
3119 return self.foo
3120 def __setstate__(self, foo):
3121 self.foo = foo
3122
3123 global C4classic, C4
3124 class C4classic: # classic
3125 pass
3126 class C4(C4classic, object): # mixed inheritance
3127 pass
3128
3129 for p in pickle, cPickle:
3130 for bin in 0, 1:
3131 for cls in C, C1, C2:
3132 s = p.dumps(cls, bin)
3133 cls2 = p.loads(s)
3134 self.assert_(cls2 is cls)
3135
3136 a = C1(1, 2); a.append(42); a.append(24)
3137 b = C2("hello", "world", 42)
3138 s = p.dumps((a, b), bin)
3139 x, y = p.loads(s)
3140 self.assertEqual(x.__class__, a.__class__)
3141 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3142 self.assertEqual(y.__class__, b.__class__)
3143 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3144 self.assertEqual(repr(x), repr(a))
3145 self.assertEqual(repr(y), repr(b))
3146 # Test for __getstate__ and __setstate__ on new style class
3147 u = C3(42)
3148 s = p.dumps(u, bin)
3149 v = p.loads(s)
3150 self.assertEqual(u.__class__, v.__class__)
3151 self.assertEqual(u.foo, v.foo)
3152 # Test for picklability of hybrid class
3153 u = C4()
3154 u.foo = 42
3155 s = p.dumps(u, bin)
3156 v = p.loads(s)
3157 self.assertEqual(u.__class__, v.__class__)
3158 self.assertEqual(u.foo, v.foo)
3159
3160 # Testing copy.deepcopy()
3161 import copy
3162 for cls in C, C1, C2:
3163 cls2 = copy.deepcopy(cls)
3164 self.assert_(cls2 is cls)
3165
3166 a = C1(1, 2); a.append(42); a.append(24)
3167 b = C2("hello", "world", 42)
3168 x, y = copy.deepcopy((a, b))
3169 self.assertEqual(x.__class__, a.__class__)
3170 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3171 self.assertEqual(y.__class__, b.__class__)
3172 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3173 self.assertEqual(repr(x), repr(a))
3174 self.assertEqual(repr(y), repr(b))
3175
3176 def test_pickle_slots(self):
3177 # Testing pickling of classes with __slots__ ...
3178 import pickle, cPickle
3179 # Pickling of classes with __slots__ but without __getstate__ should fail
3180 global B, C, D, E
3181 class B(object):
3182 pass
3183 for base in [object, B]:
3184 class C(base):
3185 __slots__ = ['a']
3186 class D(C):
3187 pass
3188 try:
3189 pickle.dumps(C())
3190 except TypeError:
3191 pass
3192 else:
3193 self.fail("should fail: pickle C instance - %s" % base)
3194 try:
3195 cPickle.dumps(C())
3196 except TypeError:
3197 pass
3198 else:
3199 self.fail("should fail: cPickle C instance - %s" % base)
3200 try:
3201 pickle.dumps(C())
3202 except TypeError:
3203 pass
3204 else:
3205 self.fail("should fail: pickle D instance - %s" % base)
3206 try:
3207 cPickle.dumps(D())
3208 except TypeError:
3209 pass
3210 else:
3211 self.fail("should fail: cPickle D instance - %s" % base)
3212 # Give C a nice generic __getstate__ and __setstate__
3213 class C(base):
3214 __slots__ = ['a']
3215 def __getstate__(self):
3216 try:
3217 d = self.__dict__.copy()
3218 except AttributeError:
3219 d = {}
3220 for cls in self.__class__.__mro__:
3221 for sn in cls.__dict__.get('__slots__', ()):
3222 try:
3223 d[sn] = getattr(self, sn)
3224 except AttributeError:
3225 pass
3226 return d
3227 def __setstate__(self, d):
3228 for k, v in d.items():
3229 setattr(self, k, v)
3230 class D(C):
3231 pass
3232 # Now it should work
3233 x = C()
3234 y = pickle.loads(pickle.dumps(x))
3235 self.assertEqual(hasattr(y, 'a'), 0)
3236 y = cPickle.loads(cPickle.dumps(x))
3237 self.assertEqual(hasattr(y, 'a'), 0)
3238 x.a = 42
3239 y = pickle.loads(pickle.dumps(x))
3240 self.assertEqual(y.a, 42)
3241 y = cPickle.loads(cPickle.dumps(x))
3242 self.assertEqual(y.a, 42)
3243 x = D()
3244 x.a = 42
3245 x.b = 100
3246 y = pickle.loads(pickle.dumps(x))
3247 self.assertEqual(y.a + y.b, 142)
3248 y = cPickle.loads(cPickle.dumps(x))
3249 self.assertEqual(y.a + y.b, 142)
3250 # A subclass that adds a slot should also work
3251 class E(C):
3252 __slots__ = ['b']
3253 x = E()
3254 x.a = 42
3255 x.b = "foo"
3256 y = pickle.loads(pickle.dumps(x))
3257 self.assertEqual(y.a, x.a)
3258 self.assertEqual(y.b, x.b)
3259 y = cPickle.loads(cPickle.dumps(x))
3260 self.assertEqual(y.a, x.a)
3261 self.assertEqual(y.b, x.b)
3262
3263 def test_binary_operator_override(self):
3264 # Testing overrides of binary operations...
3265 class I(int):
3266 def __repr__(self):
3267 return "I(%r)" % int(self)
3268 def __add__(self, other):
3269 return I(int(self) + int(other))
3270 __radd__ = __add__
3271 def __pow__(self, other, mod=None):
3272 if mod is None:
3273 return I(pow(int(self), int(other)))
3274 else:
3275 return I(pow(int(self), int(other), int(mod)))
3276 def __rpow__(self, other, mod=None):
3277 if mod is None:
3278 return I(pow(int(other), int(self), mod))
3279 else:
3280 return I(pow(int(other), int(self), int(mod)))
3281
3282 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3283 self.assertEqual(repr(I(1) + 2), "I(3)")
3284 self.assertEqual(repr(1 + I(2)), "I(3)")
3285 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3286 self.assertEqual(repr(2 ** I(3)), "I(8)")
3287 self.assertEqual(repr(I(2) ** 3), "I(8)")
3288 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3289 class S(str):
3290 def __eq__(self, other):
3291 return self.lower() == other.lower()
Nick Coghlan48361f52008-08-11 15:45:58 +00003292 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00003293
3294 def test_subclass_propagation(self):
3295 # Testing propagation of slot functions to subclasses...
3296 class A(object):
3297 pass
3298 class B(A):
3299 pass
3300 class C(A):
3301 pass
3302 class D(B, C):
3303 pass
3304 d = D()
3305 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3306 A.__hash__ = lambda self: 42
3307 self.assertEqual(hash(d), 42)
3308 C.__hash__ = lambda self: 314
3309 self.assertEqual(hash(d), 314)
3310 B.__hash__ = lambda self: 144
3311 self.assertEqual(hash(d), 144)
3312 D.__hash__ = lambda self: 100
3313 self.assertEqual(hash(d), 100)
Nick Coghlan53663a62008-07-15 14:27:37 +00003314 D.__hash__ = None
3315 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003316 del D.__hash__
3317 self.assertEqual(hash(d), 144)
Nick Coghlan53663a62008-07-15 14:27:37 +00003318 B.__hash__ = None
3319 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003320 del B.__hash__
3321 self.assertEqual(hash(d), 314)
Nick Coghlan53663a62008-07-15 14:27:37 +00003322 C.__hash__ = None
3323 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003324 del C.__hash__
3325 self.assertEqual(hash(d), 42)
Nick Coghlan53663a62008-07-15 14:27:37 +00003326 A.__hash__ = None
3327 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003328 del A.__hash__
3329 self.assertEqual(hash(d), orig_hash)
3330 d.foo = 42
3331 d.bar = 42
3332 self.assertEqual(d.foo, 42)
3333 self.assertEqual(d.bar, 42)
3334 def __getattribute__(self, name):
3335 if name == "foo":
3336 return 24
3337 return object.__getattribute__(self, name)
3338 A.__getattribute__ = __getattribute__
3339 self.assertEqual(d.foo, 24)
3340 self.assertEqual(d.bar, 42)
3341 def __getattr__(self, name):
3342 if name in ("spam", "foo", "bar"):
3343 return "hello"
3344 raise AttributeError, name
3345 B.__getattr__ = __getattr__
3346 self.assertEqual(d.spam, "hello")
3347 self.assertEqual(d.foo, 24)
3348 self.assertEqual(d.bar, 42)
3349 del A.__getattribute__
3350 self.assertEqual(d.foo, 42)
3351 del d.foo
3352 self.assertEqual(d.foo, "hello")
3353 self.assertEqual(d.bar, 42)
3354 del B.__getattr__
3355 try:
3356 d.foo
3357 except AttributeError:
3358 pass
3359 else:
3360 self.fail("d.foo should be undefined now")
3361
3362 # Test a nasty bug in recurse_down_subclasses()
3363 import gc
3364 class A(object):
3365 pass
3366 class B(A):
3367 pass
3368 del B
3369 gc.collect()
3370 A.__setitem__ = lambda *a: None # crash
3371
3372 def test_buffer_inheritance(self):
3373 # Testing that buffer interface is inherited ...
3374
3375 import binascii
3376 # SF bug [#470040] ParseTuple t# vs subclasses.
3377
3378 class MyStr(str):
3379 pass
3380 base = 'abc'
3381 m = MyStr(base)
3382 # b2a_hex uses the buffer interface to get its argument's value, via
3383 # PyArg_ParseTuple 't#' code.
3384 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3385
3386 # It's not clear that unicode will continue to support the character
3387 # buffer interface, and this test will fail if that's taken away.
3388 class MyUni(unicode):
3389 pass
3390 base = u'abc'
3391 m = MyUni(base)
3392 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3393
3394 class MyInt(int):
3395 pass
3396 m = MyInt(42)
3397 try:
3398 binascii.b2a_hex(m)
3399 self.fail('subclass of int should not have a buffer interface')
3400 except TypeError:
3401 pass
3402
3403 def test_str_of_str_subclass(self):
3404 # Testing __str__ defined in subclass of str ...
3405 import binascii
3406 import cStringIO
3407
3408 class octetstring(str):
3409 def __str__(self):
3410 return binascii.b2a_hex(self)
3411 def __repr__(self):
3412 return self + " repr"
3413
3414 o = octetstring('A')
3415 self.assertEqual(type(o), octetstring)
3416 self.assertEqual(type(str(o)), str)
3417 self.assertEqual(type(repr(o)), str)
3418 self.assertEqual(ord(o), 0x41)
3419 self.assertEqual(str(o), '41')
3420 self.assertEqual(repr(o), 'A repr')
3421 self.assertEqual(o.__str__(), '41')
3422 self.assertEqual(o.__repr__(), 'A repr')
3423
3424 capture = cStringIO.StringIO()
3425 # Calling str() or not exercises different internal paths.
3426 print >> capture, o
3427 print >> capture, str(o)
3428 self.assertEqual(capture.getvalue(), '41\n41\n')
3429 capture.close()
3430
3431 def test_keyword_arguments(self):
3432 # Testing keyword arguments to __init__, __call__...
3433 def f(a): return a
3434 self.assertEqual(f.__call__(a=42), 42)
3435 a = []
3436 list.__init__(a, sequence=[0, 1, 2])
3437 self.assertEqual(a, [0, 1, 2])
3438
3439 def test_recursive_call(self):
3440 # Testing recursive __call__() by setting to instance of class...
3441 class A(object):
3442 pass
3443
3444 A.__call__ = A()
3445 try:
3446 A()()
3447 except RuntimeError:
3448 pass
3449 else:
3450 self.fail("Recursion limit should have been reached for __call__()")
3451
3452 def test_delete_hook(self):
3453 # Testing __del__ hook...
3454 log = []
3455 class C(object):
3456 def __del__(self):
3457 log.append(1)
3458 c = C()
3459 self.assertEqual(log, [])
3460 del c
3461 self.assertEqual(log, [1])
3462
3463 class D(object): pass
3464 d = D()
3465 try: del d[0]
3466 except TypeError: pass
3467 else: self.fail("invalid del() didn't raise TypeError")
3468
3469 def test_hash_inheritance(self):
3470 # Testing hash of mutable subclasses...
3471
3472 class mydict(dict):
3473 pass
3474 d = mydict()
3475 try:
3476 hash(d)
3477 except TypeError:
3478 pass
3479 else:
3480 self.fail("hash() of dict subclass should fail")
3481
3482 class mylist(list):
3483 pass
3484 d = mylist()
3485 try:
3486 hash(d)
3487 except TypeError:
3488 pass
3489 else:
3490 self.fail("hash() of list subclass should fail")
3491
3492 def test_str_operations(self):
3493 try: 'a' + 5
3494 except TypeError: pass
3495 else: self.fail("'' + 5 doesn't raise TypeError")
3496
3497 try: ''.split('')
3498 except ValueError: pass
3499 else: self.fail("''.split('') doesn't raise ValueError")
3500
3501 try: ''.join([0])
3502 except TypeError: pass
3503 else: self.fail("''.join([0]) doesn't raise TypeError")
3504
3505 try: ''.rindex('5')
3506 except ValueError: pass
3507 else: self.fail("''.rindex('5') doesn't raise ValueError")
3508
3509 try: '%(n)s' % None
3510 except TypeError: pass
3511 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3512
3513 try: '%(n' % {}
3514 except ValueError: pass
3515 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3516
3517 try: '%*s' % ('abc')
3518 except TypeError: pass
3519 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3520
3521 try: '%*.*s' % ('abc', 5)
3522 except TypeError: pass
3523 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3524
3525 try: '%s' % (1, 2)
3526 except TypeError: pass
3527 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3528
3529 try: '%' % None
3530 except ValueError: pass
3531 else: self.fail("'%' % None doesn't raise ValueError")
3532
3533 self.assertEqual('534253'.isdigit(), 1)
3534 self.assertEqual('534253x'.isdigit(), 0)
3535 self.assertEqual('%c' % 5, '\x05')
3536 self.assertEqual('%c' % '5', '5')
3537
3538 def test_deepcopy_recursive(self):
3539 # Testing deepcopy of recursive objects...
3540 class Node:
3541 pass
3542 a = Node()
3543 b = Node()
3544 a.b = b
3545 b.a = a
3546 z = deepcopy(a) # This blew up before
3547
3548 def test_unintialized_modules(self):
3549 # Testing uninitialized module objects...
3550 from types import ModuleType as M
3551 m = M.__new__(M)
3552 str(m)
3553 self.assertEqual(hasattr(m, "__name__"), 0)
3554 self.assertEqual(hasattr(m, "__file__"), 0)
3555 self.assertEqual(hasattr(m, "foo"), 0)
3556 self.assertEqual(m.__dict__, None)
3557 m.foo = 1
3558 self.assertEqual(m.__dict__, {"foo": 1})
3559
3560 def test_funny_new(self):
3561 # Testing __new__ returning something unexpected...
3562 class C(object):
3563 def __new__(cls, arg):
3564 if isinstance(arg, str): return [1, 2, 3]
3565 elif isinstance(arg, int): return object.__new__(D)
3566 else: return object.__new__(cls)
3567 class D(C):
3568 def __init__(self, arg):
3569 self.foo = arg
3570 self.assertEqual(C("1"), [1, 2, 3])
3571 self.assertEqual(D("1"), [1, 2, 3])
3572 d = D(None)
3573 self.assertEqual(d.foo, None)
3574 d = C(1)
3575 self.assertEqual(isinstance(d, D), True)
3576 self.assertEqual(d.foo, 1)
3577 d = D(1)
3578 self.assertEqual(isinstance(d, D), True)
3579 self.assertEqual(d.foo, 1)
3580
3581 def test_imul_bug(self):
3582 # Testing for __imul__ problems...
3583 # SF bug 544647
3584 class C(object):
3585 def __imul__(self, other):
3586 return (self, other)
3587 x = C()
3588 y = x
3589 y *= 1.0
3590 self.assertEqual(y, (x, 1.0))
3591 y = x
3592 y *= 2
3593 self.assertEqual(y, (x, 2))
3594 y = x
3595 y *= 3L
3596 self.assertEqual(y, (x, 3L))
3597 y = x
3598 y *= 1L<<100
3599 self.assertEqual(y, (x, 1L<<100))
3600 y = x
3601 y *= None
3602 self.assertEqual(y, (x, None))
3603 y = x
3604 y *= "foo"
3605 self.assertEqual(y, (x, "foo"))
3606
3607 def test_copy_setstate(self):
3608 # Testing that copy.*copy() correctly uses __setstate__...
3609 import copy
3610 class C(object):
3611 def __init__(self, foo=None):
3612 self.foo = foo
3613 self.__foo = foo
3614 def setfoo(self, foo=None):
3615 self.foo = foo
3616 def getfoo(self):
3617 return self.__foo
3618 def __getstate__(self):
3619 return [self.foo]
3620 def __setstate__(self_, lst):
3621 self.assertEqual(len(lst), 1)
3622 self_.__foo = self_.foo = lst[0]
3623 a = C(42)
3624 a.setfoo(24)
3625 self.assertEqual(a.foo, 24)
3626 self.assertEqual(a.getfoo(), 42)
3627 b = copy.copy(a)
3628 self.assertEqual(b.foo, 24)
3629 self.assertEqual(b.getfoo(), 24)
3630 b = copy.deepcopy(a)
3631 self.assertEqual(b.foo, 24)
3632 self.assertEqual(b.getfoo(), 24)
3633
3634 def test_slices(self):
3635 # Testing cases with slices and overridden __getitem__ ...
3636
3637 # Strings
3638 self.assertEqual("hello"[:4], "hell")
3639 self.assertEqual("hello"[slice(4)], "hell")
3640 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3641 class S(str):
3642 def __getitem__(self, x):
3643 return str.__getitem__(self, x)
3644 self.assertEqual(S("hello")[:4], "hell")
3645 self.assertEqual(S("hello")[slice(4)], "hell")
3646 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3647 # Tuples
3648 self.assertEqual((1,2,3)[:2], (1,2))
3649 self.assertEqual((1,2,3)[slice(2)], (1,2))
3650 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3651 class T(tuple):
3652 def __getitem__(self, x):
3653 return tuple.__getitem__(self, x)
3654 self.assertEqual(T((1,2,3))[:2], (1,2))
3655 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3656 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3657 # Lists
3658 self.assertEqual([1,2,3][:2], [1,2])
3659 self.assertEqual([1,2,3][slice(2)], [1,2])
3660 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3661 class L(list):
3662 def __getitem__(self, x):
3663 return list.__getitem__(self, x)
3664 self.assertEqual(L([1,2,3])[:2], [1,2])
3665 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3666 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3667 # Now do lists and __setitem__
3668 a = L([1,2,3])
3669 a[slice(1, 3)] = [3,2]
3670 self.assertEqual(a, [1,3,2])
3671 a[slice(0, 2, 1)] = [3,1]
3672 self.assertEqual(a, [3,1,2])
3673 a.__setitem__(slice(1, 3), [2,1])
3674 self.assertEqual(a, [3,2,1])
3675 a.__setitem__(slice(0, 2, 1), [2,3])
3676 self.assertEqual(a, [2,3,1])
3677
3678 def test_subtype_resurrection(self):
3679 # Testing resurrection of new-style instance...
3680
3681 class C(object):
3682 container = []
3683
3684 def __del__(self):
3685 # resurrect the instance
3686 C.container.append(self)
3687
3688 c = C()
3689 c.attr = 42
3690
3691 # The most interesting thing here is whether this blows up, due to flawed
3692 # GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 bug).
3693 del c
3694
3695 # If that didn't blow up, it's also interesting to see whether clearing
3696 # the last container slot works: that will attempt to delete c again,
3697 # which will cause c to get appended back to the container again "during"
3698 # the del.
3699 del C.container[-1]
3700 self.assertEqual(len(C.container), 1)
3701 self.assertEqual(C.container[-1].attr, 42)
3702
3703 # Make c mortal again, so that the test framework with -l doesn't report
3704 # it as a leak.
3705 del C.__del__
3706
3707 def test_slots_trash(self):
3708 # Testing slot trash...
3709 # Deallocating deeply nested slotted trash caused stack overflows
3710 class trash(object):
3711 __slots__ = ['x']
3712 def __init__(self, x):
3713 self.x = x
3714 o = None
3715 for i in xrange(50000):
3716 o = trash(o)
3717 del o
3718
3719 def test_slots_multiple_inheritance(self):
3720 # SF bug 575229, multiple inheritance w/ slots dumps core
3721 class A(object):
3722 __slots__=()
3723 class B(object):
3724 pass
3725 class C(A,B) :
3726 __slots__=()
3727 self.assertEqual(C.__basicsize__, B.__basicsize__)
3728 self.assert_(hasattr(C, '__dict__'))
3729 self.assert_(hasattr(C, '__weakref__'))
3730 C().x = 2
3731
3732 def test_rmul(self):
3733 # Testing correct invocation of __rmul__...
3734 # SF patch 592646
3735 class C(object):
3736 def __mul__(self, other):
3737 return "mul"
3738 def __rmul__(self, other):
3739 return "rmul"
3740 a = C()
3741 self.assertEqual(a*2, "mul")
3742 self.assertEqual(a*2.2, "mul")
3743 self.assertEqual(2*a, "rmul")
3744 self.assertEqual(2.2*a, "rmul")
3745
3746 def test_ipow(self):
3747 # Testing correct invocation of __ipow__...
3748 # [SF bug 620179]
3749 class C(object):
3750 def __ipow__(self, other):
3751 pass
3752 a = C()
3753 a **= 2
3754
3755 def test_mutable_bases(self):
3756 # Testing mutable bases...
3757
3758 # stuff that should work:
3759 class C(object):
3760 pass
3761 class C2(object):
3762 def __getattribute__(self, attr):
3763 if attr == 'a':
3764 return 2
3765 else:
3766 return super(C2, self).__getattribute__(attr)
3767 def meth(self):
3768 return 1
3769 class D(C):
3770 pass
3771 class E(D):
3772 pass
3773 d = D()
3774 e = E()
3775 D.__bases__ = (C,)
3776 D.__bases__ = (C2,)
3777 self.assertEqual(d.meth(), 1)
3778 self.assertEqual(e.meth(), 1)
3779 self.assertEqual(d.a, 2)
3780 self.assertEqual(e.a, 2)
3781 self.assertEqual(C2.__subclasses__(), [D])
3782
3783 # stuff that shouldn't:
3784 class L(list):
3785 pass
3786
3787 try:
3788 L.__bases__ = (dict,)
3789 except TypeError:
3790 pass
3791 else:
3792 self.fail("shouldn't turn list subclass into dict subclass")
3793
3794 try:
3795 list.__bases__ = (dict,)
3796 except TypeError:
3797 pass
3798 else:
3799 self.fail("shouldn't be able to assign to list.__bases__")
3800
3801 try:
3802 D.__bases__ = (C2, list)
3803 except TypeError:
3804 pass
3805 else:
3806 assert 0, "best_base calculation found wanting"
3807
3808 try:
3809 del D.__bases__
3810 except TypeError:
3811 pass
3812 else:
3813 self.fail("shouldn't be able to delete .__bases__")
3814
3815 try:
3816 D.__bases__ = ()
3817 except TypeError, msg:
3818 if str(msg) == "a new-style class can't have only classic bases":
3819 self.fail("wrong error message for .__bases__ = ()")
3820 else:
3821 self.fail("shouldn't be able to set .__bases__ to ()")
3822
3823 try:
3824 D.__bases__ = (D,)
3825 except TypeError:
3826 pass
3827 else:
3828 # actually, we'll have crashed by here...
3829 self.fail("shouldn't be able to create inheritance cycles")
3830
3831 try:
3832 D.__bases__ = (C, C)
3833 except TypeError:
3834 pass
3835 else:
3836 self.fail("didn't detect repeated base classes")
3837
3838 try:
3839 D.__bases__ = (E,)
3840 except TypeError:
3841 pass
3842 else:
3843 self.fail("shouldn't be able to create inheritance cycles")
3844
3845 # let's throw a classic class into the mix:
3846 class Classic:
3847 def meth2(self):
3848 return 3
3849
3850 D.__bases__ = (C, Classic)
3851
3852 self.assertEqual(d.meth2(), 3)
3853 self.assertEqual(e.meth2(), 3)
3854 try:
3855 d.a
3856 except AttributeError:
3857 pass
3858 else:
3859 self.fail("attribute should have vanished")
3860
3861 try:
3862 D.__bases__ = (Classic,)
3863 except TypeError:
3864 pass
3865 else:
3866 self.fail("new-style class must have a new-style base")
3867
Benjamin Peterson4585ca92009-04-18 20:50:24 +00003868 def test_builtin_bases(self):
3869 # Make sure all the builtin types can have their base queried without
3870 # segfaulting. See issue #5787.
3871 builtin_types = [tp for tp in __builtin__.__dict__.itervalues()
3872 if isinstance(tp, type)]
3873 for tp in builtin_types:
3874 object.__getattribute__(tp, "__bases__")
3875 if tp is not object:
3876 self.assertEqual(len(tp.__bases__), 1, tp)
3877
3878
Georg Brandl48545522008-02-02 10:12:36 +00003879 def test_mutable_bases_with_failing_mro(self):
3880 # Testing mutable bases with failing mro...
3881 class WorkOnce(type):
3882 def __new__(self, name, bases, ns):
3883 self.flag = 0
3884 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3885 def mro(self):
3886 if self.flag > 0:
3887 raise RuntimeError, "bozo"
3888 else:
3889 self.flag += 1
3890 return type.mro(self)
3891
3892 class WorkAlways(type):
3893 def mro(self):
3894 # this is here to make sure that .mro()s aren't called
3895 # with an exception set (which was possible at one point).
3896 # An error message will be printed in a debug build.
3897 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003898 return type.mro(self)
3899
Georg Brandl48545522008-02-02 10:12:36 +00003900 class C(object):
3901 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003902
Georg Brandl48545522008-02-02 10:12:36 +00003903 class C2(object):
3904 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003905
Georg Brandl48545522008-02-02 10:12:36 +00003906 class D(C):
3907 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003908
Georg Brandl48545522008-02-02 10:12:36 +00003909 class E(D):
3910 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003911
Georg Brandl48545522008-02-02 10:12:36 +00003912 class F(D):
3913 __metaclass__ = WorkOnce
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003914
Georg Brandl48545522008-02-02 10:12:36 +00003915 class G(D):
3916 __metaclass__ = WorkAlways
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003917
Georg Brandl48545522008-02-02 10:12:36 +00003918 # Immediate subclasses have their mro's adjusted in alphabetical
3919 # order, so E's will get adjusted before adjusting F's fails. We
3920 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003921
Georg Brandl48545522008-02-02 10:12:36 +00003922 E_mro_before = E.__mro__
3923 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00003924
Armin Rigofd163f92005-12-29 15:59:19 +00003925 try:
Georg Brandl48545522008-02-02 10:12:36 +00003926 D.__bases__ = (C2,)
3927 except RuntimeError:
3928 self.assertEqual(E.__mro__, E_mro_before)
3929 self.assertEqual(D.__mro__, D_mro_before)
3930 else:
3931 self.fail("exception not propagated")
3932
3933 def test_mutable_bases_catch_mro_conflict(self):
3934 # Testing mutable bases catch mro conflict...
3935 class A(object):
3936 pass
3937
3938 class B(object):
3939 pass
3940
3941 class C(A, B):
3942 pass
3943
3944 class D(A, B):
3945 pass
3946
3947 class E(C, D):
3948 pass
3949
3950 try:
3951 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00003952 except TypeError:
3953 pass
3954 else:
Georg Brandl48545522008-02-02 10:12:36 +00003955 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00003956
Georg Brandl48545522008-02-02 10:12:36 +00003957 def test_mutable_names(self):
3958 # Testing mutable names...
3959 class C(object):
3960 pass
3961
3962 # C.__module__ could be 'test_descr' or '__main__'
3963 mod = C.__module__
3964
3965 C.__name__ = 'D'
3966 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
3967
3968 C.__name__ = 'D.E'
3969 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
3970
3971 def test_subclass_right_op(self):
3972 # Testing correct dispatch of subclass overloading __r<op>__...
3973
3974 # This code tests various cases where right-dispatch of a subclass
3975 # should be preferred over left-dispatch of a base class.
3976
3977 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3978
3979 class B(int):
3980 def __floordiv__(self, other):
3981 return "B.__floordiv__"
3982 def __rfloordiv__(self, other):
3983 return "B.__rfloordiv__"
3984
3985 self.assertEqual(B(1) // 1, "B.__floordiv__")
3986 self.assertEqual(1 // B(1), "B.__rfloordiv__")
3987
3988 # Case 2: subclass of object; this is just the baseline for case 3
3989
3990 class C(object):
3991 def __floordiv__(self, other):
3992 return "C.__floordiv__"
3993 def __rfloordiv__(self, other):
3994 return "C.__rfloordiv__"
3995
3996 self.assertEqual(C() // 1, "C.__floordiv__")
3997 self.assertEqual(1 // C(), "C.__rfloordiv__")
3998
3999 # Case 3: subclass of new-style class; here it gets interesting
4000
4001 class D(C):
4002 def __floordiv__(self, other):
4003 return "D.__floordiv__"
4004 def __rfloordiv__(self, other):
4005 return "D.__rfloordiv__"
4006
4007 self.assertEqual(D() // C(), "D.__floordiv__")
4008 self.assertEqual(C() // D(), "D.__rfloordiv__")
4009
4010 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4011
4012 class E(C):
4013 pass
4014
4015 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4016
4017 self.assertEqual(E() // 1, "C.__floordiv__")
4018 self.assertEqual(1 // E(), "C.__rfloordiv__")
4019 self.assertEqual(E() // C(), "C.__floordiv__")
4020 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4021
4022 def test_meth_class_get(self):
4023 # Testing __get__ method of METH_CLASS C methods...
4024 # Full coverage of descrobject.c::classmethod_get()
4025
4026 # Baseline
4027 arg = [1, 2, 3]
4028 res = {1: None, 2: None, 3: None}
4029 self.assertEqual(dict.fromkeys(arg), res)
4030 self.assertEqual({}.fromkeys(arg), res)
4031
4032 # Now get the descriptor
4033 descr = dict.__dict__["fromkeys"]
4034
4035 # More baseline using the descriptor directly
4036 self.assertEqual(descr.__get__(None, dict)(arg), res)
4037 self.assertEqual(descr.__get__({})(arg), res)
4038
4039 # Now check various error cases
4040 try:
4041 descr.__get__(None, None)
4042 except TypeError:
4043 pass
4044 else:
4045 self.fail("shouldn't have allowed descr.__get__(None, None)")
4046 try:
4047 descr.__get__(42)
4048 except TypeError:
4049 pass
4050 else:
4051 self.fail("shouldn't have allowed descr.__get__(42)")
4052 try:
4053 descr.__get__(None, 42)
4054 except TypeError:
4055 pass
4056 else:
4057 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4058 try:
4059 descr.__get__(None, int)
4060 except TypeError:
4061 pass
4062 else:
4063 self.fail("shouldn't have allowed descr.__get__(None, int)")
4064
4065 def test_isinst_isclass(self):
4066 # Testing proxy isinstance() and isclass()...
4067 class Proxy(object):
4068 def __init__(self, obj):
4069 self.__obj = obj
4070 def __getattribute__(self, name):
4071 if name.startswith("_Proxy__"):
4072 return object.__getattribute__(self, name)
4073 else:
4074 return getattr(self.__obj, name)
4075 # Test with a classic class
4076 class C:
4077 pass
4078 a = C()
4079 pa = Proxy(a)
4080 self.assert_(isinstance(a, C)) # Baseline
4081 self.assert_(isinstance(pa, C)) # Test
4082 # Test with a classic subclass
4083 class D(C):
4084 pass
4085 a = D()
4086 pa = Proxy(a)
4087 self.assert_(isinstance(a, C)) # Baseline
4088 self.assert_(isinstance(pa, C)) # Test
4089 # Test with a new-style class
4090 class C(object):
4091 pass
4092 a = C()
4093 pa = Proxy(a)
4094 self.assert_(isinstance(a, C)) # Baseline
4095 self.assert_(isinstance(pa, C)) # Test
4096 # Test with a new-style subclass
4097 class D(C):
4098 pass
4099 a = D()
4100 pa = Proxy(a)
4101 self.assert_(isinstance(a, C)) # Baseline
4102 self.assert_(isinstance(pa, C)) # Test
4103
4104 def test_proxy_super(self):
4105 # Testing super() for a proxy object...
4106 class Proxy(object):
4107 def __init__(self, obj):
4108 self.__obj = obj
4109 def __getattribute__(self, name):
4110 if name.startswith("_Proxy__"):
4111 return object.__getattribute__(self, name)
4112 else:
4113 return getattr(self.__obj, name)
4114
4115 class B(object):
4116 def f(self):
4117 return "B.f"
4118
4119 class C(B):
4120 def f(self):
4121 return super(C, self).f() + "->C.f"
4122
4123 obj = C()
4124 p = Proxy(obj)
4125 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4126
4127 def test_carloverre(self):
4128 # Testing prohibition of Carlo Verre's hack...
4129 try:
4130 object.__setattr__(str, "foo", 42)
4131 except TypeError:
4132 pass
4133 else:
4134 self.fail("Carlo Verre __setattr__ suceeded!")
4135 try:
4136 object.__delattr__(str, "lower")
4137 except TypeError:
4138 pass
4139 else:
4140 self.fail("Carlo Verre __delattr__ succeeded!")
4141
4142 def test_weakref_segfault(self):
4143 # Testing weakref segfault...
4144 # SF 742911
4145 import weakref
4146
4147 class Provoker:
4148 def __init__(self, referrent):
4149 self.ref = weakref.ref(referrent)
4150
4151 def __del__(self):
4152 x = self.ref()
4153
4154 class Oops(object):
4155 pass
4156
4157 o = Oops()
4158 o.whatever = Provoker(o)
4159 del o
4160
4161 def test_wrapper_segfault(self):
4162 # SF 927248: deeply nested wrappers could cause stack overflow
4163 f = lambda:None
4164 for i in xrange(1000000):
4165 f = f.__call__
4166 f = None
4167
4168 def test_file_fault(self):
4169 # Testing sys.stdout is changed in getattr...
4170 import sys
4171 class StdoutGuard:
4172 def __getattr__(self, attr):
4173 sys.stdout = sys.__stdout__
4174 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4175 sys.stdout = StdoutGuard()
4176 try:
4177 print "Oops!"
4178 except RuntimeError:
4179 pass
4180
4181 def test_vicious_descriptor_nonsense(self):
4182 # Testing vicious_descriptor_nonsense...
4183
4184 # A potential segfault spotted by Thomas Wouters in mail to
4185 # python-dev 2003-04-17, turned into an example & fixed by Michael
4186 # Hudson just less than four months later...
4187
4188 class Evil(object):
4189 def __hash__(self):
4190 return hash('attr')
4191 def __eq__(self, other):
4192 del C.attr
4193 return 0
4194
4195 class Descr(object):
4196 def __get__(self, ob, type=None):
4197 return 1
4198
4199 class C(object):
4200 attr = Descr()
4201
4202 c = C()
4203 c.__dict__[Evil()] = 0
4204
4205 self.assertEqual(c.attr, 1)
4206 # this makes a crash more likely:
4207 import gc; gc.collect()
4208 self.assertEqual(hasattr(c, 'attr'), False)
4209
4210 def test_init(self):
4211 # SF 1155938
4212 class Foo(object):
4213 def __init__(self):
4214 return 10
4215 try:
4216 Foo()
4217 except TypeError:
4218 pass
4219 else:
4220 self.fail("did not test __init__() for None return")
4221
4222 def test_method_wrapper(self):
4223 # Testing method-wrapper objects...
4224 # <type 'method-wrapper'> did not support any reflection before 2.5
4225
4226 l = []
4227 self.assertEqual(l.__add__, l.__add__)
4228 self.assertEqual(l.__add__, [].__add__)
4229 self.assert_(l.__add__ != [5].__add__)
4230 self.assert_(l.__add__ != l.__mul__)
4231 self.assert_(l.__add__.__name__ == '__add__')
4232 self.assert_(l.__add__.__self__ is l)
4233 self.assert_(l.__add__.__objclass__ is list)
4234 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4235 try:
4236 hash(l.__add__)
4237 except TypeError:
4238 pass
4239 else:
4240 self.fail("no TypeError from hash([].__add__)")
4241
4242 t = ()
4243 t += (7,)
4244 self.assertEqual(t.__add__, (7,).__add__)
4245 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4246
4247 def test_not_implemented(self):
4248 # Testing NotImplemented...
4249 # all binary methods should be able to return a NotImplemented
4250 import sys
4251 import types
4252 import operator
4253
4254 def specialmethod(self, other):
4255 return NotImplemented
4256
4257 def check(expr, x, y):
4258 try:
4259 exec expr in {'x': x, 'y': y, 'operator': operator}
4260 except TypeError:
4261 pass
Armin Rigofd163f92005-12-29 15:59:19 +00004262 else:
Georg Brandl48545522008-02-02 10:12:36 +00004263 self.fail("no TypeError from %r" % (expr,))
Armin Rigofd163f92005-12-29 15:59:19 +00004264
Georg Brandl48545522008-02-02 10:12:36 +00004265 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of
4266 # TypeErrors
4267 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4268 # ValueErrors instead of TypeErrors
4269 for metaclass in [type, types.ClassType]:
4270 for name, expr, iexpr in [
4271 ('__add__', 'x + y', 'x += y'),
4272 ('__sub__', 'x - y', 'x -= y'),
4273 ('__mul__', 'x * y', 'x *= y'),
4274 ('__truediv__', 'operator.truediv(x, y)', None),
4275 ('__floordiv__', 'operator.floordiv(x, y)', None),
4276 ('__div__', 'x / y', 'x /= y'),
4277 ('__mod__', 'x % y', 'x %= y'),
4278 ('__divmod__', 'divmod(x, y)', None),
4279 ('__pow__', 'x ** y', 'x **= y'),
4280 ('__lshift__', 'x << y', 'x <<= y'),
4281 ('__rshift__', 'x >> y', 'x >>= y'),
4282 ('__and__', 'x & y', 'x &= y'),
4283 ('__or__', 'x | y', 'x |= y'),
4284 ('__xor__', 'x ^ y', 'x ^= y'),
4285 ('__coerce__', 'coerce(x, y)', None)]:
4286 if name == '__coerce__':
4287 rname = name
4288 else:
4289 rname = '__r' + name[2:]
4290 A = metaclass('A', (), {name: specialmethod})
4291 B = metaclass('B', (), {rname: specialmethod})
4292 a = A()
4293 b = B()
4294 check(expr, a, a)
4295 check(expr, a, b)
4296 check(expr, b, a)
4297 check(expr, b, b)
4298 check(expr, a, N1)
4299 check(expr, a, N2)
4300 check(expr, N1, b)
4301 check(expr, N2, b)
4302 if iexpr:
4303 check(iexpr, a, a)
4304 check(iexpr, a, b)
4305 check(iexpr, b, a)
4306 check(iexpr, b, b)
4307 check(iexpr, a, N1)
4308 check(iexpr, a, N2)
4309 iname = '__i' + name[2:]
4310 C = metaclass('C', (), {iname: specialmethod})
4311 c = C()
4312 check(iexpr, c, a)
4313 check(iexpr, c, b)
4314 check(iexpr, c, N1)
4315 check(iexpr, c, N2)
Georg Brandl0fca97a2007-03-05 22:28:08 +00004316
Georg Brandl48545522008-02-02 10:12:36 +00004317 def test_assign_slice(self):
4318 # ceval.c's assign_slice used to check for
4319 # tp->tp_as_sequence->sq_slice instead of
4320 # tp->tp_as_sequence->sq_ass_slice
Georg Brandl0fca97a2007-03-05 22:28:08 +00004321
Georg Brandl48545522008-02-02 10:12:36 +00004322 class C(object):
4323 def __setslice__(self, start, stop, value):
4324 self.value = value
Georg Brandl0fca97a2007-03-05 22:28:08 +00004325
Georg Brandl48545522008-02-02 10:12:36 +00004326 c = C()
4327 c[1:2] = 3
4328 self.assertEqual(c.value, 3)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004329
Benjamin Peterson9adae2e2008-11-17 22:44:30 +00004330 def test_getattr_hooks(self):
4331 # issue 4230
4332
4333 class Descriptor(object):
4334 counter = 0
4335 def __get__(self, obj, objtype=None):
4336 def getter(name):
4337 self.counter += 1
4338 raise AttributeError(name)
4339 return getter
4340
4341 descr = Descriptor()
4342 class A(object):
4343 __getattribute__ = descr
4344 class B(object):
4345 __getattr__ = descr
4346 class C(object):
4347 __getattribute__ = descr
4348 __getattr__ = descr
4349
4350 self.assertRaises(AttributeError, getattr, A(), "attr")
4351 self.assertEquals(descr.counter, 1)
4352 self.assertRaises(AttributeError, getattr, B(), "attr")
4353 self.assertEquals(descr.counter, 2)
4354 self.assertRaises(AttributeError, getattr, C(), "attr")
4355 self.assertEquals(descr.counter, 4)
4356
4357 import gc
4358 class EvilGetattribute(object):
4359 # This used to segfault
4360 def __getattr__(self, name):
4361 raise AttributeError(name)
4362 def __getattribute__(self, name):
4363 del EvilGetattribute.__getattr__
4364 for i in range(5):
4365 gc.collect()
4366 raise AttributeError(name)
4367
4368 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4369
Guido van Rossum9acc3872008-01-23 23:23:43 +00004370
Georg Brandl48545522008-02-02 10:12:36 +00004371class DictProxyTests(unittest.TestCase):
4372 def setUp(self):
4373 class C(object):
4374 def meth(self):
4375 pass
4376 self.C = C
Guido van Rossum9acc3872008-01-23 23:23:43 +00004377
Georg Brandl48545522008-02-02 10:12:36 +00004378 def test_iter_keys(self):
4379 # Testing dict-proxy iterkeys...
4380 keys = [ key for key in self.C.__dict__.iterkeys() ]
4381 keys.sort()
4382 self.assertEquals(keys, ['__dict__', '__doc__', '__module__',
4383 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004384
Georg Brandl48545522008-02-02 10:12:36 +00004385 def test_iter_values(self):
4386 # Testing dict-proxy itervalues...
4387 values = [ values for values in self.C.__dict__.itervalues() ]
4388 self.assertEqual(len(values), 5)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004389
Georg Brandl48545522008-02-02 10:12:36 +00004390 def test_iter_items(self):
4391 # Testing dict-proxy iteritems...
4392 keys = [ key for (key, value) in self.C.__dict__.iteritems() ]
4393 keys.sort()
4394 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4395 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004396
Georg Brandl48545522008-02-02 10:12:36 +00004397 def test_dict_type_with_metaclass(self):
4398 # Testing type of __dict__ when __metaclass__ set...
4399 class B(object):
4400 pass
4401 class M(type):
4402 pass
4403 class C:
4404 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4405 __metaclass__ = M
4406 self.assertEqual(type(C.__dict__), type(B.__dict__))
Guido van Rossum9acc3872008-01-23 23:23:43 +00004407
Guido van Rossum9acc3872008-01-23 23:23:43 +00004408
Georg Brandl48545522008-02-02 10:12:36 +00004409class PTypesLongInitTest(unittest.TestCase):
4410 # This is in its own TestCase so that it can be run before any other tests.
4411 def test_pytype_long_ready(self):
4412 # Testing SF bug 551412 ...
Guido van Rossum9acc3872008-01-23 23:23:43 +00004413
Georg Brandl48545522008-02-02 10:12:36 +00004414 # This dumps core when SF bug 551412 isn't fixed --
4415 # but only when test_descr.py is run separately.
4416 # (That can't be helped -- as soon as PyType_Ready()
4417 # is called for PyLong_Type, the bug is gone.)
4418 class UserLong(object):
4419 def __pow__(self, *args):
4420 pass
4421 try:
4422 pow(0L, UserLong(), 0L)
4423 except:
4424 pass
Guido van Rossum9acc3872008-01-23 23:23:43 +00004425
Georg Brandl48545522008-02-02 10:12:36 +00004426 # Another segfault only when run early
4427 # (before PyType_Ready(tuple) is called)
4428 type.mro(tuple)
Guido van Rossum37edeab2008-01-24 17:58:05 +00004429
4430
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004431def test_main():
Georg Brandl48545522008-02-02 10:12:36 +00004432 # Run all local test cases, with PTypesLongInitTest first.
4433 test_support.run_unittest(PTypesLongInitTest, OperatorsTest,
4434 ClassPropertiesAndMethods, DictProxyTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004435
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004436if __name__ == "__main__":
4437 test_main()