blob: 4558b9835fe7fd5a2e23f50f504bf88bece0dcd3 [file] [log] [blame]
Benjamin Petersonae937c02009-04-18 20:54:08 +00001import builtins
Guido van Rossum360e4b82007-05-14 22:51:27 +00002import types
Georg Brandl479a7e72008-02-05 18:13:15 +00003import unittest
4import warnings
Tim Peters4d9b4662002-04-16 01:59:17 +00005
Georg Brandl479a7e72008-02-05 18:13:15 +00006from copy import deepcopy
Benjamin Petersonee8712c2008-05-20 21:35:26 +00007from test import support
Guido van Rossum875eeaa2001-10-11 18:33:53 +00008
Tim Peters6d6c1a32001-08-02 04:15:00 +00009
Georg Brandl479a7e72008-02-05 18:13:15 +000010class OperatorsTest(unittest.TestCase):
Tim Peters3caca232001-12-06 06:23:26 +000011
Georg Brandl479a7e72008-02-05 18:13:15 +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 Peters6d6c1a32001-08-02 04:15:00 +000034
Georg Brandl479a7e72008-02-05 18:13:15 +000035 for name, expr in list(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 Peters6d6c1a32001-08-02 04:15:00 +000041
Georg Brandl479a7e72008-02-05 18:13:15 +000042 self.unops = {
43 'pos': '+',
44 'neg': '-',
45 'abs': 'abs',
46 'invert': '~',
47 'int': 'int',
48 'float': 'float',
49 'oct': 'oct',
50 'hex': 'hex',
51 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000052
Georg Brandl479a7e72008-02-05 18:13:15 +000053 for name, expr in list(self.unops.items()):
54 if expr.islower():
55 expr = expr + "(a)"
56 else:
57 expr = '%s a' % expr
58 self.unops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000059
Georg Brandl479a7e72008-02-05 18:13:15 +000060 def unop_test(self, a, res, expr="len(a)", meth="__len__"):
61 d = {'a': a}
62 self.assertEqual(eval(expr, d), res)
63 t = type(a)
64 m = getattr(t, meth)
Tim Peters6d6c1a32001-08-02 04:15:00 +000065
Georg Brandl479a7e72008-02-05 18:13:15 +000066 # Find method in parent class
67 while meth not in t.__dict__:
68 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000069 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
70 # method object; the getattr() below obtains its underlying function.
71 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000072 self.assertEqual(m(a), res)
73 bm = getattr(a, meth)
74 self.assertEqual(bm(), res)
Tim Peters2f93e282001-10-04 05:27:00 +000075
Georg Brandl479a7e72008-02-05 18:13:15 +000076 def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
77 d = {'a': a, 'b': b}
Tim Peters2f93e282001-10-04 05:27:00 +000078
Georg Brandl479a7e72008-02-05 18:13:15 +000079 # XXX Hack so this passes before 2.3 when -Qnew is specified.
80 if meth == "__div__" and 1/2 == 0.5:
81 meth = "__truediv__"
Tim Peters2f93e282001-10-04 05:27:00 +000082
Georg Brandl479a7e72008-02-05 18:13:15 +000083 if meth == '__divmod__': pass
Tim Peters2f93e282001-10-04 05:27:00 +000084
Georg Brandl479a7e72008-02-05 18:13:15 +000085 self.assertEqual(eval(expr, d), res)
86 t = type(a)
87 m = getattr(t, meth)
88 while meth not in t.__dict__:
89 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000090 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
91 # method object; the getattr() below obtains its underlying function.
92 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000093 self.assertEqual(m(a, b), res)
94 bm = getattr(a, meth)
95 self.assertEqual(bm(b), res)
Tim Peters2f93e282001-10-04 05:27:00 +000096
Georg Brandl479a7e72008-02-05 18:13:15 +000097 def sliceop_test(self, a, b, c, res, expr="a[b:c]", meth="__getitem__"):
98 d = {'a': a, 'b': b, 'c': c}
99 self.assertEqual(eval(expr, d), res)
100 t = type(a)
101 m = getattr(t, meth)
102 while meth not in t.__dict__:
103 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000104 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
105 # method object; the getattr() below obtains its underlying function.
106 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000107 self.assertEqual(m(a, slice(b, c)), res)
108 bm = getattr(a, meth)
109 self.assertEqual(bm(slice(b, c)), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000110
Georg Brandl479a7e72008-02-05 18:13:15 +0000111 def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
112 d = {'a': deepcopy(a), 'b': b}
113 exec(stmt, d)
114 self.assertEqual(d['a'], res)
115 t = type(a)
116 m = getattr(t, meth)
117 while meth not in t.__dict__:
118 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000119 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
120 # method object; the getattr() below obtains its underlying function.
121 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000122 d['a'] = deepcopy(a)
123 m(d['a'], b)
124 self.assertEqual(d['a'], res)
125 d['a'] = deepcopy(a)
126 bm = getattr(d['a'], meth)
127 bm(b)
128 self.assertEqual(d['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000129
Georg Brandl479a7e72008-02-05 18:13:15 +0000130 def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
131 d = {'a': deepcopy(a), 'b': b, 'c': c}
132 exec(stmt, d)
133 self.assertEqual(d['a'], res)
134 t = type(a)
135 m = getattr(t, meth)
136 while meth not in t.__dict__:
137 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000138 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
139 # method object; the getattr() below obtains its underlying function.
140 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000141 d['a'] = deepcopy(a)
142 m(d['a'], b, c)
143 self.assertEqual(d['a'], res)
144 d['a'] = deepcopy(a)
145 bm = getattr(d['a'], meth)
146 bm(b, c)
147 self.assertEqual(d['a'], res)
148
149 def setsliceop_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setitem__"):
150 dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
151 exec(stmt, dictionary)
152 self.assertEqual(dictionary['a'], res)
153 t = type(a)
154 while meth not in t.__dict__:
155 t = t.__bases__[0]
156 m = getattr(t, meth)
Benjamin Petersone549ead2009-03-28 21:42:05 +0000157 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
158 # method object; the getattr() below obtains its underlying function.
159 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000160 dictionary['a'] = deepcopy(a)
161 m(dictionary['a'], slice(b, c), d)
162 self.assertEqual(dictionary['a'], res)
163 dictionary['a'] = deepcopy(a)
164 bm = getattr(dictionary['a'], meth)
165 bm(slice(b, c), d)
166 self.assertEqual(dictionary['a'], res)
167
168 def test_lists(self):
169 # Testing list operations...
170 # Asserts are within individual test methods
171 self.binop_test([1], [2], [1,2], "a+b", "__add__")
172 self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
173 self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
174 self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
175 self.sliceop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getitem__")
176 self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
177 self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
178 self.unop_test([1,2,3], 3, "len(a)", "__len__")
179 self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
180 self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
181 self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
182 self.setsliceop_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
183 "__setitem__")
184
185 def test_dicts(self):
186 # Testing dict operations...
Georg Brandl479a7e72008-02-05 18:13:15 +0000187 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 list(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 list(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 list(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).__bool__(), 1)
237 self.assertEqual((0).__bool__(), 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(5), 5)
Tim Peters25786c02001-09-02 08:22:48 +0000243 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000244 C() + ""
Tim Peters25786c02001-09-02 08:22:48 +0000245 except TypeError:
246 pass
247 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000248 self.fail("NotImplemented should have caused TypeError")
Tim Peters25786c02001-09-02 08:22:48 +0000249
Georg Brandl479a7e72008-02-05 18:13:15 +0000250 def test_longs(self):
251 # Testing long operations...
252 self.number_operators(100, 3)
Tim Peters25786c02001-09-02 08:22:48 +0000253
Georg Brandl479a7e72008-02-05 18:13:15 +0000254 def test_floats(self):
255 # Testing float operations...
256 self.number_operators(100.0, 3.0)
Tim Peters25786c02001-09-02 08:22:48 +0000257
Georg Brandl479a7e72008-02-05 18:13:15 +0000258 def test_complexes(self):
259 # Testing complex operations...
260 self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
261 'int', 'long', 'float',
262 'divmod', 'mod'])
Tim Peters25786c02001-09-02 08:22:48 +0000263
Georg Brandl479a7e72008-02-05 18:13:15 +0000264 class Number(complex):
265 __slots__ = ['prec']
266 def __new__(cls, *args, **kwds):
267 result = complex.__new__(cls, *args)
268 result.prec = kwds.get('prec', 12)
269 return result
270 def __repr__(self):
271 prec = self.prec
272 if self.imag == 0.0:
273 return "%.*g" % (prec, self.real)
274 if self.real == 0.0:
275 return "%.*gj" % (prec, self.imag)
276 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
277 __str__ = __repr__
Tim Peters25786c02001-09-02 08:22:48 +0000278
Georg Brandl479a7e72008-02-05 18:13:15 +0000279 a = Number(3.14, prec=6)
280 self.assertEqual(repr(a), "3.14")
281 self.assertEqual(a.prec, 6)
Tim Peters1fc240e2001-10-26 05:06:50 +0000282
Georg Brandl479a7e72008-02-05 18:13:15 +0000283 a = Number(a, prec=2)
284 self.assertEqual(repr(a), "3.1")
285 self.assertEqual(a.prec, 2)
Tim Peters1fc240e2001-10-26 05:06:50 +0000286
Georg Brandl479a7e72008-02-05 18:13:15 +0000287 a = Number(234.5)
288 self.assertEqual(repr(a), "234.5")
289 self.assertEqual(a.prec, 12)
Tim Peters1fc240e2001-10-26 05:06:50 +0000290
Benjamin Petersone549ead2009-03-28 21:42:05 +0000291 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000292 def test_spam_lists(self):
293 # Testing spamlist operations...
294 import copy, xxsubtype as spam
295
296 def spamlist(l, memo=None):
297 import xxsubtype as spam
298 return spam.spamlist(l)
299
300 # This is an ugly hack:
301 copy._deepcopy_dispatch[spam.spamlist] = spamlist
302
303 self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
304 "__add__")
305 self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
306 self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
307 self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
308 self.sliceop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
309 "__getitem__")
310 self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
311 "__iadd__")
312 self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
313 "__imul__")
314 self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
315 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
316 "__mul__")
317 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
318 "__rmul__")
319 self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
320 "__setitem__")
321 self.setsliceop_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
322 spamlist([1,5,6,4]), "a[b:c]=d", "__setitem__")
323 # Test subclassing
324 class C(spam.spamlist):
325 def foo(self): return 1
326 a = C()
327 self.assertEqual(a, [])
328 self.assertEqual(a.foo(), 1)
329 a.append(100)
330 self.assertEqual(a, [100])
331 self.assertEqual(a.getstate(), 0)
332 a.setstate(42)
333 self.assertEqual(a.getstate(), 42)
334
Benjamin Petersone549ead2009-03-28 21:42:05 +0000335 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000336 def test_spam_dicts(self):
337 # Testing spamdict operations...
338 import copy, xxsubtype as spam
339 def spamdict(d, memo=None):
340 import xxsubtype as spam
341 sd = spam.spamdict()
342 for k, v in list(d.items()):
343 sd[k] = v
344 return sd
345 # This is an ugly hack:
346 copy._deepcopy_dispatch[spam.spamdict] = spamdict
347
Georg Brandl479a7e72008-02-05 18:13:15 +0000348 self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
349 self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
350 self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
351 d = spamdict({1:2,3:4})
352 l1 = []
353 for i in list(d.keys()):
354 l1.append(i)
355 l = []
356 for i in iter(d):
357 l.append(i)
358 self.assertEqual(l, l1)
359 l = []
360 for i in d.__iter__():
361 l.append(i)
362 self.assertEqual(l, l1)
363 l = []
364 for i in type(spamdict({})).__iter__(d):
365 l.append(i)
366 self.assertEqual(l, l1)
367 straightd = {1:2, 3:4}
368 spamd = spamdict(straightd)
369 self.unop_test(spamd, 2, "len(a)", "__len__")
370 self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
371 self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
372 "a[b]=c", "__setitem__")
373 # Test subclassing
374 class C(spam.spamdict):
375 def foo(self): return 1
376 a = C()
377 self.assertEqual(list(a.items()), [])
378 self.assertEqual(a.foo(), 1)
379 a['foo'] = 'bar'
380 self.assertEqual(list(a.items()), [('foo', 'bar')])
381 self.assertEqual(a.getstate(), 0)
382 a.setstate(100)
383 self.assertEqual(a.getstate(), 100)
384
385class ClassPropertiesAndMethods(unittest.TestCase):
386
387 def test_python_dicts(self):
388 # Testing Python subclass of dict...
389 self.assert_(issubclass(dict, dict))
390 self.assert_(isinstance({}, dict))
391 d = dict()
392 self.assertEqual(d, {})
393 self.assert_(d.__class__ is dict)
394 self.assert_(isinstance(d, dict))
395 class C(dict):
396 state = -1
397 def __init__(self_local, *a, **kw):
398 if a:
399 self.assertEqual(len(a), 1)
400 self_local.state = a[0]
401 if kw:
402 for k, v in list(kw.items()):
403 self_local[v] = k
404 def __getitem__(self, key):
405 return self.get(key, 0)
406 def __setitem__(self_local, key, value):
407 self.assert_(isinstance(key, type(0)))
408 dict.__setitem__(self_local, key, value)
409 def setstate(self, state):
410 self.state = state
411 def getstate(self):
412 return self.state
413 self.assert_(issubclass(C, dict))
414 a1 = C(12)
415 self.assertEqual(a1.state, 12)
416 a2 = C(foo=1, bar=2)
417 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
418 a = C()
419 self.assertEqual(a.state, -1)
420 self.assertEqual(a.getstate(), -1)
421 a.setstate(0)
422 self.assertEqual(a.state, 0)
423 self.assertEqual(a.getstate(), 0)
424 a.setstate(10)
425 self.assertEqual(a.state, 10)
426 self.assertEqual(a.getstate(), 10)
427 self.assertEqual(a[42], 0)
428 a[42] = 24
429 self.assertEqual(a[42], 24)
430 N = 50
431 for i in range(N):
432 a[i] = C()
433 for j in range(N):
434 a[i][j] = i*j
435 for i in range(N):
436 for j in range(N):
437 self.assertEqual(a[i][j], i*j)
438
439 def test_python_lists(self):
440 # Testing Python subclass of list...
441 class C(list):
442 def __getitem__(self, i):
443 if isinstance(i, slice):
444 return i.start, i.stop
445 return list.__getitem__(self, i) + 100
446 a = C()
447 a.extend([0,1,2])
448 self.assertEqual(a[0], 100)
449 self.assertEqual(a[1], 101)
450 self.assertEqual(a[2], 102)
451 self.assertEqual(a[100:200], (100,200))
452
453 def test_metaclass(self):
Georg Brandle81f5ef2008-05-27 20:34:09 +0000454 # Testing metaclasses...
Georg Brandl479a7e72008-02-05 18:13:15 +0000455 class C(metaclass=type):
456 def __init__(self):
457 self.__state = 0
458 def getstate(self):
459 return self.__state
460 def setstate(self, state):
461 self.__state = state
462 a = C()
463 self.assertEqual(a.getstate(), 0)
464 a.setstate(10)
465 self.assertEqual(a.getstate(), 10)
466 class _metaclass(type):
467 def myself(cls): return cls
468 class D(metaclass=_metaclass):
469 pass
470 self.assertEqual(D.myself(), D)
471 d = D()
472 self.assertEqual(d.__class__, D)
473 class M1(type):
474 def __new__(cls, name, bases, dict):
475 dict['__spam__'] = 1
476 return type.__new__(cls, name, bases, dict)
477 class C(metaclass=M1):
478 pass
479 self.assertEqual(C.__spam__, 1)
480 c = C()
481 self.assertEqual(c.__spam__, 1)
482
483 class _instance(object):
484 pass
485 class M2(object):
486 @staticmethod
487 def __new__(cls, name, bases, dict):
488 self = object.__new__(cls)
489 self.name = name
490 self.bases = bases
491 self.dict = dict
492 return self
493 def __call__(self):
494 it = _instance()
495 # Early binding of methods
496 for key in self.dict:
497 if key.startswith("__"):
498 continue
499 setattr(it, key, self.dict[key].__get__(it, self))
500 return it
501 class C(metaclass=M2):
502 def spam(self):
503 return 42
504 self.assertEqual(C.name, 'C')
505 self.assertEqual(C.bases, ())
506 self.assert_('spam' in C.dict)
507 c = C()
508 self.assertEqual(c.spam(), 42)
509
510 # More metaclass examples
511
512 class autosuper(type):
513 # Automatically add __super to the class
514 # This trick only works for dynamic classes
515 def __new__(metaclass, name, bases, dict):
516 cls = super(autosuper, metaclass).__new__(metaclass,
517 name, bases, dict)
518 # Name mangling for __super removes leading underscores
519 while name[:1] == "_":
520 name = name[1:]
521 if name:
522 name = "_%s__super" % name
523 else:
524 name = "__super"
525 setattr(cls, name, super(cls))
526 return cls
527 class A(metaclass=autosuper):
528 def meth(self):
529 return "A"
530 class B(A):
531 def meth(self):
532 return "B" + self.__super.meth()
533 class C(A):
534 def meth(self):
535 return "C" + self.__super.meth()
536 class D(C, B):
537 def meth(self):
538 return "D" + self.__super.meth()
539 self.assertEqual(D().meth(), "DCBA")
540 class E(B, C):
541 def meth(self):
542 return "E" + self.__super.meth()
543 self.assertEqual(E().meth(), "EBCA")
544
545 class autoproperty(type):
546 # Automatically create property attributes when methods
547 # named _get_x and/or _set_x are found
548 def __new__(metaclass, name, bases, dict):
549 hits = {}
550 for key, val in dict.items():
551 if key.startswith("_get_"):
552 key = key[5:]
553 get, set = hits.get(key, (None, None))
554 get = val
555 hits[key] = get, set
556 elif key.startswith("_set_"):
557 key = key[5:]
558 get, set = hits.get(key, (None, None))
559 set = val
560 hits[key] = get, set
561 for key, (get, set) in hits.items():
562 dict[key] = property(get, set)
563 return super(autoproperty, metaclass).__new__(metaclass,
564 name, bases, dict)
565 class A(metaclass=autoproperty):
566 def _get_x(self):
567 return -self.__x
568 def _set_x(self, x):
569 self.__x = -x
570 a = A()
571 self.assert_(not hasattr(a, "x"))
572 a.x = 12
573 self.assertEqual(a.x, 12)
574 self.assertEqual(a._A__x, -12)
575
576 class multimetaclass(autoproperty, autosuper):
577 # Merge of multiple cooperating metaclasses
578 pass
579 class A(metaclass=multimetaclass):
580 def _get_x(self):
581 return "A"
582 class B(A):
583 def _get_x(self):
584 return "B" + self.__super._get_x()
585 class C(A):
586 def _get_x(self):
587 return "C" + self.__super._get_x()
588 class D(C, B):
589 def _get_x(self):
590 return "D" + self.__super._get_x()
591 self.assertEqual(D().x, "DCBA")
592
593 # Make sure type(x) doesn't call x.__class__.__init__
594 class T(type):
595 counter = 0
596 def __init__(self, *args):
597 T.counter += 1
598 class C(metaclass=T):
599 pass
600 self.assertEqual(T.counter, 1)
601 a = C()
602 self.assertEqual(type(a), C)
603 self.assertEqual(T.counter, 1)
604
605 class C(object): pass
606 c = C()
607 try: c()
608 except TypeError: pass
609 else: self.fail("calling object w/o call method should raise "
610 "TypeError")
611
612 # Testing code to find most derived baseclass
613 class A(type):
614 def __new__(*args, **kwargs):
615 return type.__new__(*args, **kwargs)
616
617 class B(object):
618 pass
619
620 class C(object, metaclass=A):
621 pass
622
623 # The most derived metaclass of D is A rather than type.
624 class D(B, C):
625 pass
626
627 def test_module_subclasses(self):
628 # Testing Python subclass of module...
629 log = []
630 import types, sys
631 MT = type(sys)
632 class MM(MT):
633 def __init__(self, name):
634 MT.__init__(self, name)
635 def __getattribute__(self, name):
636 log.append(("getattr", name))
637 return MT.__getattribute__(self, name)
638 def __setattr__(self, name, value):
639 log.append(("setattr", name, value))
640 MT.__setattr__(self, name, value)
641 def __delattr__(self, name):
642 log.append(("delattr", name))
643 MT.__delattr__(self, name)
644 a = MM("a")
645 a.foo = 12
646 x = a.foo
647 del a.foo
648 self.assertEqual(log, [("setattr", "foo", 12),
649 ("getattr", "foo"),
650 ("delattr", "foo")])
651
652 # http://python.org/sf/1174712
Tim Peters1fc240e2001-10-26 05:06:50 +0000653 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000654 class Module(types.ModuleType, str):
655 pass
656 except TypeError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000657 pass
658 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000659 self.fail("inheriting from ModuleType and str at the same time "
660 "should fail")
Tim Peters1fc240e2001-10-26 05:06:50 +0000661
Georg Brandl479a7e72008-02-05 18:13:15 +0000662 def test_multiple_inheritance(self):
663 # Testing multiple inheritance...
664 class C(object):
665 def __init__(self):
666 self.__state = 0
667 def getstate(self):
668 return self.__state
669 def setstate(self, state):
670 self.__state = state
671 a = C()
672 self.assertEqual(a.getstate(), 0)
673 a.setstate(10)
674 self.assertEqual(a.getstate(), 10)
675 class D(dict, C):
676 def __init__(self):
677 type({}).__init__(self)
678 C.__init__(self)
679 d = D()
680 self.assertEqual(list(d.keys()), [])
681 d["hello"] = "world"
682 self.assertEqual(list(d.items()), [("hello", "world")])
683 self.assertEqual(d["hello"], "world")
684 self.assertEqual(d.getstate(), 0)
685 d.setstate(10)
686 self.assertEqual(d.getstate(), 10)
687 self.assertEqual(D.__mro__, (D, dict, C, object))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000688
Georg Brandl479a7e72008-02-05 18:13:15 +0000689 # SF bug #442833
690 class Node(object):
691 def __int__(self):
692 return int(self.foo())
693 def foo(self):
694 return "23"
695 class Frag(Node, list):
696 def foo(self):
697 return "42"
698 self.assertEqual(Node().__int__(), 23)
699 self.assertEqual(int(Node()), 23)
700 self.assertEqual(Frag().__int__(), 42)
701 self.assertEqual(int(Frag()), 42)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000702
Georg Brandl479a7e72008-02-05 18:13:15 +0000703 def test_diamond_inheritence(self):
704 # Testing multiple inheritance special cases...
705 class A(object):
706 def spam(self): return "A"
707 self.assertEqual(A().spam(), "A")
708 class B(A):
709 def boo(self): return "B"
710 def spam(self): return "B"
711 self.assertEqual(B().spam(), "B")
712 self.assertEqual(B().boo(), "B")
713 class C(A):
714 def boo(self): return "C"
715 self.assertEqual(C().spam(), "A")
716 self.assertEqual(C().boo(), "C")
717 class D(B, C): pass
718 self.assertEqual(D().spam(), "B")
719 self.assertEqual(D().boo(), "B")
720 self.assertEqual(D.__mro__, (D, B, C, A, object))
721 class E(C, B): pass
722 self.assertEqual(E().spam(), "B")
723 self.assertEqual(E().boo(), "C")
724 self.assertEqual(E.__mro__, (E, C, B, A, object))
725 # MRO order disagreement
726 try:
727 class F(D, E): pass
728 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000729 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000730 else:
731 self.fail("expected MRO order disagreement (F)")
732 try:
733 class G(E, D): pass
734 except TypeError:
735 pass
736 else:
737 self.fail("expected MRO order disagreement (G)")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000738
Georg Brandl479a7e72008-02-05 18:13:15 +0000739 # see thread python-dev/2002-October/029035.html
740 def test_ex5_from_c3_switch(self):
741 # Testing ex5 from C3 switch discussion...
742 class A(object): pass
743 class B(object): pass
744 class C(object): pass
745 class X(A): pass
746 class Y(A): pass
747 class Z(X,B,Y,C): pass
748 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000749
Georg Brandl479a7e72008-02-05 18:13:15 +0000750 # see "A Monotonic Superclass Linearization for Dylan",
751 # by Kim Barrett et al. (OOPSLA 1996)
752 def test_monotonicity(self):
753 # Testing MRO monotonicity...
754 class Boat(object): pass
755 class DayBoat(Boat): pass
756 class WheelBoat(Boat): pass
757 class EngineLess(DayBoat): pass
758 class SmallMultihull(DayBoat): pass
759 class PedalWheelBoat(EngineLess,WheelBoat): pass
760 class SmallCatamaran(SmallMultihull): pass
761 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
Guido van Rossume45763a2001-08-10 21:28:46 +0000762
Georg Brandl479a7e72008-02-05 18:13:15 +0000763 self.assertEqual(PedalWheelBoat.__mro__,
764 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
765 self.assertEqual(SmallCatamaran.__mro__,
766 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
767 self.assertEqual(Pedalo.__mro__,
768 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
769 SmallMultihull, DayBoat, WheelBoat, Boat, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000770
Georg Brandl479a7e72008-02-05 18:13:15 +0000771 # see "A Monotonic Superclass Linearization for Dylan",
772 # by Kim Barrett et al. (OOPSLA 1996)
773 def test_consistency_with_epg(self):
774 # Testing consistentcy with EPG...
775 class Pane(object): pass
776 class ScrollingMixin(object): pass
777 class EditingMixin(object): pass
778 class ScrollablePane(Pane,ScrollingMixin): pass
779 class EditablePane(Pane,EditingMixin): pass
780 class EditableScrollablePane(ScrollablePane,EditablePane): pass
Guido van Rossum9a818922002-11-14 19:50:14 +0000781
Georg Brandl479a7e72008-02-05 18:13:15 +0000782 self.assertEqual(EditableScrollablePane.__mro__,
783 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
784 ScrollingMixin, EditingMixin, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000785
Georg Brandl479a7e72008-02-05 18:13:15 +0000786 def test_mro_disagreement(self):
787 # Testing error messages for MRO disagreement...
788 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000789order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000790
Georg Brandl479a7e72008-02-05 18:13:15 +0000791 def raises(exc, expected, callable, *args):
Guido van Rossum58da9312007-11-10 23:39:45 +0000792 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000793 callable(*args)
794 except exc as msg:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000795 # the exact msg is generally considered an impl detail
796 if support.check_impl_detail():
797 if not str(msg).startswith(expected):
798 self.fail("Message %r, expected %r" %
799 (str(msg), expected))
Georg Brandl479a7e72008-02-05 18:13:15 +0000800 else:
801 self.fail("Expected %s" % exc)
Guido van Rossum58da9312007-11-10 23:39:45 +0000802
Georg Brandl479a7e72008-02-05 18:13:15 +0000803 class A(object): pass
804 class B(A): pass
805 class C(object): pass
Christian Heimes9a371592007-12-28 14:08:13 +0000806
Georg Brandl479a7e72008-02-05 18:13:15 +0000807 # Test some very simple errors
808 raises(TypeError, "duplicate base class A",
809 type, "X", (A, A), {})
810 raises(TypeError, mro_err_msg,
811 type, "X", (A, B), {})
812 raises(TypeError, mro_err_msg,
813 type, "X", (A, C, B), {})
814 # Test a slightly more complex error
815 class GridLayout(object): pass
816 class HorizontalGrid(GridLayout): pass
817 class VerticalGrid(GridLayout): pass
818 class HVGrid(HorizontalGrid, VerticalGrid): pass
819 class VHGrid(VerticalGrid, HorizontalGrid): pass
820 raises(TypeError, mro_err_msg,
821 type, "ConfusedGrid", (HVGrid, VHGrid), {})
Guido van Rossum58da9312007-11-10 23:39:45 +0000822
Georg Brandl479a7e72008-02-05 18:13:15 +0000823 def test_object_class(self):
824 # Testing object class...
825 a = object()
826 self.assertEqual(a.__class__, object)
827 self.assertEqual(type(a), object)
828 b = object()
829 self.assertNotEqual(a, b)
830 self.assertFalse(hasattr(a, "foo"))
Tim Peters808b94e2001-09-13 19:33:07 +0000831 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000832 a.foo = 12
833 except (AttributeError, TypeError):
Tim Peters808b94e2001-09-13 19:33:07 +0000834 pass
835 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000836 self.fail("object() should not allow setting a foo attribute")
837 self.assertFalse(hasattr(object(), "__dict__"))
Tim Peters561f8992001-09-13 19:36:36 +0000838
Georg Brandl479a7e72008-02-05 18:13:15 +0000839 class Cdict(object):
Guido van Rossum5c294fb2001-09-25 03:43:42 +0000840 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000841 x = Cdict()
842 self.assertEqual(x.__dict__, {})
843 x.foo = 1
844 self.assertEqual(x.foo, 1)
845 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossumd8faa362007-04-27 19:54:29 +0000846
Georg Brandl479a7e72008-02-05 18:13:15 +0000847 def test_slots(self):
848 # Testing __slots__...
849 class C0(object):
850 __slots__ = []
851 x = C0()
852 self.assertFalse(hasattr(x, "__dict__"))
853 self.assertFalse(hasattr(x, "foo"))
854
855 class C1(object):
856 __slots__ = ['a']
857 x = C1()
858 self.assertFalse(hasattr(x, "__dict__"))
859 self.assertFalse(hasattr(x, "a"))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000860 x.a = 1
Georg Brandl479a7e72008-02-05 18:13:15 +0000861 self.assertEqual(x.a, 1)
862 x.a = None
863 self.assertEqual(x.a, None)
864 del x.a
865 self.assertFalse(hasattr(x, "a"))
Guido van Rossum5c294fb2001-09-25 03:43:42 +0000866
Georg Brandl479a7e72008-02-05 18:13:15 +0000867 class C3(object):
868 __slots__ = ['a', 'b', 'c']
869 x = C3()
870 self.assertFalse(hasattr(x, "__dict__"))
871 self.assertFalse(hasattr(x, 'a'))
872 self.assertFalse(hasattr(x, 'b'))
873 self.assertFalse(hasattr(x, 'c'))
874 x.a = 1
875 x.b = 2
876 x.c = 3
877 self.assertEqual(x.a, 1)
878 self.assertEqual(x.b, 2)
879 self.assertEqual(x.c, 3)
880
881 class C4(object):
882 """Validate name mangling"""
883 __slots__ = ['__a']
884 def __init__(self, value):
885 self.__a = value
886 def get(self):
887 return self.__a
888 x = C4(5)
889 self.assertFalse(hasattr(x, '__dict__'))
890 self.assertFalse(hasattr(x, '__a'))
891 self.assertEqual(x.get(), 5)
Guido van Rossum6661be32001-10-26 04:26:12 +0000892 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000893 x.__a = 6
894 except AttributeError:
Guido van Rossum6661be32001-10-26 04:26:12 +0000895 pass
896 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000897 self.fail("Double underscored names not mangled")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000898
Georg Brandl479a7e72008-02-05 18:13:15 +0000899 # Make sure slot names are proper identifiers
Guido van Rossum360e4b82007-05-14 22:51:27 +0000900 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000901 class C(object):
902 __slots__ = [None]
Guido van Rossum360e4b82007-05-14 22:51:27 +0000903 except TypeError:
904 pass
905 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000906 self.fail("[None] slots not caught")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000907 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000908 class C(object):
909 __slots__ = ["foo bar"]
910 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000911 pass
912 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000913 self.fail("['foo bar'] slots not caught")
914 try:
915 class C(object):
916 __slots__ = ["foo\0bar"]
917 except TypeError:
918 pass
919 else:
920 self.fail("['foo\\0bar'] slots not caught")
921 try:
922 class C(object):
923 __slots__ = ["1"]
924 except TypeError:
925 pass
926 else:
927 self.fail("['1'] slots not caught")
928 try:
929 class C(object):
930 __slots__ = [""]
931 except TypeError:
932 pass
933 else:
934 self.fail("[''] slots not caught")
935 class C(object):
936 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
937 # XXX(nnorwitz): was there supposed to be something tested
938 # from the class above?
Guido van Rossum360e4b82007-05-14 22:51:27 +0000939
Georg Brandl479a7e72008-02-05 18:13:15 +0000940 # Test a single string is not expanded as a sequence.
941 class C(object):
942 __slots__ = "abc"
943 c = C()
944 c.abc = 5
945 self.assertEqual(c.abc, 5)
Guido van Rossum6661be32001-10-26 04:26:12 +0000946
Georg Brandl479a7e72008-02-05 18:13:15 +0000947 # Test unicode slot names
948 # Test a single unicode string is not expanded as a sequence.
949 class C(object):
950 __slots__ = "abc"
951 c = C()
952 c.abc = 5
953 self.assertEqual(c.abc, 5)
Guido van Rossum3926a632001-09-25 16:25:58 +0000954
Georg Brandl479a7e72008-02-05 18:13:15 +0000955 # _unicode_to_string used to modify slots in certain circumstances
956 slots = ("foo", "bar")
957 class C(object):
958 __slots__ = slots
959 x = C()
960 x.foo = 5
961 self.assertEqual(x.foo, 5)
962 self.assert_(type(slots[0]) is str)
963 # this used to leak references
964 try:
965 class C(object):
966 __slots__ = [chr(128)]
967 except (TypeError, UnicodeEncodeError):
968 pass
969 else:
970 raise TestFailed("[chr(128)] slots not caught")
Guido van Rossum3926a632001-09-25 16:25:58 +0000971
Georg Brandl479a7e72008-02-05 18:13:15 +0000972 # Test leaks
973 class Counted(object):
974 counter = 0 # counts the number of instances alive
975 def __init__(self):
976 Counted.counter += 1
977 def __del__(self):
978 Counted.counter -= 1
979 class C(object):
980 __slots__ = ['a', 'b', 'c']
981 x = C()
982 x.a = Counted()
983 x.b = Counted()
984 x.c = Counted()
985 self.assertEqual(Counted.counter, 3)
986 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +0000987 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +0000988 self.assertEqual(Counted.counter, 0)
989 class D(C):
990 pass
991 x = D()
992 x.a = Counted()
993 x.z = Counted()
994 self.assertEqual(Counted.counter, 2)
995 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +0000996 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +0000997 self.assertEqual(Counted.counter, 0)
998 class E(D):
999 __slots__ = ['e']
1000 x = E()
1001 x.a = Counted()
1002 x.z = Counted()
1003 x.e = Counted()
1004 self.assertEqual(Counted.counter, 3)
1005 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001006 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001007 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001008
Georg Brandl479a7e72008-02-05 18:13:15 +00001009 # Test cyclical leaks [SF bug 519621]
1010 class F(object):
1011 __slots__ = ['a', 'b']
1012 log = []
1013 s = F()
1014 s.a = [Counted(), s]
1015 self.assertEqual(Counted.counter, 1)
1016 s = None
Benjamin Petersone549ead2009-03-28 21:42:05 +00001017 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001018 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001019
Georg Brandl479a7e72008-02-05 18:13:15 +00001020 # Test lookup leaks [SF bug 572567]
1021 import sys,gc
Benjamin Petersone549ead2009-03-28 21:42:05 +00001022 if hasattr(gc, 'get_objects'):
1023 class G(object):
1024 def __cmp__(self, other):
1025 return 0
1026 g = G()
1027 orig_objects = len(gc.get_objects())
1028 for i in range(10):
1029 g==g
1030 new_objects = len(gc.get_objects())
1031 self.assertEqual(orig_objects, new_objects)
1032
Georg Brandl479a7e72008-02-05 18:13:15 +00001033 class H(object):
1034 __slots__ = ['a', 'b']
1035 def __init__(self):
1036 self.a = 1
1037 self.b = 2
1038 def __del__(self_):
1039 self.assertEqual(self_.a, 1)
1040 self.assertEqual(self_.b, 2)
Benjamin Petersonc1de4cc2008-11-03 21:29:09 +00001041 with support.captured_output('stderr') as s:
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001042 h = H()
Georg Brandl479a7e72008-02-05 18:13:15 +00001043 del h
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001044 self.assertEqual(s.getvalue(), '')
Guido van Rossum90c45142001-11-24 21:07:01 +00001045
Georg Brandl479a7e72008-02-05 18:13:15 +00001046 def test_slots_special(self):
1047 # Testing __dict__ and __weakref__ in __slots__...
1048 class D(object):
1049 __slots__ = ["__dict__"]
1050 a = D()
1051 self.assert_(hasattr(a, "__dict__"))
1052 self.assertFalse(hasattr(a, "__weakref__"))
1053 a.foo = 42
1054 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum90c45142001-11-24 21:07:01 +00001055
Georg Brandl479a7e72008-02-05 18:13:15 +00001056 class W(object):
1057 __slots__ = ["__weakref__"]
1058 a = W()
1059 self.assert_(hasattr(a, "__weakref__"))
1060 self.assertFalse(hasattr(a, "__dict__"))
1061 try:
1062 a.foo = 42
1063 except AttributeError:
1064 pass
1065 else:
1066 self.fail("shouldn't be allowed to set a.foo")
1067
1068 class C1(W, D):
1069 __slots__ = []
1070 a = C1()
1071 self.assert_(hasattr(a, "__dict__"))
1072 self.assert_(hasattr(a, "__weakref__"))
1073 a.foo = 42
1074 self.assertEqual(a.__dict__, {"foo": 42})
1075
1076 class C2(D, W):
1077 __slots__ = []
1078 a = C2()
1079 self.assert_(hasattr(a, "__dict__"))
1080 self.assert_(hasattr(a, "__weakref__"))
1081 a.foo = 42
1082 self.assertEqual(a.__dict__, {"foo": 42})
1083
Christian Heimesa156e092008-02-16 07:38:31 +00001084 def test_slots_descriptor(self):
1085 # Issue2115: slot descriptors did not correctly check
1086 # the type of the given object
1087 import abc
1088 class MyABC(metaclass=abc.ABCMeta):
1089 __slots__ = "a"
1090
1091 class Unrelated(object):
1092 pass
1093 MyABC.register(Unrelated)
1094
1095 u = Unrelated()
1096 self.assert_(isinstance(u, MyABC))
1097
1098 # This used to crash
1099 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1100
Georg Brandl479a7e72008-02-05 18:13:15 +00001101 def test_dynamics(self):
1102 # Testing class attribute propagation...
1103 class D(object):
1104 pass
1105 class E(D):
1106 pass
1107 class F(D):
1108 pass
1109 D.foo = 1
1110 self.assertEqual(D.foo, 1)
1111 # Test that dynamic attributes are inherited
1112 self.assertEqual(E.foo, 1)
1113 self.assertEqual(F.foo, 1)
1114 # Test dynamic instances
1115 class C(object):
1116 pass
1117 a = C()
1118 self.assertFalse(hasattr(a, "foobar"))
1119 C.foobar = 2
1120 self.assertEqual(a.foobar, 2)
1121 C.method = lambda self: 42
1122 self.assertEqual(a.method(), 42)
1123 C.__repr__ = lambda self: "C()"
1124 self.assertEqual(repr(a), "C()")
1125 C.__int__ = lambda self: 100
1126 self.assertEqual(int(a), 100)
1127 self.assertEqual(a.foobar, 2)
1128 self.assertFalse(hasattr(a, "spam"))
1129 def mygetattr(self, name):
1130 if name == "spam":
1131 return "spam"
1132 raise AttributeError
1133 C.__getattr__ = mygetattr
1134 self.assertEqual(a.spam, "spam")
1135 a.new = 12
1136 self.assertEqual(a.new, 12)
1137 def mysetattr(self, name, value):
1138 if name == "spam":
1139 raise AttributeError
1140 return object.__setattr__(self, name, value)
1141 C.__setattr__ = mysetattr
1142 try:
1143 a.spam = "not spam"
1144 except AttributeError:
1145 pass
1146 else:
1147 self.fail("expected AttributeError")
1148 self.assertEqual(a.spam, "spam")
1149 class D(C):
1150 pass
1151 d = D()
1152 d.foo = 1
1153 self.assertEqual(d.foo, 1)
1154
1155 # Test handling of int*seq and seq*int
1156 class I(int):
1157 pass
1158 self.assertEqual("a"*I(2), "aa")
1159 self.assertEqual(I(2)*"a", "aa")
1160 self.assertEqual(2*I(3), 6)
1161 self.assertEqual(I(3)*2, 6)
1162 self.assertEqual(I(3)*I(2), 6)
1163
1164 # Test handling of long*seq and seq*long
1165 class L(int):
1166 pass
1167 self.assertEqual("a"*L(2), "aa")
1168 self.assertEqual(L(2)*"a", "aa")
1169 self.assertEqual(2*L(3), 6)
1170 self.assertEqual(L(3)*2, 6)
1171 self.assertEqual(L(3)*L(2), 6)
1172
1173 # Test comparison of classes with dynamic metaclasses
1174 class dynamicmetaclass(type):
1175 pass
1176 class someclass(metaclass=dynamicmetaclass):
1177 pass
1178 self.assertNotEqual(someclass, object)
1179
1180 def test_errors(self):
1181 # Testing errors...
1182 try:
1183 class C(list, dict):
1184 pass
1185 except TypeError:
1186 pass
1187 else:
1188 self.fail("inheritance from both list and dict should be illegal")
1189
1190 try:
1191 class C(object, None):
1192 pass
1193 except TypeError:
1194 pass
1195 else:
1196 self.fail("inheritance from non-type should be illegal")
1197 class Classic:
1198 pass
1199
1200 try:
1201 class C(type(len)):
1202 pass
1203 except TypeError:
1204 pass
1205 else:
1206 self.fail("inheritance from CFunction should be illegal")
1207
1208 try:
1209 class C(object):
1210 __slots__ = 1
1211 except TypeError:
1212 pass
1213 else:
1214 self.fail("__slots__ = 1 should be illegal")
1215
1216 try:
1217 class C(object):
1218 __slots__ = [1]
1219 except TypeError:
1220 pass
1221 else:
1222 self.fail("__slots__ = [1] should be illegal")
1223
1224 class M1(type):
1225 pass
1226 class M2(type):
1227 pass
1228 class A1(object, metaclass=M1):
1229 pass
1230 class A2(object, metaclass=M2):
1231 pass
1232 try:
1233 class B(A1, A2):
1234 pass
1235 except TypeError:
1236 pass
1237 else:
1238 self.fail("finding the most derived metaclass should have failed")
1239
1240 def test_classmethods(self):
1241 # Testing class methods...
1242 class C(object):
1243 def foo(*a): return a
1244 goo = classmethod(foo)
1245 c = C()
1246 self.assertEqual(C.goo(1), (C, 1))
1247 self.assertEqual(c.goo(1), (C, 1))
1248 self.assertEqual(c.foo(1), (c, 1))
1249 class D(C):
1250 pass
1251 d = D()
1252 self.assertEqual(D.goo(1), (D, 1))
1253 self.assertEqual(d.goo(1), (D, 1))
1254 self.assertEqual(d.foo(1), (d, 1))
1255 self.assertEqual(D.foo(d, 1), (d, 1))
1256 # Test for a specific crash (SF bug 528132)
1257 def f(cls, arg): return (cls, arg)
1258 ff = classmethod(f)
1259 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1260 self.assertEqual(ff.__get__(0)(42), (int, 42))
1261
1262 # Test super() with classmethods (SF bug 535444)
1263 self.assertEqual(C.goo.__self__, C)
1264 self.assertEqual(D.goo.__self__, D)
1265 self.assertEqual(super(D,D).goo.__self__, D)
1266 self.assertEqual(super(D,d).goo.__self__, D)
1267 self.assertEqual(super(D,D).goo(), (D,))
1268 self.assertEqual(super(D,d).goo(), (D,))
1269
1270 # Verify that argument is checked for callability (SF bug 753451)
1271 try:
1272 classmethod(1).__get__(1)
1273 except TypeError:
1274 pass
1275 else:
1276 self.fail("classmethod should check for callability")
1277
1278 # Verify that classmethod() doesn't allow keyword args
1279 try:
1280 classmethod(f, kw=1)
1281 except TypeError:
1282 pass
1283 else:
1284 self.fail("classmethod shouldn't accept keyword args")
1285
Benjamin Petersone549ead2009-03-28 21:42:05 +00001286 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001287 def test_classmethods_in_c(self):
1288 # Testing C-based class methods...
1289 import xxsubtype as spam
1290 a = (1, 2, 3)
1291 d = {'abc': 123}
1292 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1293 self.assertEqual(x, spam.spamlist)
1294 self.assertEqual(a, a1)
1295 self.assertEqual(d, d1)
1296 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1297 self.assertEqual(x, spam.spamlist)
1298 self.assertEqual(a, a1)
1299 self.assertEqual(d, d1)
1300
1301 def test_staticmethods(self):
1302 # Testing static methods...
1303 class C(object):
1304 def foo(*a): return a
1305 goo = staticmethod(foo)
1306 c = C()
1307 self.assertEqual(C.goo(1), (1,))
1308 self.assertEqual(c.goo(1), (1,))
1309 self.assertEqual(c.foo(1), (c, 1,))
1310 class D(C):
1311 pass
1312 d = D()
1313 self.assertEqual(D.goo(1), (1,))
1314 self.assertEqual(d.goo(1), (1,))
1315 self.assertEqual(d.foo(1), (d, 1))
1316 self.assertEqual(D.foo(d, 1), (d, 1))
1317
Benjamin Petersone549ead2009-03-28 21:42:05 +00001318 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001319 def test_staticmethods_in_c(self):
1320 # Testing C-based static methods...
1321 import xxsubtype as spam
1322 a = (1, 2, 3)
1323 d = {"abc": 123}
1324 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1325 self.assertEqual(x, None)
1326 self.assertEqual(a, a1)
1327 self.assertEqual(d, d1)
1328 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1329 self.assertEqual(x, None)
1330 self.assertEqual(a, a1)
1331 self.assertEqual(d, d1)
1332
1333 def test_classic(self):
1334 # Testing classic classes...
1335 class C:
1336 def foo(*a): return a
1337 goo = classmethod(foo)
1338 c = C()
1339 self.assertEqual(C.goo(1), (C, 1))
1340 self.assertEqual(c.goo(1), (C, 1))
1341 self.assertEqual(c.foo(1), (c, 1))
1342 class D(C):
1343 pass
1344 d = D()
1345 self.assertEqual(D.goo(1), (D, 1))
1346 self.assertEqual(d.goo(1), (D, 1))
1347 self.assertEqual(d.foo(1), (d, 1))
1348 self.assertEqual(D.foo(d, 1), (d, 1))
1349 class E: # *not* subclassing from C
1350 foo = C.foo
1351 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
1352 self.assert_(repr(C.foo.__get__(C())).startswith("<bound method "))
1353
1354 def test_compattr(self):
1355 # Testing computed attributes...
1356 class C(object):
1357 class computed_attribute(object):
1358 def __init__(self, get, set=None, delete=None):
1359 self.__get = get
1360 self.__set = set
1361 self.__delete = delete
1362 def __get__(self, obj, type=None):
1363 return self.__get(obj)
1364 def __set__(self, obj, value):
1365 return self.__set(obj, value)
1366 def __delete__(self, obj):
1367 return self.__delete(obj)
1368 def __init__(self):
1369 self.__x = 0
1370 def __get_x(self):
1371 x = self.__x
1372 self.__x = x+1
1373 return x
1374 def __set_x(self, x):
1375 self.__x = x
1376 def __delete_x(self):
1377 del self.__x
1378 x = computed_attribute(__get_x, __set_x, __delete_x)
1379 a = C()
1380 self.assertEqual(a.x, 0)
1381 self.assertEqual(a.x, 1)
1382 a.x = 10
1383 self.assertEqual(a.x, 10)
1384 self.assertEqual(a.x, 11)
1385 del a.x
1386 self.assertEqual(hasattr(a, 'x'), 0)
1387
1388 def test_newslots(self):
1389 # Testing __new__ slot override...
1390 class C(list):
1391 def __new__(cls):
1392 self = list.__new__(cls)
1393 self.foo = 1
1394 return self
1395 def __init__(self):
1396 self.foo = self.foo + 2
1397 a = C()
1398 self.assertEqual(a.foo, 3)
1399 self.assertEqual(a.__class__, C)
1400 class D(C):
1401 pass
1402 b = D()
1403 self.assertEqual(b.foo, 3)
1404 self.assertEqual(b.__class__, D)
1405
1406 def test_altmro(self):
1407 # Testing mro() and overriding it...
1408 class A(object):
1409 def f(self): return "A"
1410 class B(A):
1411 pass
1412 class C(A):
1413 def f(self): return "C"
1414 class D(B, C):
1415 pass
1416 self.assertEqual(D.mro(), [D, B, C, A, object])
1417 self.assertEqual(D.__mro__, (D, B, C, A, object))
1418 self.assertEqual(D().f(), "C")
1419
1420 class PerverseMetaType(type):
1421 def mro(cls):
1422 L = type.mro(cls)
1423 L.reverse()
1424 return L
1425 class X(D,B,C,A, metaclass=PerverseMetaType):
1426 pass
1427 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1428 self.assertEqual(X().f(), "A")
1429
1430 try:
1431 class _metaclass(type):
1432 def mro(self):
1433 return [self, dict, object]
1434 class X(object, metaclass=_metaclass):
1435 pass
Benjamin Petersone549ead2009-03-28 21:42:05 +00001436 # In CPython, the class creation above already raises
1437 # TypeError, as a protection against the fact that
1438 # instances of X would segfault it. In other Python
1439 # implementations it would be ok to let the class X
1440 # be created, but instead get a clean TypeError on the
1441 # __setitem__ below.
1442 x = object.__new__(X)
1443 x[5] = 6
Georg Brandl479a7e72008-02-05 18:13:15 +00001444 except TypeError:
1445 pass
1446 else:
1447 self.fail("devious mro() return not caught")
1448
1449 try:
1450 class _metaclass(type):
1451 def mro(self):
1452 return [1]
1453 class X(object, metaclass=_metaclass):
1454 pass
1455 except TypeError:
1456 pass
1457 else:
1458 self.fail("non-class mro() return not caught")
1459
1460 try:
1461 class _metaclass(type):
1462 def mro(self):
1463 return 1
1464 class X(object, metaclass=_metaclass):
1465 pass
1466 except TypeError:
1467 pass
1468 else:
1469 self.fail("non-sequence mro() return not caught")
1470
1471 def test_overloading(self):
1472 # Testing operator overloading...
1473
1474 class B(object):
1475 "Intermediate class because object doesn't have a __setattr__"
1476
1477 class C(B):
1478 def __getattr__(self, name):
1479 if name == "foo":
1480 return ("getattr", name)
1481 else:
1482 raise AttributeError
1483 def __setattr__(self, name, value):
1484 if name == "foo":
1485 self.setattr = (name, value)
1486 else:
1487 return B.__setattr__(self, name, value)
1488 def __delattr__(self, name):
1489 if name == "foo":
1490 self.delattr = name
1491 else:
1492 return B.__delattr__(self, name)
1493
1494 def __getitem__(self, key):
1495 return ("getitem", key)
1496 def __setitem__(self, key, value):
1497 self.setitem = (key, value)
1498 def __delitem__(self, key):
1499 self.delitem = key
1500
1501 a = C()
1502 self.assertEqual(a.foo, ("getattr", "foo"))
1503 a.foo = 12
1504 self.assertEqual(a.setattr, ("foo", 12))
1505 del a.foo
1506 self.assertEqual(a.delattr, "foo")
1507
1508 self.assertEqual(a[12], ("getitem", 12))
1509 a[12] = 21
1510 self.assertEqual(a.setitem, (12, 21))
1511 del a[12]
1512 self.assertEqual(a.delitem, 12)
1513
1514 self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1515 a[0:10] = "foo"
1516 self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1517 del a[0:10]
1518 self.assertEqual(a.delitem, (slice(0, 10)))
1519
1520 def test_methods(self):
1521 # Testing methods...
1522 class C(object):
1523 def __init__(self, x):
1524 self.x = x
1525 def foo(self):
1526 return self.x
1527 c1 = C(1)
1528 self.assertEqual(c1.foo(), 1)
1529 class D(C):
1530 boo = C.foo
1531 goo = c1.foo
1532 d2 = D(2)
1533 self.assertEqual(d2.foo(), 2)
1534 self.assertEqual(d2.boo(), 2)
1535 self.assertEqual(d2.goo(), 1)
1536 class E(object):
1537 foo = C.foo
1538 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
1539 self.assert_(repr(C.foo.__get__(C(1))).startswith("<bound method "))
1540
1541 def test_specials(self):
1542 # Testing special operators...
1543 # Test operators like __hash__ for which a built-in default exists
1544
1545 # Test the default behavior for static classes
1546 class C(object):
1547 def __getitem__(self, i):
1548 if 0 <= i < 10: return i
1549 raise IndexError
1550 c1 = C()
1551 c2 = C()
1552 self.assert_(not not c1) # What?
1553 self.assertNotEqual(id(c1), id(c2))
1554 hash(c1)
1555 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001556 self.assertEqual(c1, c1)
1557 self.assert_(c1 != c2)
1558 self.assert_(not c1 != c1)
1559 self.assert_(not c1 == c2)
1560 # Note that the module name appears in str/repr, and that varies
1561 # depending on whether this test is run standalone or from a framework.
1562 self.assert_(str(c1).find('C object at ') >= 0)
1563 self.assertEqual(str(c1), repr(c1))
1564 self.assert_(-1 not in c1)
1565 for i in range(10):
1566 self.assert_(i in c1)
1567 self.assertFalse(10 in c1)
1568 # Test the default behavior for dynamic classes
1569 class D(object):
1570 def __getitem__(self, i):
1571 if 0 <= i < 10: return i
1572 raise IndexError
1573 d1 = D()
1574 d2 = D()
1575 self.assert_(not not d1)
1576 self.assertNotEqual(id(d1), id(d2))
1577 hash(d1)
1578 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001579 self.assertEqual(d1, d1)
1580 self.assertNotEqual(d1, d2)
1581 self.assert_(not d1 != d1)
1582 self.assert_(not d1 == d2)
1583 # Note that the module name appears in str/repr, and that varies
1584 # depending on whether this test is run standalone or from a framework.
1585 self.assert_(str(d1).find('D object at ') >= 0)
1586 self.assertEqual(str(d1), repr(d1))
1587 self.assert_(-1 not in d1)
1588 for i in range(10):
1589 self.assert_(i in d1)
1590 self.assertFalse(10 in d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00001591 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00001592 class Proxy(object):
1593 def __init__(self, x):
1594 self.x = x
1595 def __bool__(self):
1596 return not not self.x
1597 def __hash__(self):
1598 return hash(self.x)
1599 def __eq__(self, other):
1600 return self.x == other
1601 def __ne__(self, other):
1602 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00001603 def __ge__(self, other):
1604 return self.x >= other
1605 def __gt__(self, other):
1606 return self.x > other
1607 def __le__(self, other):
1608 return self.x <= other
1609 def __lt__(self, other):
1610 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00001611 def __str__(self):
1612 return "Proxy:%s" % self.x
1613 def __repr__(self):
1614 return "Proxy(%r)" % self.x
1615 def __contains__(self, value):
1616 return value in self.x
1617 p0 = Proxy(0)
1618 p1 = Proxy(1)
1619 p_1 = Proxy(-1)
1620 self.assertFalse(p0)
1621 self.assert_(not not p1)
1622 self.assertEqual(hash(p0), hash(0))
1623 self.assertEqual(p0, p0)
1624 self.assertNotEqual(p0, p1)
1625 self.assert_(not p0 != p0)
1626 self.assertEqual(not p0, p1)
Benjamin Peterson60192082008-10-16 19:34:46 +00001627 self.assert_(p0 < p1)
1628 self.assert_(p0 <= p1)
1629 self.assert_(p1 > p0)
1630 self.assert_(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001631 self.assertEqual(str(p0), "Proxy:0")
1632 self.assertEqual(repr(p0), "Proxy(0)")
1633 p10 = Proxy(range(10))
1634 self.assertFalse(-1 in p10)
1635 for i in range(10):
1636 self.assert_(i in p10)
1637 self.assertFalse(10 in p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001638
Georg Brandl479a7e72008-02-05 18:13:15 +00001639 def test_weakrefs(self):
1640 # Testing weak references...
1641 import weakref
1642 class C(object):
1643 pass
1644 c = C()
1645 r = weakref.ref(c)
1646 self.assertEqual(r(), c)
1647 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00001648 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001649 self.assertEqual(r(), None)
1650 del r
1651 class NoWeak(object):
1652 __slots__ = ['foo']
1653 no = NoWeak()
1654 try:
1655 weakref.ref(no)
1656 except TypeError as msg:
1657 self.assert_(str(msg).find("weak reference") >= 0)
1658 else:
1659 self.fail("weakref.ref(no) should be illegal")
1660 class Weak(object):
1661 __slots__ = ['foo', '__weakref__']
1662 yes = Weak()
1663 r = weakref.ref(yes)
1664 self.assertEqual(r(), yes)
1665 del yes
Benjamin Petersone549ead2009-03-28 21:42:05 +00001666 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001667 self.assertEqual(r(), None)
1668 del r
1669
1670 def test_properties(self):
1671 # Testing property...
1672 class C(object):
1673 def getx(self):
1674 return self.__x
1675 def setx(self, value):
1676 self.__x = value
1677 def delx(self):
1678 del self.__x
1679 x = property(getx, setx, delx, doc="I'm the x property.")
1680 a = C()
1681 self.assertFalse(hasattr(a, "x"))
1682 a.x = 42
1683 self.assertEqual(a._C__x, 42)
1684 self.assertEqual(a.x, 42)
1685 del a.x
1686 self.assertFalse(hasattr(a, "x"))
1687 self.assertFalse(hasattr(a, "_C__x"))
1688 C.x.__set__(a, 100)
1689 self.assertEqual(C.x.__get__(a), 100)
1690 C.x.__delete__(a)
1691 self.assertFalse(hasattr(a, "x"))
1692
1693 raw = C.__dict__['x']
1694 self.assert_(isinstance(raw, property))
1695
1696 attrs = dir(raw)
1697 self.assert_("__doc__" in attrs)
1698 self.assert_("fget" in attrs)
1699 self.assert_("fset" in attrs)
1700 self.assert_("fdel" in attrs)
1701
1702 self.assertEqual(raw.__doc__, "I'm the x property.")
1703 self.assert_(raw.fget is C.__dict__['getx'])
1704 self.assert_(raw.fset is C.__dict__['setx'])
1705 self.assert_(raw.fdel is C.__dict__['delx'])
1706
1707 for attr in "__doc__", "fget", "fset", "fdel":
1708 try:
1709 setattr(raw, attr, 42)
1710 except AttributeError as msg:
1711 if str(msg).find('readonly') < 0:
1712 self.fail("when setting readonly attr %r on a property, "
1713 "got unexpected AttributeError msg %r" % (attr, str(msg)))
1714 else:
1715 self.fail("expected AttributeError from trying to set readonly %r "
1716 "attr on a property" % attr)
1717
1718 class D(object):
1719 __getitem__ = property(lambda s: 1/0)
1720
1721 d = D()
1722 try:
1723 for i in d:
1724 str(i)
1725 except ZeroDivisionError:
1726 pass
1727 else:
1728 self.fail("expected ZeroDivisionError from bad property")
1729
1730 class E(object):
1731 def getter(self):
1732 "getter method"
1733 return 0
1734 def setter(self_, value):
1735 "setter method"
1736 pass
1737 prop = property(getter)
1738 self.assertEqual(prop.__doc__, "getter method")
1739 prop2 = property(fset=setter)
1740 self.assertEqual(prop2.__doc__, None)
1741
1742 # this segfaulted in 2.5b2
1743 try:
1744 import _testcapi
1745 except ImportError:
1746 pass
1747 else:
1748 class X(object):
1749 p = property(_testcapi.test_with_docstring)
1750
1751 def test_properties_plus(self):
1752 class C(object):
1753 foo = property(doc="hello")
1754 @foo.getter
1755 def foo(self):
1756 return self._foo
1757 @foo.setter
1758 def foo(self, value):
1759 self._foo = abs(value)
1760 @foo.deleter
1761 def foo(self):
1762 del self._foo
1763 c = C()
1764 self.assertEqual(C.foo.__doc__, "hello")
1765 self.assertFalse(hasattr(c, "foo"))
1766 c.foo = -42
1767 self.assert_(hasattr(c, '_foo'))
1768 self.assertEqual(c._foo, 42)
1769 self.assertEqual(c.foo, 42)
1770 del c.foo
1771 self.assertFalse(hasattr(c, '_foo'))
1772 self.assertFalse(hasattr(c, "foo"))
1773
1774 class D(C):
1775 @C.foo.deleter
1776 def foo(self):
1777 try:
1778 del self._foo
1779 except AttributeError:
1780 pass
1781 d = D()
1782 d.foo = 24
1783 self.assertEqual(d.foo, 24)
1784 del d.foo
1785 del d.foo
1786
1787 class E(object):
1788 @property
1789 def foo(self):
1790 return self._foo
1791 @foo.setter
1792 def foo(self, value):
1793 raise RuntimeError
1794 @foo.setter
1795 def foo(self, value):
1796 self._foo = abs(value)
1797 @foo.deleter
1798 def foo(self, value=None):
1799 del self._foo
1800
1801 e = E()
1802 e.foo = -42
1803 self.assertEqual(e.foo, 42)
1804 del e.foo
1805
1806 class F(E):
1807 @E.foo.deleter
1808 def foo(self):
1809 del self._foo
1810 @foo.setter
1811 def foo(self, value):
1812 self._foo = max(0, value)
1813 f = F()
1814 f.foo = -10
1815 self.assertEqual(f.foo, 0)
1816 del f.foo
1817
1818 def test_dict_constructors(self):
1819 # Testing dict constructor ...
1820 d = dict()
1821 self.assertEqual(d, {})
1822 d = dict({})
1823 self.assertEqual(d, {})
1824 d = dict({1: 2, 'a': 'b'})
1825 self.assertEqual(d, {1: 2, 'a': 'b'})
1826 self.assertEqual(d, dict(list(d.items())))
1827 self.assertEqual(d, dict(iter(d.items())))
1828 d = dict({'one':1, 'two':2})
1829 self.assertEqual(d, dict(one=1, two=2))
1830 self.assertEqual(d, dict(**d))
1831 self.assertEqual(d, dict({"one": 1}, two=2))
1832 self.assertEqual(d, dict([("two", 2)], one=1))
1833 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
1834 self.assertEqual(d, dict(**d))
1835
1836 for badarg in 0, 0, 0j, "0", [0], (0,):
1837 try:
1838 dict(badarg)
1839 except TypeError:
1840 pass
1841 except ValueError:
1842 if badarg == "0":
1843 # It's a sequence, and its elements are also sequences (gotta
1844 # love strings <wink>), but they aren't of length 2, so this
1845 # one seemed better as a ValueError than a TypeError.
1846 pass
1847 else:
1848 self.fail("no TypeError from dict(%r)" % badarg)
1849 else:
1850 self.fail("no TypeError from dict(%r)" % badarg)
1851
1852 try:
1853 dict({}, {})
1854 except TypeError:
1855 pass
1856 else:
1857 self.fail("no TypeError from dict({}, {})")
1858
1859 class Mapping:
1860 # Lacks a .keys() method; will be added later.
1861 dict = {1:2, 3:4, 'a':1j}
1862
1863 try:
1864 dict(Mapping())
1865 except TypeError:
1866 pass
1867 else:
1868 self.fail("no TypeError from dict(incomplete mapping)")
1869
1870 Mapping.keys = lambda self: list(self.dict.keys())
1871 Mapping.__getitem__ = lambda self, i: self.dict[i]
1872 d = dict(Mapping())
1873 self.assertEqual(d, Mapping.dict)
1874
1875 # Init from sequence of iterable objects, each producing a 2-sequence.
1876 class AddressBookEntry:
1877 def __init__(self, first, last):
1878 self.first = first
1879 self.last = last
1880 def __iter__(self):
1881 return iter([self.first, self.last])
1882
1883 d = dict([AddressBookEntry('Tim', 'Warsaw'),
1884 AddressBookEntry('Barry', 'Peters'),
1885 AddressBookEntry('Tim', 'Peters'),
1886 AddressBookEntry('Barry', 'Warsaw')])
1887 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
1888
1889 d = dict(zip(range(4), range(1, 5)))
1890 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
1891
1892 # Bad sequence lengths.
1893 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
1894 try:
1895 dict(bad)
1896 except ValueError:
1897 pass
1898 else:
1899 self.fail("no ValueError from dict(%r)" % bad)
1900
1901 def test_dir(self):
1902 # Testing dir() ...
1903 junk = 12
1904 self.assertEqual(dir(), ['junk', 'self'])
1905 del junk
1906
1907 # Just make sure these don't blow up!
1908 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
1909 dir(arg)
1910
1911 # Test dir on new-style classes. Since these have object as a
1912 # base class, a lot more gets sucked in.
1913 def interesting(strings):
1914 return [s for s in strings if not s.startswith('_')]
1915
1916 class C(object):
1917 Cdata = 1
1918 def Cmethod(self): pass
1919
1920 cstuff = ['Cdata', 'Cmethod']
1921 self.assertEqual(interesting(dir(C)), cstuff)
1922
1923 c = C()
1924 self.assertEqual(interesting(dir(c)), cstuff)
1925 ## self.assert_('__self__' in dir(C.Cmethod))
1926
1927 c.cdata = 2
1928 c.cmethod = lambda self: 0
1929 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
1930 ## self.assert_('__self__' in dir(c.Cmethod))
1931
1932 class A(C):
1933 Adata = 1
1934 def Amethod(self): pass
1935
1936 astuff = ['Adata', 'Amethod'] + cstuff
1937 self.assertEqual(interesting(dir(A)), astuff)
1938 ## self.assert_('__self__' in dir(A.Amethod))
1939 a = A()
1940 self.assertEqual(interesting(dir(a)), astuff)
1941 a.adata = 42
1942 a.amethod = lambda self: 3
1943 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
1944 ## self.assert_('__self__' in dir(a.Amethod))
1945
1946 # Try a module subclass.
1947 import sys
1948 class M(type(sys)):
1949 pass
1950 minstance = M("m")
1951 minstance.b = 2
1952 minstance.a = 1
1953 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
1954 self.assertEqual(names, ['a', 'b'])
1955
1956 class M2(M):
1957 def getdict(self):
1958 return "Not a dict!"
1959 __dict__ = property(getdict)
1960
1961 m2instance = M2("m2")
1962 m2instance.b = 2
1963 m2instance.a = 1
1964 self.assertEqual(m2instance.__dict__, "Not a dict!")
1965 try:
1966 dir(m2instance)
1967 except TypeError:
1968 pass
1969
1970 # Two essentially featureless objects, just inheriting stuff from
1971 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00001972 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
1973 if support.check_impl_detail():
1974 # None differs in PyPy: it has a __nonzero__
1975 self.assertEqual(dir(None), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00001976
1977 # Nasty test case for proxied objects
1978 class Wrapper(object):
1979 def __init__(self, obj):
1980 self.__obj = obj
1981 def __repr__(self):
1982 return "Wrapper(%s)" % repr(self.__obj)
1983 def __getitem__(self, key):
1984 return Wrapper(self.__obj[key])
1985 def __len__(self):
1986 return len(self.__obj)
1987 def __getattr__(self, name):
1988 return Wrapper(getattr(self.__obj, name))
1989
1990 class C(object):
1991 def __getclass(self):
1992 return Wrapper(type(self))
1993 __class__ = property(__getclass)
1994
1995 dir(C()) # This used to segfault
1996
1997 def test_supers(self):
1998 # Testing super...
1999
2000 class A(object):
2001 def meth(self, a):
2002 return "A(%r)" % a
2003
2004 self.assertEqual(A().meth(1), "A(1)")
2005
2006 class B(A):
2007 def __init__(self):
2008 self.__super = super(B, self)
2009 def meth(self, a):
2010 return "B(%r)" % a + self.__super.meth(a)
2011
2012 self.assertEqual(B().meth(2), "B(2)A(2)")
2013
2014 class C(A):
2015 def meth(self, a):
2016 return "C(%r)" % a + self.__super.meth(a)
2017 C._C__super = super(C)
2018
2019 self.assertEqual(C().meth(3), "C(3)A(3)")
2020
2021 class D(C, B):
2022 def meth(self, a):
2023 return "D(%r)" % a + super(D, self).meth(a)
2024
2025 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2026
2027 # Test for subclassing super
2028
2029 class mysuper(super):
2030 def __init__(self, *args):
2031 return super(mysuper, self).__init__(*args)
2032
2033 class E(D):
2034 def meth(self, a):
2035 return "E(%r)" % a + mysuper(E, self).meth(a)
2036
2037 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2038
2039 class F(E):
2040 def meth(self, a):
2041 s = self.__super # == mysuper(F, self)
2042 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2043 F._F__super = mysuper(F)
2044
2045 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2046
2047 # Make sure certain errors are raised
2048
2049 try:
2050 super(D, 42)
2051 except TypeError:
2052 pass
2053 else:
2054 self.fail("shouldn't allow super(D, 42)")
2055
2056 try:
2057 super(D, C())
2058 except TypeError:
2059 pass
2060 else:
2061 self.fail("shouldn't allow super(D, C())")
2062
2063 try:
2064 super(D).__get__(12)
2065 except TypeError:
2066 pass
2067 else:
2068 self.fail("shouldn't allow super(D).__get__(12)")
2069
2070 try:
2071 super(D).__get__(C())
2072 except TypeError:
2073 pass
2074 else:
2075 self.fail("shouldn't allow super(D).__get__(C())")
2076
2077 # Make sure data descriptors can be overridden and accessed via super
2078 # (new feature in Python 2.3)
2079
2080 class DDbase(object):
2081 def getx(self): return 42
2082 x = property(getx)
2083
2084 class DDsub(DDbase):
2085 def getx(self): return "hello"
2086 x = property(getx)
2087
2088 dd = DDsub()
2089 self.assertEqual(dd.x, "hello")
2090 self.assertEqual(super(DDsub, dd).x, 42)
2091
2092 # Ensure that super() lookup of descriptor from classmethod
2093 # works (SF ID# 743627)
2094
2095 class Base(object):
2096 aProp = property(lambda self: "foo")
2097
2098 class Sub(Base):
2099 @classmethod
2100 def test(klass):
2101 return super(Sub,klass).aProp
2102
2103 self.assertEqual(Sub.test(), Base.aProp)
2104
2105 # Verify that super() doesn't allow keyword args
2106 try:
2107 super(Base, kw=1)
2108 except TypeError:
2109 pass
2110 else:
2111 self.assertEqual("super shouldn't accept keyword args")
2112
2113 def test_basic_inheritance(self):
2114 # Testing inheritance from basic types...
2115
2116 class hexint(int):
2117 def __repr__(self):
2118 return hex(self)
2119 def __add__(self, other):
2120 return hexint(int.__add__(self, other))
2121 # (Note that overriding __radd__ doesn't work,
2122 # because the int type gets first dibs.)
2123 self.assertEqual(repr(hexint(7) + 9), "0x10")
2124 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2125 a = hexint(12345)
2126 self.assertEqual(a, 12345)
2127 self.assertEqual(int(a), 12345)
2128 self.assert_(int(a).__class__ is int)
2129 self.assertEqual(hash(a), hash(12345))
2130 self.assert_((+a).__class__ is int)
2131 self.assert_((a >> 0).__class__ is int)
2132 self.assert_((a << 0).__class__ is int)
2133 self.assert_((hexint(0) << 12).__class__ is int)
2134 self.assert_((hexint(0) >> 12).__class__ is int)
2135
2136 class octlong(int):
2137 __slots__ = []
2138 def __str__(self):
2139 s = oct(self)
2140 if s[-1] == 'L':
2141 s = s[:-1]
2142 return s
2143 def __add__(self, other):
2144 return self.__class__(super(octlong, self).__add__(other))
2145 __radd__ = __add__
2146 self.assertEqual(str(octlong(3) + 5), "0o10")
2147 # (Note that overriding __radd__ here only seems to work
2148 # because the example uses a short int left argument.)
2149 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2150 a = octlong(12345)
2151 self.assertEqual(a, 12345)
2152 self.assertEqual(int(a), 12345)
2153 self.assertEqual(hash(a), hash(12345))
2154 self.assert_(int(a).__class__ is int)
2155 self.assert_((+a).__class__ is int)
2156 self.assert_((-a).__class__ is int)
2157 self.assert_((-octlong(0)).__class__ is int)
2158 self.assert_((a >> 0).__class__ is int)
2159 self.assert_((a << 0).__class__ is int)
2160 self.assert_((a - 0).__class__ is int)
2161 self.assert_((a * 1).__class__ is int)
2162 self.assert_((a ** 1).__class__ is int)
2163 self.assert_((a // 1).__class__ is int)
2164 self.assert_((1 * a).__class__ is int)
2165 self.assert_((a | 0).__class__ is int)
2166 self.assert_((a ^ 0).__class__ is int)
2167 self.assert_((a & -1).__class__ is int)
2168 self.assert_((octlong(0) << 12).__class__ is int)
2169 self.assert_((octlong(0) >> 12).__class__ is int)
2170 self.assert_(abs(octlong(0)).__class__ is int)
2171
2172 # Because octlong overrides __add__, we can't check the absence of +0
2173 # optimizations using octlong.
2174 class longclone(int):
2175 pass
2176 a = longclone(1)
2177 self.assert_((a + 0).__class__ is int)
2178 self.assert_((0 + a).__class__ is int)
2179
2180 # Check that negative clones don't segfault
2181 a = longclone(-1)
2182 self.assertEqual(a.__dict__, {})
2183 self.assertEqual(int(a), -1) # self.assert_ PyNumber_Long() copies the sign bit
2184
2185 class precfloat(float):
2186 __slots__ = ['prec']
2187 def __init__(self, value=0.0, prec=12):
2188 self.prec = int(prec)
2189 def __repr__(self):
2190 return "%.*g" % (self.prec, self)
2191 self.assertEqual(repr(precfloat(1.1)), "1.1")
2192 a = precfloat(12345)
2193 self.assertEqual(a, 12345.0)
2194 self.assertEqual(float(a), 12345.0)
2195 self.assert_(float(a).__class__ is float)
2196 self.assertEqual(hash(a), hash(12345.0))
2197 self.assert_((+a).__class__ is float)
2198
2199 class madcomplex(complex):
2200 def __repr__(self):
2201 return "%.17gj%+.17g" % (self.imag, self.real)
2202 a = madcomplex(-3, 4)
2203 self.assertEqual(repr(a), "4j-3")
2204 base = complex(-3, 4)
2205 self.assertEqual(base.__class__, complex)
2206 self.assertEqual(a, base)
2207 self.assertEqual(complex(a), base)
2208 self.assertEqual(complex(a).__class__, complex)
2209 a = madcomplex(a) # just trying another form of the constructor
2210 self.assertEqual(repr(a), "4j-3")
2211 self.assertEqual(a, base)
2212 self.assertEqual(complex(a), base)
2213 self.assertEqual(complex(a).__class__, complex)
2214 self.assertEqual(hash(a), hash(base))
2215 self.assertEqual((+a).__class__, complex)
2216 self.assertEqual((a + 0).__class__, complex)
2217 self.assertEqual(a + 0, base)
2218 self.assertEqual((a - 0).__class__, complex)
2219 self.assertEqual(a - 0, base)
2220 self.assertEqual((a * 1).__class__, complex)
2221 self.assertEqual(a * 1, base)
2222 self.assertEqual((a / 1).__class__, complex)
2223 self.assertEqual(a / 1, base)
2224
2225 class madtuple(tuple):
2226 _rev = None
2227 def rev(self):
2228 if self._rev is not None:
2229 return self._rev
2230 L = list(self)
2231 L.reverse()
2232 self._rev = self.__class__(L)
2233 return self._rev
2234 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2235 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2236 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2237 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2238 for i in range(512):
2239 t = madtuple(range(i))
2240 u = t.rev()
2241 v = u.rev()
2242 self.assertEqual(v, t)
2243 a = madtuple((1,2,3,4,5))
2244 self.assertEqual(tuple(a), (1,2,3,4,5))
2245 self.assert_(tuple(a).__class__ is tuple)
2246 self.assertEqual(hash(a), hash((1,2,3,4,5)))
2247 self.assert_(a[:].__class__ is tuple)
2248 self.assert_((a * 1).__class__ is tuple)
2249 self.assert_((a * 0).__class__ is tuple)
2250 self.assert_((a + ()).__class__ is tuple)
2251 a = madtuple(())
2252 self.assertEqual(tuple(a), ())
2253 self.assert_(tuple(a).__class__ is tuple)
2254 self.assert_((a + a).__class__ is tuple)
2255 self.assert_((a * 0).__class__ is tuple)
2256 self.assert_((a * 1).__class__ is tuple)
2257 self.assert_((a * 2).__class__ is tuple)
2258 self.assert_(a[:].__class__ is tuple)
2259
2260 class madstring(str):
2261 _rev = None
2262 def rev(self):
2263 if self._rev is not None:
2264 return self._rev
2265 L = list(self)
2266 L.reverse()
2267 self._rev = self.__class__("".join(L))
2268 return self._rev
2269 s = madstring("abcdefghijklmnopqrstuvwxyz")
2270 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2271 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2272 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2273 for i in range(256):
2274 s = madstring("".join(map(chr, range(i))))
2275 t = s.rev()
2276 u = t.rev()
2277 self.assertEqual(u, s)
2278 s = madstring("12345")
2279 self.assertEqual(str(s), "12345")
2280 self.assert_(str(s).__class__ is str)
2281
2282 base = "\x00" * 5
2283 s = madstring(base)
2284 self.assertEqual(s, base)
2285 self.assertEqual(str(s), base)
2286 self.assert_(str(s).__class__ is str)
2287 self.assertEqual(hash(s), hash(base))
2288 self.assertEqual({s: 1}[base], 1)
2289 self.assertEqual({base: 1}[s], 1)
2290 self.assert_((s + "").__class__ is str)
2291 self.assertEqual(s + "", base)
2292 self.assert_(("" + s).__class__ is str)
2293 self.assertEqual("" + s, base)
2294 self.assert_((s * 0).__class__ is str)
2295 self.assertEqual(s * 0, "")
2296 self.assert_((s * 1).__class__ is str)
2297 self.assertEqual(s * 1, base)
2298 self.assert_((s * 2).__class__ is str)
2299 self.assertEqual(s * 2, base + base)
2300 self.assert_(s[:].__class__ is str)
2301 self.assertEqual(s[:], base)
2302 self.assert_(s[0:0].__class__ is str)
2303 self.assertEqual(s[0:0], "")
2304 self.assert_(s.strip().__class__ is str)
2305 self.assertEqual(s.strip(), base)
2306 self.assert_(s.lstrip().__class__ is str)
2307 self.assertEqual(s.lstrip(), base)
2308 self.assert_(s.rstrip().__class__ is str)
2309 self.assertEqual(s.rstrip(), base)
2310 identitytab = {}
2311 self.assert_(s.translate(identitytab).__class__ is str)
2312 self.assertEqual(s.translate(identitytab), base)
2313 self.assert_(s.replace("x", "x").__class__ is str)
2314 self.assertEqual(s.replace("x", "x"), base)
2315 self.assert_(s.ljust(len(s)).__class__ is str)
2316 self.assertEqual(s.ljust(len(s)), base)
2317 self.assert_(s.rjust(len(s)).__class__ is str)
2318 self.assertEqual(s.rjust(len(s)), base)
2319 self.assert_(s.center(len(s)).__class__ is str)
2320 self.assertEqual(s.center(len(s)), base)
2321 self.assert_(s.lower().__class__ is str)
2322 self.assertEqual(s.lower(), base)
2323
2324 class madunicode(str):
2325 _rev = None
2326 def rev(self):
2327 if self._rev is not None:
2328 return self._rev
2329 L = list(self)
2330 L.reverse()
2331 self._rev = self.__class__("".join(L))
2332 return self._rev
2333 u = madunicode("ABCDEF")
2334 self.assertEqual(u, "ABCDEF")
2335 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2336 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2337 base = "12345"
2338 u = madunicode(base)
2339 self.assertEqual(str(u), base)
2340 self.assert_(str(u).__class__ is str)
2341 self.assertEqual(hash(u), hash(base))
2342 self.assertEqual({u: 1}[base], 1)
2343 self.assertEqual({base: 1}[u], 1)
2344 self.assert_(u.strip().__class__ is str)
2345 self.assertEqual(u.strip(), base)
2346 self.assert_(u.lstrip().__class__ is str)
2347 self.assertEqual(u.lstrip(), base)
2348 self.assert_(u.rstrip().__class__ is str)
2349 self.assertEqual(u.rstrip(), base)
2350 self.assert_(u.replace("x", "x").__class__ is str)
2351 self.assertEqual(u.replace("x", "x"), base)
2352 self.assert_(u.replace("xy", "xy").__class__ is str)
2353 self.assertEqual(u.replace("xy", "xy"), base)
2354 self.assert_(u.center(len(u)).__class__ is str)
2355 self.assertEqual(u.center(len(u)), base)
2356 self.assert_(u.ljust(len(u)).__class__ is str)
2357 self.assertEqual(u.ljust(len(u)), base)
2358 self.assert_(u.rjust(len(u)).__class__ is str)
2359 self.assertEqual(u.rjust(len(u)), base)
2360 self.assert_(u.lower().__class__ is str)
2361 self.assertEqual(u.lower(), base)
2362 self.assert_(u.upper().__class__ is str)
2363 self.assertEqual(u.upper(), base)
2364 self.assert_(u.capitalize().__class__ is str)
2365 self.assertEqual(u.capitalize(), base)
2366 self.assert_(u.title().__class__ is str)
2367 self.assertEqual(u.title(), base)
2368 self.assert_((u + "").__class__ is str)
2369 self.assertEqual(u + "", base)
2370 self.assert_(("" + u).__class__ is str)
2371 self.assertEqual("" + u, base)
2372 self.assert_((u * 0).__class__ is str)
2373 self.assertEqual(u * 0, "")
2374 self.assert_((u * 1).__class__ is str)
2375 self.assertEqual(u * 1, base)
2376 self.assert_((u * 2).__class__ is str)
2377 self.assertEqual(u * 2, base + base)
2378 self.assert_(u[:].__class__ is str)
2379 self.assertEqual(u[:], base)
2380 self.assert_(u[0:0].__class__ is str)
2381 self.assertEqual(u[0:0], "")
2382
2383 class sublist(list):
2384 pass
2385 a = sublist(range(5))
2386 self.assertEqual(a, list(range(5)))
2387 a.append("hello")
2388 self.assertEqual(a, list(range(5)) + ["hello"])
2389 a[5] = 5
2390 self.assertEqual(a, list(range(6)))
2391 a.extend(range(6, 20))
2392 self.assertEqual(a, list(range(20)))
2393 a[-5:] = []
2394 self.assertEqual(a, list(range(15)))
2395 del a[10:15]
2396 self.assertEqual(len(a), 10)
2397 self.assertEqual(a, list(range(10)))
2398 self.assertEqual(list(a), list(range(10)))
2399 self.assertEqual(a[0], 0)
2400 self.assertEqual(a[9], 9)
2401 self.assertEqual(a[-10], 0)
2402 self.assertEqual(a[-1], 9)
2403 self.assertEqual(a[:5], list(range(5)))
2404
2405 ## class CountedInput(file):
2406 ## """Counts lines read by self.readline().
2407 ##
2408 ## self.lineno is the 0-based ordinal of the last line read, up to
2409 ## a maximum of one greater than the number of lines in the file.
2410 ##
2411 ## self.ateof is true if and only if the final "" line has been read,
2412 ## at which point self.lineno stops incrementing, and further calls
2413 ## to readline() continue to return "".
2414 ## """
2415 ##
2416 ## lineno = 0
2417 ## ateof = 0
2418 ## def readline(self):
2419 ## if self.ateof:
2420 ## return ""
2421 ## s = file.readline(self)
2422 ## # Next line works too.
2423 ## # s = super(CountedInput, self).readline()
2424 ## self.lineno += 1
2425 ## if s == "":
2426 ## self.ateof = 1
2427 ## return s
2428 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002429 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002430 ## lines = ['a\n', 'b\n', 'c\n']
2431 ## try:
2432 ## f.writelines(lines)
2433 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002434 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002435 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2436 ## got = f.readline()
2437 ## self.assertEqual(expected, got)
2438 ## self.assertEqual(f.lineno, i)
2439 ## self.assertEqual(f.ateof, (i > len(lines)))
2440 ## f.close()
2441 ## finally:
2442 ## try:
2443 ## f.close()
2444 ## except:
2445 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002446 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002447
2448 def test_keywords(self):
2449 # Testing keyword args to basic type constructors ...
2450 self.assertEqual(int(x=1), 1)
2451 self.assertEqual(float(x=2), 2.0)
2452 self.assertEqual(int(x=3), 3)
2453 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2454 self.assertEqual(str(object=500), '500')
2455 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
2456 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2457 self.assertEqual(list(sequence=(0, 1, 2)), list(range(3)))
2458 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2459
2460 for constructor in (int, float, int, complex, str, str,
2461 tuple, list):
2462 try:
2463 constructor(bogus_keyword_arg=1)
2464 except TypeError:
2465 pass
2466 else:
2467 self.fail("expected TypeError from bogus keyword argument to %r"
2468 % constructor)
2469
2470 def test_str_subclass_as_dict_key(self):
2471 # Testing a str subclass used as dict key ..
2472
2473 class cistr(str):
2474 """Sublcass of str that computes __eq__ case-insensitively.
2475
2476 Also computes a hash code of the string in canonical form.
2477 """
2478
2479 def __init__(self, value):
2480 self.canonical = value.lower()
2481 self.hashcode = hash(self.canonical)
2482
2483 def __eq__(self, other):
2484 if not isinstance(other, cistr):
2485 other = cistr(other)
2486 return self.canonical == other.canonical
2487
2488 def __hash__(self):
2489 return self.hashcode
2490
2491 self.assertEqual(cistr('ABC'), 'abc')
2492 self.assertEqual('aBc', cistr('ABC'))
2493 self.assertEqual(str(cistr('ABC')), 'ABC')
2494
2495 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2496 self.assertEqual(d[cistr('one')], 1)
2497 self.assertEqual(d[cistr('tWo')], 2)
2498 self.assertEqual(d[cistr('THrEE')], 3)
2499 self.assert_(cistr('ONe') in d)
2500 self.assertEqual(d.get(cistr('thrEE')), 3)
2501
2502 def test_classic_comparisons(self):
2503 # Testing classic comparisons...
2504 class classic:
2505 pass
2506
2507 for base in (classic, int, object):
2508 class C(base):
2509 def __init__(self, value):
2510 self.value = int(value)
2511 def __eq__(self, other):
2512 if isinstance(other, C):
2513 return self.value == other.value
2514 if isinstance(other, int) or isinstance(other, int):
2515 return self.value == other
2516 return NotImplemented
2517 def __ne__(self, other):
2518 if isinstance(other, C):
2519 return self.value != other.value
2520 if isinstance(other, int) or isinstance(other, int):
2521 return self.value != other
2522 return NotImplemented
2523 def __lt__(self, other):
2524 if isinstance(other, C):
2525 return self.value < other.value
2526 if isinstance(other, int) or isinstance(other, int):
2527 return self.value < other
2528 return NotImplemented
2529 def __le__(self, other):
2530 if isinstance(other, C):
2531 return self.value <= other.value
2532 if isinstance(other, int) or isinstance(other, int):
2533 return self.value <= other
2534 return NotImplemented
2535 def __gt__(self, other):
2536 if isinstance(other, C):
2537 return self.value > other.value
2538 if isinstance(other, int) or isinstance(other, int):
2539 return self.value > other
2540 return NotImplemented
2541 def __ge__(self, other):
2542 if isinstance(other, C):
2543 return self.value >= other.value
2544 if isinstance(other, int) or isinstance(other, int):
2545 return self.value >= other
2546 return NotImplemented
2547
2548 c1 = C(1)
2549 c2 = C(2)
2550 c3 = C(3)
2551 self.assertEqual(c1, 1)
2552 c = {1: c1, 2: c2, 3: c3}
2553 for x in 1, 2, 3:
2554 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00002555 for op in "<", "<=", "==", "!=", ">", ">=":
Mark Dickinsona56c4672009-01-27 18:17:45 +00002556 self.assert_(eval("c[x] %s c[y]" % op) ==
2557 eval("x %s y" % op),
2558 "x=%d, y=%d" % (x, y))
2559 self.assert_(eval("c[x] %s y" % op) ==
2560 eval("x %s y" % op),
2561 "x=%d, y=%d" % (x, y))
2562 self.assert_(eval("x %s c[y]" % op) ==
2563 eval("x %s y" % op),
2564 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002565
2566 def test_rich_comparisons(self):
2567 # Testing rich comparisons...
2568 class Z(complex):
2569 pass
2570 z = Z(1)
2571 self.assertEqual(z, 1+0j)
2572 self.assertEqual(1+0j, z)
2573 class ZZ(complex):
2574 def __eq__(self, other):
2575 try:
2576 return abs(self - other) <= 1e-6
2577 except:
2578 return NotImplemented
2579 zz = ZZ(1.0000003)
2580 self.assertEqual(zz, 1+0j)
2581 self.assertEqual(1+0j, zz)
2582
2583 class classic:
2584 pass
2585 for base in (classic, int, object, list):
2586 class C(base):
2587 def __init__(self, value):
2588 self.value = int(value)
2589 def __cmp__(self_, other):
2590 self.fail("shouldn't call __cmp__")
2591 def __eq__(self, other):
2592 if isinstance(other, C):
2593 return self.value == other.value
2594 if isinstance(other, int) or isinstance(other, int):
2595 return self.value == other
2596 return NotImplemented
2597 def __ne__(self, other):
2598 if isinstance(other, C):
2599 return self.value != other.value
2600 if isinstance(other, int) or isinstance(other, int):
2601 return self.value != other
2602 return NotImplemented
2603 def __lt__(self, other):
2604 if isinstance(other, C):
2605 return self.value < other.value
2606 if isinstance(other, int) or isinstance(other, int):
2607 return self.value < other
2608 return NotImplemented
2609 def __le__(self, other):
2610 if isinstance(other, C):
2611 return self.value <= other.value
2612 if isinstance(other, int) or isinstance(other, int):
2613 return self.value <= other
2614 return NotImplemented
2615 def __gt__(self, other):
2616 if isinstance(other, C):
2617 return self.value > other.value
2618 if isinstance(other, int) or isinstance(other, int):
2619 return self.value > other
2620 return NotImplemented
2621 def __ge__(self, other):
2622 if isinstance(other, C):
2623 return self.value >= other.value
2624 if isinstance(other, int) or isinstance(other, int):
2625 return self.value >= other
2626 return NotImplemented
2627 c1 = C(1)
2628 c2 = C(2)
2629 c3 = C(3)
2630 self.assertEqual(c1, 1)
2631 c = {1: c1, 2: c2, 3: c3}
2632 for x in 1, 2, 3:
2633 for y in 1, 2, 3:
2634 for op in "<", "<=", "==", "!=", ">", ">=":
2635 self.assert_(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2636 "x=%d, y=%d" % (x, y))
2637 self.assert_(eval("c[x] %s y" % op) == eval("x %s y" % op),
2638 "x=%d, y=%d" % (x, y))
2639 self.assert_(eval("x %s c[y]" % op) == eval("x %s y" % op),
2640 "x=%d, y=%d" % (x, y))
2641
2642 def test_descrdoc(self):
2643 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002644 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00002645 def check(descr, what):
2646 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002647 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00002648 check(complex.real, "the real part of a complex number") # member descriptor
2649
2650 def test_doc_descriptor(self):
2651 # Testing __doc__ descriptor...
2652 # SF bug 542984
2653 class DocDescr(object):
2654 def __get__(self, object, otype):
2655 if object:
2656 object = object.__class__.__name__ + ' instance'
2657 if otype:
2658 otype = otype.__name__
2659 return 'object=%s; type=%s' % (object, otype)
2660 class OldClass:
2661 __doc__ = DocDescr()
2662 class NewClass(object):
2663 __doc__ = DocDescr()
2664 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
2665 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
2666 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
2667 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
2668
2669 def test_set_class(self):
2670 # Testing __class__ assignment...
2671 class C(object): pass
2672 class D(object): pass
2673 class E(object): pass
2674 class F(D, E): pass
2675 for cls in C, D, E, F:
2676 for cls2 in C, D, E, F:
2677 x = cls()
2678 x.__class__ = cls2
2679 self.assert_(x.__class__ is cls2)
2680 x.__class__ = cls
2681 self.assert_(x.__class__ is cls)
2682 def cant(x, C):
2683 try:
2684 x.__class__ = C
2685 except TypeError:
2686 pass
2687 else:
2688 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
2689 try:
2690 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00002691 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00002692 pass
2693 else:
2694 self.fail("shouldn't allow del %r.__class__" % x)
2695 cant(C(), list)
2696 cant(list(), C)
2697 cant(C(), 1)
2698 cant(C(), object)
2699 cant(object(), list)
2700 cant(list(), object)
2701 class Int(int): __slots__ = []
2702 cant(2, Int)
2703 cant(Int(), int)
2704 cant(True, int)
2705 cant(2, bool)
2706 o = object()
2707 cant(o, type(1))
2708 cant(o, type(None))
2709 del o
2710 class G(object):
2711 __slots__ = ["a", "b"]
2712 class H(object):
2713 __slots__ = ["b", "a"]
2714 class I(object):
2715 __slots__ = ["a", "b"]
2716 class J(object):
2717 __slots__ = ["c", "b"]
2718 class K(object):
2719 __slots__ = ["a", "b", "d"]
2720 class L(H):
2721 __slots__ = ["e"]
2722 class M(I):
2723 __slots__ = ["e"]
2724 class N(J):
2725 __slots__ = ["__weakref__"]
2726 class P(J):
2727 __slots__ = ["__dict__"]
2728 class Q(J):
2729 pass
2730 class R(J):
2731 __slots__ = ["__dict__", "__weakref__"]
2732
2733 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
2734 x = cls()
2735 x.a = 1
2736 x.__class__ = cls2
2737 self.assert_(x.__class__ is cls2,
2738 "assigning %r as __class__ for %r silently failed" % (cls2, x))
2739 self.assertEqual(x.a, 1)
2740 x.__class__ = cls
2741 self.assert_(x.__class__ is cls,
2742 "assigning %r as __class__ for %r silently failed" % (cls, x))
2743 self.assertEqual(x.a, 1)
2744 for cls in G, J, K, L, M, N, P, R, list, Int:
2745 for cls2 in G, J, K, L, M, N, P, R, list, Int:
2746 if cls is cls2:
2747 continue
2748 cant(cls(), cls2)
2749
Benjamin Peterson193152c2009-04-25 01:08:45 +00002750 # Issue5283: when __class__ changes in __del__, the wrong
2751 # type gets DECREF'd.
2752 class O(object):
2753 pass
2754 class A(object):
2755 def __del__(self):
2756 self.__class__ = O
2757 l = [A() for x in range(100)]
2758 del l
2759
Georg Brandl479a7e72008-02-05 18:13:15 +00002760 def test_set_dict(self):
2761 # Testing __dict__ assignment...
2762 class C(object): pass
2763 a = C()
2764 a.__dict__ = {'b': 1}
2765 self.assertEqual(a.b, 1)
2766 def cant(x, dict):
2767 try:
2768 x.__dict__ = dict
2769 except (AttributeError, TypeError):
2770 pass
2771 else:
2772 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
2773 cant(a, None)
2774 cant(a, [])
2775 cant(a, 1)
2776 del a.__dict__ # Deleting __dict__ is allowed
2777
2778 class Base(object):
2779 pass
2780 def verify_dict_readonly(x):
2781 """
2782 x has to be an instance of a class inheriting from Base.
2783 """
2784 cant(x, {})
2785 try:
2786 del x.__dict__
2787 except (AttributeError, TypeError):
2788 pass
2789 else:
2790 self.fail("shouldn't allow del %r.__dict__" % x)
2791 dict_descr = Base.__dict__["__dict__"]
2792 try:
2793 dict_descr.__set__(x, {})
2794 except (AttributeError, TypeError):
2795 pass
2796 else:
2797 self.fail("dict_descr allowed access to %r's dict" % x)
2798
2799 # Classes don't allow __dict__ assignment and have readonly dicts
2800 class Meta1(type, Base):
2801 pass
2802 class Meta2(Base, type):
2803 pass
2804 class D(object, metaclass=Meta1):
2805 pass
2806 class E(object, metaclass=Meta2):
2807 pass
2808 for cls in C, D, E:
2809 verify_dict_readonly(cls)
2810 class_dict = cls.__dict__
2811 try:
2812 class_dict["spam"] = "eggs"
2813 except TypeError:
2814 pass
2815 else:
2816 self.fail("%r's __dict__ can be modified" % cls)
2817
2818 # Modules also disallow __dict__ assignment
2819 class Module1(types.ModuleType, Base):
2820 pass
2821 class Module2(Base, types.ModuleType):
2822 pass
2823 for ModuleType in Module1, Module2:
2824 mod = ModuleType("spam")
2825 verify_dict_readonly(mod)
2826 mod.__dict__["spam"] = "eggs"
2827
2828 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00002829 # (at least not any more than regular exception's __dict__ can
2830 # be deleted; on CPython it is not the case, whereas on PyPy they
2831 # can, just like any other new-style instance's __dict__.)
2832 def can_delete_dict(e):
2833 try:
2834 del e.__dict__
2835 except (TypeError, AttributeError):
2836 return False
2837 else:
2838 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00002839 class Exception1(Exception, Base):
2840 pass
2841 class Exception2(Base, Exception):
2842 pass
2843 for ExceptionType in Exception, Exception1, Exception2:
2844 e = ExceptionType()
2845 e.__dict__ = {"a": 1}
2846 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00002847 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00002848
2849 def test_pickles(self):
2850 # Testing pickling and copying new-style classes and objects...
2851 import pickle
2852
2853 def sorteditems(d):
2854 L = list(d.items())
2855 L.sort()
2856 return L
2857
2858 global C
2859 class C(object):
2860 def __init__(self, a, b):
2861 super(C, self).__init__()
2862 self.a = a
2863 self.b = b
2864 def __repr__(self):
2865 return "C(%r, %r)" % (self.a, self.b)
2866
2867 global C1
2868 class C1(list):
2869 def __new__(cls, a, b):
2870 return super(C1, cls).__new__(cls)
2871 def __getnewargs__(self):
2872 return (self.a, self.b)
2873 def __init__(self, a, b):
2874 self.a = a
2875 self.b = b
2876 def __repr__(self):
2877 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2878
2879 global C2
2880 class C2(int):
2881 def __new__(cls, a, b, val=0):
2882 return super(C2, cls).__new__(cls, val)
2883 def __getnewargs__(self):
2884 return (self.a, self.b, int(self))
2885 def __init__(self, a, b, val=0):
2886 self.a = a
2887 self.b = b
2888 def __repr__(self):
2889 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2890
2891 global C3
2892 class C3(object):
2893 def __init__(self, foo):
2894 self.foo = foo
2895 def __getstate__(self):
2896 return self.foo
2897 def __setstate__(self, foo):
2898 self.foo = foo
2899
2900 global C4classic, C4
2901 class C4classic: # classic
2902 pass
2903 class C4(C4classic, object): # mixed inheritance
2904 pass
2905
Guido van Rossum3926a632001-09-25 16:25:58 +00002906 for bin in 0, 1:
Guido van Rossum3926a632001-09-25 16:25:58 +00002907 for cls in C, C1, C2:
Georg Brandl479a7e72008-02-05 18:13:15 +00002908 s = pickle.dumps(cls, bin)
2909 cls2 = pickle.loads(s)
2910 self.assert_(cls2 is cls)
Guido van Rossum3926a632001-09-25 16:25:58 +00002911
2912 a = C1(1, 2); a.append(42); a.append(24)
2913 b = C2("hello", "world", 42)
Georg Brandl479a7e72008-02-05 18:13:15 +00002914 s = pickle.dumps((a, b), bin)
2915 x, y = pickle.loads(s)
2916 self.assertEqual(x.__class__, a.__class__)
2917 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
2918 self.assertEqual(y.__class__, b.__class__)
2919 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
2920 self.assertEqual(repr(x), repr(a))
2921 self.assertEqual(repr(y), repr(b))
Guido van Rossum90c45142001-11-24 21:07:01 +00002922 # Test for __getstate__ and __setstate__ on new style class
2923 u = C3(42)
Georg Brandl479a7e72008-02-05 18:13:15 +00002924 s = pickle.dumps(u, bin)
2925 v = pickle.loads(s)
2926 self.assertEqual(u.__class__, v.__class__)
2927 self.assertEqual(u.foo, v.foo)
Guido van Rossum90c45142001-11-24 21:07:01 +00002928 # Test for picklability of hybrid class
2929 u = C4()
2930 u.foo = 42
Georg Brandl479a7e72008-02-05 18:13:15 +00002931 s = pickle.dumps(u, bin)
2932 v = pickle.loads(s)
2933 self.assertEqual(u.__class__, v.__class__)
2934 self.assertEqual(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00002935
Georg Brandl479a7e72008-02-05 18:13:15 +00002936 # Testing copy.deepcopy()
2937 import copy
2938 for cls in C, C1, C2:
2939 cls2 = copy.deepcopy(cls)
2940 self.assert_(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002941
Georg Brandl479a7e72008-02-05 18:13:15 +00002942 a = C1(1, 2); a.append(42); a.append(24)
2943 b = C2("hello", "world", 42)
2944 x, y = copy.deepcopy((a, b))
2945 self.assertEqual(x.__class__, a.__class__)
2946 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
2947 self.assertEqual(y.__class__, b.__class__)
2948 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
2949 self.assertEqual(repr(x), repr(a))
2950 self.assertEqual(repr(y), repr(b))
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002951
Georg Brandl479a7e72008-02-05 18:13:15 +00002952 def test_pickle_slots(self):
2953 # Testing pickling of classes with __slots__ ...
2954 import pickle
2955 # Pickling of classes with __slots__ but without __getstate__ should fail
2956 # (if using protocol 0 or 1)
2957 global B, C, D, E
2958 class B(object):
Guido van Rossum8c842552002-03-14 23:05:54 +00002959 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00002960 for base in [object, B]:
2961 class C(base):
2962 __slots__ = ['a']
2963 class D(C):
2964 pass
2965 try:
2966 pickle.dumps(C(), 0)
2967 except TypeError:
2968 pass
2969 else:
2970 self.fail("should fail: pickle C instance - %s" % base)
2971 try:
2972 pickle.dumps(C(), 0)
2973 except TypeError:
2974 pass
2975 else:
2976 self.fail("should fail: pickle D instance - %s" % base)
2977 # Give C a nice generic __getstate__ and __setstate__
2978 class C(base):
2979 __slots__ = ['a']
2980 def __getstate__(self):
2981 try:
2982 d = self.__dict__.copy()
2983 except AttributeError:
2984 d = {}
2985 for cls in self.__class__.__mro__:
2986 for sn in cls.__dict__.get('__slots__', ()):
2987 try:
2988 d[sn] = getattr(self, sn)
2989 except AttributeError:
2990 pass
2991 return d
2992 def __setstate__(self, d):
2993 for k, v in list(d.items()):
2994 setattr(self, k, v)
2995 class D(C):
2996 pass
2997 # Now it should work
2998 x = C()
2999 y = pickle.loads(pickle.dumps(x))
3000 self.assertEqual(hasattr(y, 'a'), 0)
3001 x.a = 42
3002 y = pickle.loads(pickle.dumps(x))
3003 self.assertEqual(y.a, 42)
3004 x = D()
3005 x.a = 42
3006 x.b = 100
3007 y = pickle.loads(pickle.dumps(x))
3008 self.assertEqual(y.a + y.b, 142)
3009 # A subclass that adds a slot should also work
3010 class E(C):
3011 __slots__ = ['b']
3012 x = E()
3013 x.a = 42
3014 x.b = "foo"
3015 y = pickle.loads(pickle.dumps(x))
3016 self.assertEqual(y.a, x.a)
3017 self.assertEqual(y.b, x.b)
3018
3019 def test_binary_operator_override(self):
3020 # Testing overrides of binary operations...
3021 class I(int):
3022 def __repr__(self):
3023 return "I(%r)" % int(self)
3024 def __add__(self, other):
3025 return I(int(self) + int(other))
3026 __radd__ = __add__
3027 def __pow__(self, other, mod=None):
3028 if mod is None:
3029 return I(pow(int(self), int(other)))
3030 else:
3031 return I(pow(int(self), int(other), int(mod)))
3032 def __rpow__(self, other, mod=None):
3033 if mod is None:
3034 return I(pow(int(other), int(self), mod))
3035 else:
3036 return I(pow(int(other), int(self), int(mod)))
3037
3038 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3039 self.assertEqual(repr(I(1) + 2), "I(3)")
3040 self.assertEqual(repr(1 + I(2)), "I(3)")
3041 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3042 self.assertEqual(repr(2 ** I(3)), "I(8)")
3043 self.assertEqual(repr(I(2) ** 3), "I(8)")
3044 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3045 class S(str):
3046 def __eq__(self, other):
3047 return self.lower() == other.lower()
3048
3049 def test_subclass_propagation(self):
3050 # Testing propagation of slot functions to subclasses...
3051 class A(object):
3052 pass
3053 class B(A):
3054 pass
3055 class C(A):
3056 pass
3057 class D(B, C):
3058 pass
3059 d = D()
3060 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3061 A.__hash__ = lambda self: 42
3062 self.assertEqual(hash(d), 42)
3063 C.__hash__ = lambda self: 314
3064 self.assertEqual(hash(d), 314)
3065 B.__hash__ = lambda self: 144
3066 self.assertEqual(hash(d), 144)
3067 D.__hash__ = lambda self: 100
3068 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003069 D.__hash__ = None
3070 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003071 del D.__hash__
3072 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003073 B.__hash__ = None
3074 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003075 del B.__hash__
3076 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003077 C.__hash__ = None
3078 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003079 del C.__hash__
3080 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003081 A.__hash__ = None
3082 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003083 del A.__hash__
3084 self.assertEqual(hash(d), orig_hash)
3085 d.foo = 42
3086 d.bar = 42
3087 self.assertEqual(d.foo, 42)
3088 self.assertEqual(d.bar, 42)
3089 def __getattribute__(self, name):
3090 if name == "foo":
3091 return 24
3092 return object.__getattribute__(self, name)
3093 A.__getattribute__ = __getattribute__
3094 self.assertEqual(d.foo, 24)
3095 self.assertEqual(d.bar, 42)
3096 def __getattr__(self, name):
3097 if name in ("spam", "foo", "bar"):
3098 return "hello"
3099 raise AttributeError(name)
3100 B.__getattr__ = __getattr__
3101 self.assertEqual(d.spam, "hello")
3102 self.assertEqual(d.foo, 24)
3103 self.assertEqual(d.bar, 42)
3104 del A.__getattribute__
3105 self.assertEqual(d.foo, 42)
3106 del d.foo
3107 self.assertEqual(d.foo, "hello")
3108 self.assertEqual(d.bar, 42)
3109 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003110 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003111 d.foo
3112 except AttributeError:
3113 pass
3114 else:
3115 self.fail("d.foo should be undefined now")
3116
3117 # Test a nasty bug in recurse_down_subclasses()
3118 import gc
3119 class A(object):
3120 pass
3121 class B(A):
3122 pass
3123 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003124 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003125 A.__setitem__ = lambda *a: None # crash
3126
3127 def test_buffer_inheritance(self):
3128 # Testing that buffer interface is inherited ...
3129
3130 import binascii
3131 # SF bug [#470040] ParseTuple t# vs subclasses.
3132
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003133 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003134 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003135 base = b'abc'
3136 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003137 # b2a_hex uses the buffer interface to get its argument's value, via
3138 # PyArg_ParseTuple 't#' code.
3139 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3140
Georg Brandl479a7e72008-02-05 18:13:15 +00003141 class MyInt(int):
3142 pass
3143 m = MyInt(42)
3144 try:
3145 binascii.b2a_hex(m)
3146 self.fail('subclass of int should not have a buffer interface')
3147 except TypeError:
3148 pass
3149
3150 def test_str_of_str_subclass(self):
3151 # Testing __str__ defined in subclass of str ...
3152 import binascii
3153 import io
3154
3155 class octetstring(str):
3156 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003157 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003158 def __repr__(self):
3159 return self + " repr"
3160
3161 o = octetstring('A')
3162 self.assertEqual(type(o), octetstring)
3163 self.assertEqual(type(str(o)), str)
3164 self.assertEqual(type(repr(o)), str)
3165 self.assertEqual(ord(o), 0x41)
3166 self.assertEqual(str(o), '41')
3167 self.assertEqual(repr(o), 'A repr')
3168 self.assertEqual(o.__str__(), '41')
3169 self.assertEqual(o.__repr__(), 'A repr')
3170
3171 capture = io.StringIO()
3172 # Calling str() or not exercises different internal paths.
3173 print(o, file=capture)
3174 print(str(o), file=capture)
3175 self.assertEqual(capture.getvalue(), '41\n41\n')
3176 capture.close()
3177
3178 def test_keyword_arguments(self):
3179 # Testing keyword arguments to __init__, __call__...
3180 def f(a): return a
3181 self.assertEqual(f.__call__(a=42), 42)
3182 a = []
3183 list.__init__(a, sequence=[0, 1, 2])
3184 self.assertEqual(a, [0, 1, 2])
3185
3186 def test_recursive_call(self):
3187 # Testing recursive __call__() by setting to instance of class...
3188 class A(object):
3189 pass
3190
3191 A.__call__ = A()
3192 try:
3193 A()()
3194 except RuntimeError:
3195 pass
3196 else:
3197 self.fail("Recursion limit should have been reached for __call__()")
3198
3199 def test_delete_hook(self):
3200 # Testing __del__ hook...
3201 log = []
3202 class C(object):
3203 def __del__(self):
3204 log.append(1)
3205 c = C()
3206 self.assertEqual(log, [])
3207 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003208 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003209 self.assertEqual(log, [1])
3210
3211 class D(object): pass
3212 d = D()
3213 try: del d[0]
3214 except TypeError: pass
3215 else: self.fail("invalid del() didn't raise TypeError")
3216
3217 def test_hash_inheritance(self):
3218 # Testing hash of mutable subclasses...
3219
3220 class mydict(dict):
3221 pass
3222 d = mydict()
3223 try:
3224 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003225 except TypeError:
3226 pass
3227 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003228 self.fail("hash() of dict subclass should fail")
3229
3230 class mylist(list):
3231 pass
3232 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003233 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003234 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003235 except TypeError:
3236 pass
3237 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003238 self.fail("hash() of list subclass should fail")
3239
3240 def test_str_operations(self):
3241 try: 'a' + 5
3242 except TypeError: pass
3243 else: self.fail("'' + 5 doesn't raise TypeError")
3244
3245 try: ''.split('')
3246 except ValueError: pass
3247 else: self.fail("''.split('') doesn't raise ValueError")
3248
3249 try: ''.join([0])
3250 except TypeError: pass
3251 else: self.fail("''.join([0]) doesn't raise TypeError")
3252
3253 try: ''.rindex('5')
3254 except ValueError: pass
3255 else: self.fail("''.rindex('5') doesn't raise ValueError")
3256
3257 try: '%(n)s' % None
3258 except TypeError: pass
3259 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3260
3261 try: '%(n' % {}
3262 except ValueError: pass
3263 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3264
3265 try: '%*s' % ('abc')
3266 except TypeError: pass
3267 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3268
3269 try: '%*.*s' % ('abc', 5)
3270 except TypeError: pass
3271 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3272
3273 try: '%s' % (1, 2)
3274 except TypeError: pass
3275 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3276
3277 try: '%' % None
3278 except ValueError: pass
3279 else: self.fail("'%' % None doesn't raise ValueError")
3280
3281 self.assertEqual('534253'.isdigit(), 1)
3282 self.assertEqual('534253x'.isdigit(), 0)
3283 self.assertEqual('%c' % 5, '\x05')
3284 self.assertEqual('%c' % '5', '5')
3285
3286 def test_deepcopy_recursive(self):
3287 # Testing deepcopy of recursive objects...
3288 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003289 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003290 a = Node()
3291 b = Node()
3292 a.b = b
3293 b.a = a
3294 z = deepcopy(a) # This blew up before
3295
3296 def test_unintialized_modules(self):
3297 # Testing uninitialized module objects...
3298 from types import ModuleType as M
3299 m = M.__new__(M)
3300 str(m)
3301 self.assertEqual(hasattr(m, "__name__"), 0)
3302 self.assertEqual(hasattr(m, "__file__"), 0)
3303 self.assertEqual(hasattr(m, "foo"), 0)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003304 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003305 m.foo = 1
3306 self.assertEqual(m.__dict__, {"foo": 1})
3307
3308 def test_funny_new(self):
3309 # Testing __new__ returning something unexpected...
3310 class C(object):
3311 def __new__(cls, arg):
3312 if isinstance(arg, str): return [1, 2, 3]
3313 elif isinstance(arg, int): return object.__new__(D)
3314 else: return object.__new__(cls)
3315 class D(C):
3316 def __init__(self, arg):
3317 self.foo = arg
3318 self.assertEqual(C("1"), [1, 2, 3])
3319 self.assertEqual(D("1"), [1, 2, 3])
3320 d = D(None)
3321 self.assertEqual(d.foo, None)
3322 d = C(1)
3323 self.assertEqual(isinstance(d, D), True)
3324 self.assertEqual(d.foo, 1)
3325 d = D(1)
3326 self.assertEqual(isinstance(d, D), True)
3327 self.assertEqual(d.foo, 1)
3328
3329 def test_imul_bug(self):
3330 # Testing for __imul__ problems...
3331 # SF bug 544647
3332 class C(object):
3333 def __imul__(self, other):
3334 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003335 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003336 y = x
3337 y *= 1.0
3338 self.assertEqual(y, (x, 1.0))
3339 y = x
3340 y *= 2
3341 self.assertEqual(y, (x, 2))
3342 y = x
3343 y *= 3
3344 self.assertEqual(y, (x, 3))
3345 y = x
3346 y *= 1<<100
3347 self.assertEqual(y, (x, 1<<100))
3348 y = x
3349 y *= None
3350 self.assertEqual(y, (x, None))
3351 y = x
3352 y *= "foo"
3353 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003354
Georg Brandl479a7e72008-02-05 18:13:15 +00003355 def test_copy_setstate(self):
3356 # Testing that copy.*copy() correctly uses __setstate__...
3357 import copy
3358 class C(object):
3359 def __init__(self, foo=None):
3360 self.foo = foo
3361 self.__foo = foo
3362 def setfoo(self, foo=None):
3363 self.foo = foo
3364 def getfoo(self):
3365 return self.__foo
3366 def __getstate__(self):
3367 return [self.foo]
3368 def __setstate__(self_, lst):
3369 self.assertEqual(len(lst), 1)
3370 self_.__foo = self_.foo = lst[0]
3371 a = C(42)
3372 a.setfoo(24)
3373 self.assertEqual(a.foo, 24)
3374 self.assertEqual(a.getfoo(), 42)
3375 b = copy.copy(a)
3376 self.assertEqual(b.foo, 24)
3377 self.assertEqual(b.getfoo(), 24)
3378 b = copy.deepcopy(a)
3379 self.assertEqual(b.foo, 24)
3380 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003381
Georg Brandl479a7e72008-02-05 18:13:15 +00003382 def test_slices(self):
3383 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003384
Georg Brandl479a7e72008-02-05 18:13:15 +00003385 # Strings
3386 self.assertEqual("hello"[:4], "hell")
3387 self.assertEqual("hello"[slice(4)], "hell")
3388 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3389 class S(str):
3390 def __getitem__(self, x):
3391 return str.__getitem__(self, x)
3392 self.assertEqual(S("hello")[:4], "hell")
3393 self.assertEqual(S("hello")[slice(4)], "hell")
3394 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3395 # Tuples
3396 self.assertEqual((1,2,3)[:2], (1,2))
3397 self.assertEqual((1,2,3)[slice(2)], (1,2))
3398 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3399 class T(tuple):
3400 def __getitem__(self, x):
3401 return tuple.__getitem__(self, x)
3402 self.assertEqual(T((1,2,3))[:2], (1,2))
3403 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3404 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3405 # Lists
3406 self.assertEqual([1,2,3][:2], [1,2])
3407 self.assertEqual([1,2,3][slice(2)], [1,2])
3408 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3409 class L(list):
3410 def __getitem__(self, x):
3411 return list.__getitem__(self, x)
3412 self.assertEqual(L([1,2,3])[:2], [1,2])
3413 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3414 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3415 # Now do lists and __setitem__
3416 a = L([1,2,3])
3417 a[slice(1, 3)] = [3,2]
3418 self.assertEqual(a, [1,3,2])
3419 a[slice(0, 2, 1)] = [3,1]
3420 self.assertEqual(a, [3,1,2])
3421 a.__setitem__(slice(1, 3), [2,1])
3422 self.assertEqual(a, [3,2,1])
3423 a.__setitem__(slice(0, 2, 1), [2,3])
3424 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003425
Georg Brandl479a7e72008-02-05 18:13:15 +00003426 def test_subtype_resurrection(self):
3427 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003428
Georg Brandl479a7e72008-02-05 18:13:15 +00003429 class C(object):
3430 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003431
Georg Brandl479a7e72008-02-05 18:13:15 +00003432 def __del__(self):
3433 # resurrect the instance
3434 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003435
Georg Brandl479a7e72008-02-05 18:13:15 +00003436 c = C()
3437 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003438
Benjamin Petersone549ead2009-03-28 21:42:05 +00003439 # The most interesting thing here is whether this blows up, due to
3440 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3441 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003442 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003443
Georg Brandl479a7e72008-02-05 18:13:15 +00003444 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Petersone549ead2009-03-28 21:42:05 +00003445 # the last container slot works: that will attempt to delete c again,
3446 # which will cause c to get appended back to the container again
3447 # "during" the del. (On non-CPython implementations, however, __del__
3448 # is typically not called again.)
3449 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003450 self.assertEqual(len(C.container), 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003451 del C.container[-1]
3452 if support.check_impl_detail():
3453 support.gc_collect()
3454 self.assertEqual(len(C.container), 1)
3455 self.assertEqual(C.container[-1].attr, 42)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003456
Georg Brandl479a7e72008-02-05 18:13:15 +00003457 # Make c mortal again, so that the test framework with -l doesn't report
3458 # it as a leak.
3459 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003460
Georg Brandl479a7e72008-02-05 18:13:15 +00003461 def test_slots_trash(self):
3462 # Testing slot trash...
3463 # Deallocating deeply nested slotted trash caused stack overflows
3464 class trash(object):
3465 __slots__ = ['x']
3466 def __init__(self, x):
3467 self.x = x
3468 o = None
3469 for i in range(50000):
3470 o = trash(o)
3471 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003472
Georg Brandl479a7e72008-02-05 18:13:15 +00003473 def test_slots_multiple_inheritance(self):
3474 # SF bug 575229, multiple inheritance w/ slots dumps core
3475 class A(object):
3476 __slots__=()
3477 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003478 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003479 class C(A,B) :
3480 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003481 if support.check_impl_detail():
3482 self.assertEqual(C.__basicsize__, B.__basicsize__)
Georg Brandl479a7e72008-02-05 18:13:15 +00003483 self.assert_(hasattr(C, '__dict__'))
3484 self.assert_(hasattr(C, '__weakref__'))
3485 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003486
Georg Brandl479a7e72008-02-05 18:13:15 +00003487 def test_rmul(self):
3488 # Testing correct invocation of __rmul__...
3489 # SF patch 592646
3490 class C(object):
3491 def __mul__(self, other):
3492 return "mul"
3493 def __rmul__(self, other):
3494 return "rmul"
3495 a = C()
3496 self.assertEqual(a*2, "mul")
3497 self.assertEqual(a*2.2, "mul")
3498 self.assertEqual(2*a, "rmul")
3499 self.assertEqual(2.2*a, "rmul")
3500
3501 def test_ipow(self):
3502 # Testing correct invocation of __ipow__...
3503 # [SF bug 620179]
3504 class C(object):
3505 def __ipow__(self, other):
3506 pass
3507 a = C()
3508 a **= 2
3509
3510 def test_mutable_bases(self):
3511 # Testing mutable bases...
3512
3513 # stuff that should work:
3514 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003515 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003516 class C2(object):
3517 def __getattribute__(self, attr):
3518 if attr == 'a':
3519 return 2
3520 else:
3521 return super(C2, self).__getattribute__(attr)
3522 def meth(self):
3523 return 1
3524 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003525 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003526 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003527 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003528 d = D()
3529 e = E()
3530 D.__bases__ = (C,)
3531 D.__bases__ = (C2,)
3532 self.assertEqual(d.meth(), 1)
3533 self.assertEqual(e.meth(), 1)
3534 self.assertEqual(d.a, 2)
3535 self.assertEqual(e.a, 2)
3536 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003537
Georg Brandl479a7e72008-02-05 18:13:15 +00003538 # stuff that shouldn't:
3539 class L(list):
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003540 pass
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003541
Georg Brandl479a7e72008-02-05 18:13:15 +00003542 try:
3543 L.__bases__ = (dict,)
3544 except TypeError:
3545 pass
3546 else:
3547 self.fail("shouldn't turn list subclass into dict subclass")
Guido van Rossuma96b0df2002-06-18 16:49:45 +00003548
Georg Brandl479a7e72008-02-05 18:13:15 +00003549 try:
3550 list.__bases__ = (dict,)
3551 except TypeError:
3552 pass
3553 else:
3554 self.fail("shouldn't be able to assign to list.__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003555
Georg Brandl479a7e72008-02-05 18:13:15 +00003556 try:
3557 D.__bases__ = (C2, list)
3558 except TypeError:
3559 pass
3560 else:
3561 assert 0, "best_base calculation found wanting"
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003562
Georg Brandl479a7e72008-02-05 18:13:15 +00003563 try:
3564 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003565 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003566 pass
3567 else:
3568 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003569
Georg Brandl479a7e72008-02-05 18:13:15 +00003570 try:
3571 D.__bases__ = ()
3572 except TypeError as msg:
3573 if str(msg) == "a new-style class can't have only classic bases":
3574 self.fail("wrong error message for .__bases__ = ()")
3575 else:
3576 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003577
Georg Brandl479a7e72008-02-05 18:13:15 +00003578 try:
3579 D.__bases__ = (D,)
3580 except TypeError:
3581 pass
3582 else:
3583 # actually, we'll have crashed by here...
3584 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003585
Georg Brandl479a7e72008-02-05 18:13:15 +00003586 try:
3587 D.__bases__ = (C, C)
3588 except TypeError:
3589 pass
3590 else:
3591 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003592
Georg Brandl479a7e72008-02-05 18:13:15 +00003593 try:
3594 D.__bases__ = (E,)
3595 except TypeError:
3596 pass
3597 else:
3598 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003599
Benjamin Petersonae937c02009-04-18 20:54:08 +00003600 def test_builtin_bases(self):
3601 # Make sure all the builtin types can have their base queried without
3602 # segfaulting. See issue #5787.
3603 builtin_types = [tp for tp in builtins.__dict__.values()
3604 if isinstance(tp, type)]
3605 for tp in builtin_types:
3606 object.__getattribute__(tp, "__bases__")
3607 if tp is not object:
3608 self.assertEqual(len(tp.__bases__), 1, tp)
3609
3610
Georg Brandl479a7e72008-02-05 18:13:15 +00003611 def test_mutable_bases_with_failing_mro(self):
3612 # Testing mutable bases with failing mro...
3613 class WorkOnce(type):
3614 def __new__(self, name, bases, ns):
3615 self.flag = 0
3616 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3617 def mro(self):
3618 if self.flag > 0:
3619 raise RuntimeError("bozo")
3620 else:
3621 self.flag += 1
3622 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003623
Georg Brandl479a7e72008-02-05 18:13:15 +00003624 class WorkAlways(type):
3625 def mro(self):
3626 # this is here to make sure that .mro()s aren't called
3627 # with an exception set (which was possible at one point).
3628 # An error message will be printed in a debug build.
3629 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003630 return type.mro(self)
3631
Georg Brandl479a7e72008-02-05 18:13:15 +00003632 class C(object):
3633 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003634
Georg Brandl479a7e72008-02-05 18:13:15 +00003635 class C2(object):
3636 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003637
Georg Brandl479a7e72008-02-05 18:13:15 +00003638 class D(C):
3639 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003640
Georg Brandl479a7e72008-02-05 18:13:15 +00003641 class E(D):
3642 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003643
Georg Brandl479a7e72008-02-05 18:13:15 +00003644 class F(D, metaclass=WorkOnce):
3645 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003646
Georg Brandl479a7e72008-02-05 18:13:15 +00003647 class G(D, metaclass=WorkAlways):
3648 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003649
Georg Brandl479a7e72008-02-05 18:13:15 +00003650 # Immediate subclasses have their mro's adjusted in alphabetical
3651 # order, so E's will get adjusted before adjusting F's fails. We
3652 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003653
Georg Brandl479a7e72008-02-05 18:13:15 +00003654 E_mro_before = E.__mro__
3655 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00003656
Armin Rigofd163f92005-12-29 15:59:19 +00003657 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003658 D.__bases__ = (C2,)
3659 except RuntimeError:
3660 self.assertEqual(E.__mro__, E_mro_before)
3661 self.assertEqual(D.__mro__, D_mro_before)
3662 else:
3663 self.fail("exception not propagated")
3664
3665 def test_mutable_bases_catch_mro_conflict(self):
3666 # Testing mutable bases catch mro conflict...
3667 class A(object):
3668 pass
3669
3670 class B(object):
3671 pass
3672
3673 class C(A, B):
3674 pass
3675
3676 class D(A, B):
3677 pass
3678
3679 class E(C, D):
3680 pass
3681
3682 try:
3683 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00003684 except TypeError:
3685 pass
3686 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003687 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00003688
Georg Brandl479a7e72008-02-05 18:13:15 +00003689 def test_mutable_names(self):
3690 # Testing mutable names...
3691 class C(object):
3692 pass
3693
3694 # C.__module__ could be 'test_descr' or '__main__'
3695 mod = C.__module__
3696
3697 C.__name__ = 'D'
3698 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
3699
3700 C.__name__ = 'D.E'
3701 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
3702
3703 def test_subclass_right_op(self):
3704 # Testing correct dispatch of subclass overloading __r<op>__...
3705
3706 # This code tests various cases where right-dispatch of a subclass
3707 # should be preferred over left-dispatch of a base class.
3708
3709 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3710
3711 class B(int):
3712 def __floordiv__(self, other):
3713 return "B.__floordiv__"
3714 def __rfloordiv__(self, other):
3715 return "B.__rfloordiv__"
3716
3717 self.assertEqual(B(1) // 1, "B.__floordiv__")
3718 self.assertEqual(1 // B(1), "B.__rfloordiv__")
3719
3720 # Case 2: subclass of object; this is just the baseline for case 3
3721
3722 class C(object):
3723 def __floordiv__(self, other):
3724 return "C.__floordiv__"
3725 def __rfloordiv__(self, other):
3726 return "C.__rfloordiv__"
3727
3728 self.assertEqual(C() // 1, "C.__floordiv__")
3729 self.assertEqual(1 // C(), "C.__rfloordiv__")
3730
3731 # Case 3: subclass of new-style class; here it gets interesting
3732
3733 class D(C):
3734 def __floordiv__(self, other):
3735 return "D.__floordiv__"
3736 def __rfloordiv__(self, other):
3737 return "D.__rfloordiv__"
3738
3739 self.assertEqual(D() // C(), "D.__floordiv__")
3740 self.assertEqual(C() // D(), "D.__rfloordiv__")
3741
3742 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3743
3744 class E(C):
3745 pass
3746
3747 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
3748
3749 self.assertEqual(E() // 1, "C.__floordiv__")
3750 self.assertEqual(1 // E(), "C.__rfloordiv__")
3751 self.assertEqual(E() // C(), "C.__floordiv__")
3752 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
3753
Benjamin Petersone549ead2009-03-28 21:42:05 +00003754 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00003755 def test_meth_class_get(self):
3756 # Testing __get__ method of METH_CLASS C methods...
3757 # Full coverage of descrobject.c::classmethod_get()
3758
3759 # Baseline
3760 arg = [1, 2, 3]
3761 res = {1: None, 2: None, 3: None}
3762 self.assertEqual(dict.fromkeys(arg), res)
3763 self.assertEqual({}.fromkeys(arg), res)
3764
3765 # Now get the descriptor
3766 descr = dict.__dict__["fromkeys"]
3767
3768 # More baseline using the descriptor directly
3769 self.assertEqual(descr.__get__(None, dict)(arg), res)
3770 self.assertEqual(descr.__get__({})(arg), res)
3771
3772 # Now check various error cases
3773 try:
3774 descr.__get__(None, None)
3775 except TypeError:
3776 pass
3777 else:
3778 self.fail("shouldn't have allowed descr.__get__(None, None)")
3779 try:
3780 descr.__get__(42)
3781 except TypeError:
3782 pass
3783 else:
3784 self.fail("shouldn't have allowed descr.__get__(42)")
3785 try:
3786 descr.__get__(None, 42)
3787 except TypeError:
3788 pass
3789 else:
3790 self.fail("shouldn't have allowed descr.__get__(None, 42)")
3791 try:
3792 descr.__get__(None, int)
3793 except TypeError:
3794 pass
3795 else:
3796 self.fail("shouldn't have allowed descr.__get__(None, int)")
3797
3798 def test_isinst_isclass(self):
3799 # Testing proxy isinstance() and isclass()...
3800 class Proxy(object):
3801 def __init__(self, obj):
3802 self.__obj = obj
3803 def __getattribute__(self, name):
3804 if name.startswith("_Proxy__"):
3805 return object.__getattribute__(self, name)
3806 else:
3807 return getattr(self.__obj, name)
3808 # Test with a classic class
3809 class C:
3810 pass
3811 a = C()
3812 pa = Proxy(a)
3813 self.assert_(isinstance(a, C)) # Baseline
3814 self.assert_(isinstance(pa, C)) # Test
3815 # Test with a classic subclass
3816 class D(C):
3817 pass
3818 a = D()
3819 pa = Proxy(a)
3820 self.assert_(isinstance(a, C)) # Baseline
3821 self.assert_(isinstance(pa, C)) # Test
3822 # Test with a new-style class
3823 class C(object):
3824 pass
3825 a = C()
3826 pa = Proxy(a)
3827 self.assert_(isinstance(a, C)) # Baseline
3828 self.assert_(isinstance(pa, C)) # Test
3829 # Test with a new-style subclass
3830 class D(C):
3831 pass
3832 a = D()
3833 pa = Proxy(a)
3834 self.assert_(isinstance(a, C)) # Baseline
3835 self.assert_(isinstance(pa, C)) # Test
3836
3837 def test_proxy_super(self):
3838 # Testing super() for a proxy object...
3839 class Proxy(object):
3840 def __init__(self, obj):
3841 self.__obj = obj
3842 def __getattribute__(self, name):
3843 if name.startswith("_Proxy__"):
3844 return object.__getattribute__(self, name)
3845 else:
3846 return getattr(self.__obj, name)
3847
3848 class B(object):
3849 def f(self):
3850 return "B.f"
3851
3852 class C(B):
3853 def f(self):
3854 return super(C, self).f() + "->C.f"
3855
3856 obj = C()
3857 p = Proxy(obj)
3858 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
3859
3860 def test_carloverre(self):
3861 # Testing prohibition of Carlo Verre's hack...
3862 try:
3863 object.__setattr__(str, "foo", 42)
3864 except TypeError:
3865 pass
3866 else:
3867 self.fail("Carlo Verre __setattr__ suceeded!")
3868 try:
3869 object.__delattr__(str, "lower")
3870 except TypeError:
3871 pass
3872 else:
3873 self.fail("Carlo Verre __delattr__ succeeded!")
3874
3875 def test_weakref_segfault(self):
3876 # Testing weakref segfault...
3877 # SF 742911
3878 import weakref
3879
3880 class Provoker:
3881 def __init__(self, referrent):
3882 self.ref = weakref.ref(referrent)
3883
3884 def __del__(self):
3885 x = self.ref()
3886
3887 class Oops(object):
3888 pass
3889
3890 o = Oops()
3891 o.whatever = Provoker(o)
3892 del o
3893
3894 def test_wrapper_segfault(self):
3895 # SF 927248: deeply nested wrappers could cause stack overflow
3896 f = lambda:None
3897 for i in range(1000000):
3898 f = f.__call__
3899 f = None
3900
3901 def test_file_fault(self):
3902 # Testing sys.stdout is changed in getattr...
3903 import sys
3904 class StdoutGuard:
3905 def __getattr__(self, attr):
3906 sys.stdout = sys.__stdout__
3907 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
3908 sys.stdout = StdoutGuard()
3909 try:
3910 print("Oops!")
3911 except RuntimeError:
3912 pass
3913
3914 def test_vicious_descriptor_nonsense(self):
3915 # Testing vicious_descriptor_nonsense...
3916
3917 # A potential segfault spotted by Thomas Wouters in mail to
3918 # python-dev 2003-04-17, turned into an example & fixed by Michael
3919 # Hudson just less than four months later...
3920
3921 class Evil(object):
3922 def __hash__(self):
3923 return hash('attr')
3924 def __eq__(self, other):
3925 del C.attr
3926 return 0
3927
3928 class Descr(object):
3929 def __get__(self, ob, type=None):
3930 return 1
3931
3932 class C(object):
3933 attr = Descr()
3934
3935 c = C()
3936 c.__dict__[Evil()] = 0
3937
3938 self.assertEqual(c.attr, 1)
3939 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00003940 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003941 self.assertEqual(hasattr(c, 'attr'), False)
3942
3943 def test_init(self):
3944 # SF 1155938
3945 class Foo(object):
3946 def __init__(self):
3947 return 10
3948 try:
3949 Foo()
3950 except TypeError:
3951 pass
3952 else:
3953 self.fail("did not test __init__() for None return")
3954
3955 def test_method_wrapper(self):
3956 # Testing method-wrapper objects...
3957 # <type 'method-wrapper'> did not support any reflection before 2.5
3958
Mark Dickinson211c6252009-02-01 10:28:51 +00003959 # XXX should methods really support __eq__?
Georg Brandl479a7e72008-02-05 18:13:15 +00003960
3961 l = []
3962 self.assertEqual(l.__add__, l.__add__)
3963 self.assertEqual(l.__add__, [].__add__)
3964 self.assert_(l.__add__ != [5].__add__)
3965 self.assert_(l.__add__ != l.__mul__)
3966 self.assert_(l.__add__.__name__ == '__add__')
Benjamin Petersone549ead2009-03-28 21:42:05 +00003967 if hasattr(l.__add__, '__self__'):
3968 # CPython
3969 self.assert_(l.__add__.__self__ is l)
3970 self.assert_(l.__add__.__objclass__ is list)
3971 else:
3972 # Python implementations where [].__add__ is a normal bound method
3973 self.assert_(l.__add__.im_self is l)
3974 self.assert_(l.__add__.im_class is list)
Georg Brandl479a7e72008-02-05 18:13:15 +00003975 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
3976 try:
3977 hash(l.__add__)
3978 except TypeError:
3979 pass
3980 else:
3981 self.fail("no TypeError from hash([].__add__)")
3982
3983 t = ()
3984 t += (7,)
3985 self.assertEqual(t.__add__, (7,).__add__)
3986 self.assertEqual(hash(t.__add__), hash((7,).__add__))
3987
3988 def test_not_implemented(self):
3989 # Testing NotImplemented...
3990 # all binary methods should be able to return a NotImplemented
3991 import sys
3992 import types
3993 import operator
3994
3995 def specialmethod(self, other):
3996 return NotImplemented
3997
3998 def check(expr, x, y):
3999 try:
4000 exec(expr, {'x': x, 'y': y, 'operator': operator})
4001 except TypeError:
4002 pass
4003 else:
4004 self.fail("no TypeError from %r" % (expr,))
4005
4006 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4007 # TypeErrors
4008 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4009 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004010 for name, expr, iexpr in [
4011 ('__add__', 'x + y', 'x += y'),
4012 ('__sub__', 'x - y', 'x -= y'),
4013 ('__mul__', 'x * y', 'x *= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004014 ('__truediv__', 'operator.truediv(x, y)', None),
4015 ('__floordiv__', 'operator.floordiv(x, y)', None),
4016 ('__div__', 'x / y', 'x /= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004017 ('__mod__', 'x % y', 'x %= y'),
4018 ('__divmod__', 'divmod(x, y)', None),
4019 ('__pow__', 'x ** y', 'x **= y'),
4020 ('__lshift__', 'x << y', 'x <<= y'),
4021 ('__rshift__', 'x >> y', 'x >>= y'),
4022 ('__and__', 'x & y', 'x &= y'),
4023 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004024 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004025 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004026 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004027 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004028 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004029 check(expr, a, N1)
4030 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004031 if iexpr:
4032 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004033 check(iexpr, a, N1)
4034 check(iexpr, a, N2)
4035 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004036 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004037 c = C()
4038 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004039 check(iexpr, c, N1)
4040 check(iexpr, c, N2)
4041
Georg Brandl479a7e72008-02-05 18:13:15 +00004042 def test_assign_slice(self):
4043 # ceval.c's assign_slice used to check for
4044 # tp->tp_as_sequence->sq_slice instead of
4045 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004046
Georg Brandl479a7e72008-02-05 18:13:15 +00004047 class C(object):
4048 def __setitem__(self, idx, value):
4049 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004050
Georg Brandl479a7e72008-02-05 18:13:15 +00004051 c = C()
4052 c[1:2] = 3
4053 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004054
Benjamin Peterson9262b842008-11-17 22:45:50 +00004055 def test_getattr_hooks(self):
4056 # issue 4230
4057
4058 class Descriptor(object):
4059 counter = 0
4060 def __get__(self, obj, objtype=None):
4061 def getter(name):
4062 self.counter += 1
4063 raise AttributeError(name)
4064 return getter
4065
4066 descr = Descriptor()
4067 class A(object):
4068 __getattribute__ = descr
4069 class B(object):
4070 __getattr__ = descr
4071 class C(object):
4072 __getattribute__ = descr
4073 __getattr__ = descr
4074
4075 self.assertRaises(AttributeError, getattr, A(), "attr")
4076 self.assertEquals(descr.counter, 1)
4077 self.assertRaises(AttributeError, getattr, B(), "attr")
4078 self.assertEquals(descr.counter, 2)
4079 self.assertRaises(AttributeError, getattr, C(), "attr")
4080 self.assertEquals(descr.counter, 4)
4081
4082 import gc
4083 class EvilGetattribute(object):
4084 # This used to segfault
4085 def __getattr__(self, name):
4086 raise AttributeError(name)
4087 def __getattribute__(self, name):
4088 del EvilGetattribute.__getattr__
4089 for i in range(5):
4090 gc.collect()
4091 raise AttributeError(name)
4092
4093 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4094
Christian Heimesbbffeb62008-01-24 09:42:52 +00004095
Georg Brandl479a7e72008-02-05 18:13:15 +00004096class DictProxyTests(unittest.TestCase):
4097 def setUp(self):
4098 class C(object):
4099 def meth(self):
4100 pass
4101 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004102
Georg Brandl479a7e72008-02-05 18:13:15 +00004103 def test_iter_keys(self):
4104 # Testing dict-proxy iterkeys...
4105 keys = [ key for key in self.C.__dict__.keys() ]
4106 keys.sort()
4107 self.assertEquals(keys, ['__dict__', '__doc__', '__module__',
4108 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004109
Georg Brandl479a7e72008-02-05 18:13:15 +00004110 def test_iter_values(self):
4111 # Testing dict-proxy itervalues...
4112 values = [ values for values in self.C.__dict__.values() ]
4113 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004114
Georg Brandl479a7e72008-02-05 18:13:15 +00004115 def test_iter_items(self):
4116 # Testing dict-proxy iteritems...
4117 keys = [ key for (key, value) in self.C.__dict__.items() ]
4118 keys.sort()
4119 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4120 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004121
Georg Brandl479a7e72008-02-05 18:13:15 +00004122 def test_dict_type_with_metaclass(self):
4123 # Testing type of __dict__ when metaclass set...
4124 class B(object):
4125 pass
4126 class M(type):
4127 pass
4128 class C(metaclass=M):
4129 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4130 pass
4131 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004132
Christian Heimesbbffeb62008-01-24 09:42:52 +00004133
Georg Brandl479a7e72008-02-05 18:13:15 +00004134class PTypesLongInitTest(unittest.TestCase):
4135 # This is in its own TestCase so that it can be run before any other tests.
4136 def test_pytype_long_ready(self):
4137 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004138
Georg Brandl479a7e72008-02-05 18:13:15 +00004139 # This dumps core when SF bug 551412 isn't fixed --
4140 # but only when test_descr.py is run separately.
4141 # (That can't be helped -- as soon as PyType_Ready()
4142 # is called for PyLong_Type, the bug is gone.)
4143 class UserLong(object):
4144 def __pow__(self, *args):
4145 pass
4146 try:
4147 pow(0, UserLong(), 0)
4148 except:
4149 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004150
Georg Brandl479a7e72008-02-05 18:13:15 +00004151 # Another segfault only when run early
4152 # (before PyType_Ready(tuple) is called)
4153 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004154
4155
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004156def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00004157 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004158 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Georg Brandl479a7e72008-02-05 18:13:15 +00004159 ClassPropertiesAndMethods, DictProxyTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004160
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004161if __name__ == "__main__":
4162 test_main()