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