blob: 5c505715a8e6a38265ddcc3bfd02447a73ace17c [file] [log] [blame]
Benjamin Petersonae937c02009-04-18 20:54:08 +00001import builtins
Benjamin Petersona5758c02009-05-09 18:15:04 +00002import sys
Guido van Rossum360e4b82007-05-14 22:51:27 +00003import types
Georg Brandl479a7e72008-02-05 18:13:15 +00004import unittest
5import warnings
Tim Peters4d9b4662002-04-16 01:59:17 +00006
Georg Brandl479a7e72008-02-05 18:13:15 +00007from copy import deepcopy
Benjamin Petersonee8712c2008-05-20 21:35:26 +00008from test import support
Guido van Rossum875eeaa2001-10-11 18:33:53 +00009
Tim Peters6d6c1a32001-08-02 04:15:00 +000010
Georg Brandl479a7e72008-02-05 18:13:15 +000011class OperatorsTest(unittest.TestCase):
Tim Peters3caca232001-12-06 06:23:26 +000012
Georg Brandl479a7e72008-02-05 18:13:15 +000013 def __init__(self, *args, **kwargs):
14 unittest.TestCase.__init__(self, *args, **kwargs)
15 self.binops = {
16 'add': '+',
17 'sub': '-',
18 'mul': '*',
19 'div': '/',
20 'divmod': 'divmod',
21 'pow': '**',
22 'lshift': '<<',
23 'rshift': '>>',
24 'and': '&',
25 'xor': '^',
26 'or': '|',
27 'cmp': 'cmp',
28 'lt': '<',
29 'le': '<=',
30 'eq': '==',
31 'ne': '!=',
32 'gt': '>',
33 'ge': '>=',
34 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000035
Georg Brandl479a7e72008-02-05 18:13:15 +000036 for name, expr in list(self.binops.items()):
37 if expr.islower():
38 expr = expr + "(a, b)"
39 else:
40 expr = 'a %s b' % expr
41 self.binops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000042
Georg Brandl479a7e72008-02-05 18:13:15 +000043 self.unops = {
44 'pos': '+',
45 'neg': '-',
46 'abs': 'abs',
47 'invert': '~',
48 'int': 'int',
49 'float': 'float',
50 'oct': 'oct',
51 'hex': 'hex',
52 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000053
Georg Brandl479a7e72008-02-05 18:13:15 +000054 for name, expr in list(self.unops.items()):
55 if expr.islower():
56 expr = expr + "(a)"
57 else:
58 expr = '%s a' % expr
59 self.unops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000060
Georg Brandl479a7e72008-02-05 18:13:15 +000061 def unop_test(self, a, res, expr="len(a)", meth="__len__"):
62 d = {'a': a}
63 self.assertEqual(eval(expr, d), res)
64 t = type(a)
65 m = getattr(t, meth)
Tim Peters6d6c1a32001-08-02 04:15:00 +000066
Georg Brandl479a7e72008-02-05 18:13:15 +000067 # Find method in parent class
68 while meth not in t.__dict__:
69 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000070 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
71 # method object; the getattr() below obtains its underlying function.
72 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000073 self.assertEqual(m(a), res)
74 bm = getattr(a, meth)
75 self.assertEqual(bm(), res)
Tim Peters2f93e282001-10-04 05:27:00 +000076
Georg Brandl479a7e72008-02-05 18:13:15 +000077 def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
78 d = {'a': a, 'b': b}
Tim Peters2f93e282001-10-04 05:27:00 +000079
Georg Brandl479a7e72008-02-05 18:13:15 +000080 # XXX Hack so this passes before 2.3 when -Qnew is specified.
81 if meth == "__div__" and 1/2 == 0.5:
82 meth = "__truediv__"
Tim Peters2f93e282001-10-04 05:27:00 +000083
Georg Brandl479a7e72008-02-05 18:13:15 +000084 if meth == '__divmod__': pass
Tim Peters2f93e282001-10-04 05:27:00 +000085
Georg Brandl479a7e72008-02-05 18:13:15 +000086 self.assertEqual(eval(expr, d), res)
87 t = type(a)
88 m = getattr(t, meth)
89 while meth not in t.__dict__:
90 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000091 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
92 # method object; the getattr() below obtains its underlying function.
93 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000094 self.assertEqual(m(a, b), res)
95 bm = getattr(a, meth)
96 self.assertEqual(bm(b), res)
Tim Peters2f93e282001-10-04 05:27:00 +000097
Georg Brandl479a7e72008-02-05 18:13:15 +000098 def sliceop_test(self, a, b, c, res, expr="a[b:c]", meth="__getitem__"):
99 d = {'a': a, 'b': b, 'c': c}
100 self.assertEqual(eval(expr, d), res)
101 t = type(a)
102 m = getattr(t, meth)
103 while meth not in t.__dict__:
104 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000105 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
106 # method object; the getattr() below obtains its underlying function.
107 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000108 self.assertEqual(m(a, slice(b, c)), res)
109 bm = getattr(a, meth)
110 self.assertEqual(bm(slice(b, c)), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000111
Georg Brandl479a7e72008-02-05 18:13:15 +0000112 def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
113 d = {'a': deepcopy(a), 'b': b}
114 exec(stmt, d)
115 self.assertEqual(d['a'], res)
116 t = type(a)
117 m = getattr(t, meth)
118 while meth not in t.__dict__:
119 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000120 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
121 # method object; the getattr() below obtains its underlying function.
122 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000123 d['a'] = deepcopy(a)
124 m(d['a'], b)
125 self.assertEqual(d['a'], res)
126 d['a'] = deepcopy(a)
127 bm = getattr(d['a'], meth)
128 bm(b)
129 self.assertEqual(d['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000130
Georg Brandl479a7e72008-02-05 18:13:15 +0000131 def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
132 d = {'a': deepcopy(a), 'b': b, 'c': c}
133 exec(stmt, d)
134 self.assertEqual(d['a'], res)
135 t = type(a)
136 m = getattr(t, meth)
137 while meth not in t.__dict__:
138 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000139 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
140 # method object; the getattr() below obtains its underlying function.
141 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000142 d['a'] = deepcopy(a)
143 m(d['a'], b, c)
144 self.assertEqual(d['a'], res)
145 d['a'] = deepcopy(a)
146 bm = getattr(d['a'], meth)
147 bm(b, c)
148 self.assertEqual(d['a'], res)
149
150 def setsliceop_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setitem__"):
151 dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
152 exec(stmt, dictionary)
153 self.assertEqual(dictionary['a'], res)
154 t = type(a)
155 while meth not in t.__dict__:
156 t = t.__bases__[0]
157 m = getattr(t, meth)
Benjamin Petersone549ead2009-03-28 21:42:05 +0000158 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
159 # method object; the getattr() below obtains its underlying function.
160 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000161 dictionary['a'] = deepcopy(a)
162 m(dictionary['a'], slice(b, c), d)
163 self.assertEqual(dictionary['a'], res)
164 dictionary['a'] = deepcopy(a)
165 bm = getattr(dictionary['a'], meth)
166 bm(slice(b, c), d)
167 self.assertEqual(dictionary['a'], res)
168
169 def test_lists(self):
170 # Testing list operations...
171 # Asserts are within individual test methods
172 self.binop_test([1], [2], [1,2], "a+b", "__add__")
173 self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
174 self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
175 self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
176 self.sliceop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getitem__")
177 self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
178 self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
179 self.unop_test([1,2,3], 3, "len(a)", "__len__")
180 self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
181 self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
182 self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
183 self.setsliceop_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
184 "__setitem__")
185
186 def test_dicts(self):
187 # Testing dict operations...
Georg Brandl479a7e72008-02-05 18:13:15 +0000188 self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
189 self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
190 self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
191
192 d = {1:2, 3:4}
193 l1 = []
194 for i in list(d.keys()):
195 l1.append(i)
196 l = []
197 for i in iter(d):
198 l.append(i)
199 self.assertEqual(l, l1)
200 l = []
201 for i in d.__iter__():
202 l.append(i)
203 self.assertEqual(l, l1)
204 l = []
205 for i in dict.__iter__(d):
206 l.append(i)
207 self.assertEqual(l, l1)
208 d = {1:2, 3:4}
209 self.unop_test(d, 2, "len(a)", "__len__")
210 self.assertEqual(eval(repr(d), {}), d)
211 self.assertEqual(eval(d.__repr__(), {}), d)
212 self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
213 "__setitem__")
214
215 # Tests for unary and binary operators
216 def number_operators(self, a, b, skip=[]):
217 dict = {'a': a, 'b': b}
218
219 for name, expr in list(self.binops.items()):
220 if name not in skip:
221 name = "__%s__" % name
222 if hasattr(a, name):
223 res = eval(expr, dict)
224 self.binop_test(a, b, res, expr, name)
225
226 for name, expr in list(self.unops.items()):
227 if name not in skip:
228 name = "__%s__" % name
229 if hasattr(a, name):
230 res = eval(expr, dict)
231 self.unop_test(a, res, expr, name)
232
233 def test_ints(self):
234 # Testing int operations...
235 self.number_operators(100, 3)
236 # The following crashes in Python 2.2
237 self.assertEqual((1).__bool__(), 1)
238 self.assertEqual((0).__bool__(), 0)
239 # This returns 'NotImplemented' in Python 2.2
240 class C(int):
241 def __add__(self, other):
242 return NotImplemented
243 self.assertEqual(C(5), 5)
Tim Peters25786c02001-09-02 08:22:48 +0000244 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000245 C() + ""
Tim Peters25786c02001-09-02 08:22:48 +0000246 except TypeError:
247 pass
248 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000249 self.fail("NotImplemented should have caused TypeError")
Tim Peters25786c02001-09-02 08:22:48 +0000250
Georg Brandl479a7e72008-02-05 18:13:15 +0000251 def test_longs(self):
252 # Testing long operations...
253 self.number_operators(100, 3)
Tim Peters25786c02001-09-02 08:22:48 +0000254
Georg Brandl479a7e72008-02-05 18:13:15 +0000255 def test_floats(self):
256 # Testing float operations...
257 self.number_operators(100.0, 3.0)
Tim Peters25786c02001-09-02 08:22:48 +0000258
Georg Brandl479a7e72008-02-05 18:13:15 +0000259 def test_complexes(self):
260 # Testing complex operations...
261 self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
262 'int', 'long', 'float',
263 'divmod', 'mod'])
Tim Peters25786c02001-09-02 08:22:48 +0000264
Georg Brandl479a7e72008-02-05 18:13:15 +0000265 class Number(complex):
266 __slots__ = ['prec']
267 def __new__(cls, *args, **kwds):
268 result = complex.__new__(cls, *args)
269 result.prec = kwds.get('prec', 12)
270 return result
271 def __repr__(self):
272 prec = self.prec
273 if self.imag == 0.0:
274 return "%.*g" % (prec, self.real)
275 if self.real == 0.0:
276 return "%.*gj" % (prec, self.imag)
277 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
278 __str__ = __repr__
Tim Peters25786c02001-09-02 08:22:48 +0000279
Georg Brandl479a7e72008-02-05 18:13:15 +0000280 a = Number(3.14, prec=6)
281 self.assertEqual(repr(a), "3.14")
282 self.assertEqual(a.prec, 6)
Tim Peters1fc240e2001-10-26 05:06:50 +0000283
Georg Brandl479a7e72008-02-05 18:13:15 +0000284 a = Number(a, prec=2)
285 self.assertEqual(repr(a), "3.1")
286 self.assertEqual(a.prec, 2)
Tim Peters1fc240e2001-10-26 05:06:50 +0000287
Georg Brandl479a7e72008-02-05 18:13:15 +0000288 a = Number(234.5)
289 self.assertEqual(repr(a), "234.5")
290 self.assertEqual(a.prec, 12)
Tim Peters1fc240e2001-10-26 05:06:50 +0000291
Benjamin Petersone549ead2009-03-28 21:42:05 +0000292 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000293 def test_spam_lists(self):
294 # Testing spamlist operations...
295 import copy, xxsubtype as spam
296
297 def spamlist(l, memo=None):
298 import xxsubtype as spam
299 return spam.spamlist(l)
300
301 # This is an ugly hack:
302 copy._deepcopy_dispatch[spam.spamlist] = spamlist
303
304 self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
305 "__add__")
306 self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
307 self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
308 self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
309 self.sliceop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
310 "__getitem__")
311 self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
312 "__iadd__")
313 self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
314 "__imul__")
315 self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
316 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
317 "__mul__")
318 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
319 "__rmul__")
320 self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
321 "__setitem__")
322 self.setsliceop_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
323 spamlist([1,5,6,4]), "a[b:c]=d", "__setitem__")
324 # Test subclassing
325 class C(spam.spamlist):
326 def foo(self): return 1
327 a = C()
328 self.assertEqual(a, [])
329 self.assertEqual(a.foo(), 1)
330 a.append(100)
331 self.assertEqual(a, [100])
332 self.assertEqual(a.getstate(), 0)
333 a.setstate(42)
334 self.assertEqual(a.getstate(), 42)
335
Benjamin Petersone549ead2009-03-28 21:42:05 +0000336 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000337 def test_spam_dicts(self):
338 # Testing spamdict operations...
339 import copy, xxsubtype as spam
340 def spamdict(d, memo=None):
341 import xxsubtype as spam
342 sd = spam.spamdict()
343 for k, v in list(d.items()):
344 sd[k] = v
345 return sd
346 # This is an ugly hack:
347 copy._deepcopy_dispatch[spam.spamdict] = spamdict
348
Georg Brandl479a7e72008-02-05 18:13:15 +0000349 self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
350 self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
351 self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
352 d = spamdict({1:2,3:4})
353 l1 = []
354 for i in list(d.keys()):
355 l1.append(i)
356 l = []
357 for i in iter(d):
358 l.append(i)
359 self.assertEqual(l, l1)
360 l = []
361 for i in d.__iter__():
362 l.append(i)
363 self.assertEqual(l, l1)
364 l = []
365 for i in type(spamdict({})).__iter__(d):
366 l.append(i)
367 self.assertEqual(l, l1)
368 straightd = {1:2, 3:4}
369 spamd = spamdict(straightd)
370 self.unop_test(spamd, 2, "len(a)", "__len__")
371 self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
372 self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
373 "a[b]=c", "__setitem__")
374 # Test subclassing
375 class C(spam.spamdict):
376 def foo(self): return 1
377 a = C()
378 self.assertEqual(list(a.items()), [])
379 self.assertEqual(a.foo(), 1)
380 a['foo'] = 'bar'
381 self.assertEqual(list(a.items()), [('foo', 'bar')])
382 self.assertEqual(a.getstate(), 0)
383 a.setstate(100)
384 self.assertEqual(a.getstate(), 100)
385
386class ClassPropertiesAndMethods(unittest.TestCase):
387
388 def test_python_dicts(self):
389 # Testing Python subclass of dict...
390 self.assert_(issubclass(dict, dict))
391 self.assert_(isinstance({}, dict))
392 d = dict()
393 self.assertEqual(d, {})
394 self.assert_(d.__class__ is dict)
395 self.assert_(isinstance(d, dict))
396 class C(dict):
397 state = -1
398 def __init__(self_local, *a, **kw):
399 if a:
400 self.assertEqual(len(a), 1)
401 self_local.state = a[0]
402 if kw:
403 for k, v in list(kw.items()):
404 self_local[v] = k
405 def __getitem__(self, key):
406 return self.get(key, 0)
407 def __setitem__(self_local, key, value):
408 self.assert_(isinstance(key, type(0)))
409 dict.__setitem__(self_local, key, value)
410 def setstate(self, state):
411 self.state = state
412 def getstate(self):
413 return self.state
414 self.assert_(issubclass(C, dict))
415 a1 = C(12)
416 self.assertEqual(a1.state, 12)
417 a2 = C(foo=1, bar=2)
418 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
419 a = C()
420 self.assertEqual(a.state, -1)
421 self.assertEqual(a.getstate(), -1)
422 a.setstate(0)
423 self.assertEqual(a.state, 0)
424 self.assertEqual(a.getstate(), 0)
425 a.setstate(10)
426 self.assertEqual(a.state, 10)
427 self.assertEqual(a.getstate(), 10)
428 self.assertEqual(a[42], 0)
429 a[42] = 24
430 self.assertEqual(a[42], 24)
431 N = 50
432 for i in range(N):
433 a[i] = C()
434 for j in range(N):
435 a[i][j] = i*j
436 for i in range(N):
437 for j in range(N):
438 self.assertEqual(a[i][j], i*j)
439
440 def test_python_lists(self):
441 # Testing Python subclass of list...
442 class C(list):
443 def __getitem__(self, i):
444 if isinstance(i, slice):
445 return i.start, i.stop
446 return list.__getitem__(self, i) + 100
447 a = C()
448 a.extend([0,1,2])
449 self.assertEqual(a[0], 100)
450 self.assertEqual(a[1], 101)
451 self.assertEqual(a[2], 102)
452 self.assertEqual(a[100:200], (100,200))
453
454 def test_metaclass(self):
Georg Brandle81f5ef2008-05-27 20:34:09 +0000455 # Testing metaclasses...
Georg Brandl479a7e72008-02-05 18:13:15 +0000456 class C(metaclass=type):
457 def __init__(self):
458 self.__state = 0
459 def getstate(self):
460 return self.__state
461 def setstate(self, state):
462 self.__state = state
463 a = C()
464 self.assertEqual(a.getstate(), 0)
465 a.setstate(10)
466 self.assertEqual(a.getstate(), 10)
467 class _metaclass(type):
468 def myself(cls): return cls
469 class D(metaclass=_metaclass):
470 pass
471 self.assertEqual(D.myself(), D)
472 d = D()
473 self.assertEqual(d.__class__, D)
474 class M1(type):
475 def __new__(cls, name, bases, dict):
476 dict['__spam__'] = 1
477 return type.__new__(cls, name, bases, dict)
478 class C(metaclass=M1):
479 pass
480 self.assertEqual(C.__spam__, 1)
481 c = C()
482 self.assertEqual(c.__spam__, 1)
483
484 class _instance(object):
485 pass
486 class M2(object):
487 @staticmethod
488 def __new__(cls, name, bases, dict):
489 self = object.__new__(cls)
490 self.name = name
491 self.bases = bases
492 self.dict = dict
493 return self
494 def __call__(self):
495 it = _instance()
496 # Early binding of methods
497 for key in self.dict:
498 if key.startswith("__"):
499 continue
500 setattr(it, key, self.dict[key].__get__(it, self))
501 return it
502 class C(metaclass=M2):
503 def spam(self):
504 return 42
505 self.assertEqual(C.name, 'C')
506 self.assertEqual(C.bases, ())
507 self.assert_('spam' in C.dict)
508 c = C()
509 self.assertEqual(c.spam(), 42)
510
511 # More metaclass examples
512
513 class autosuper(type):
514 # Automatically add __super to the class
515 # This trick only works for dynamic classes
516 def __new__(metaclass, name, bases, dict):
517 cls = super(autosuper, metaclass).__new__(metaclass,
518 name, bases, dict)
519 # Name mangling for __super removes leading underscores
520 while name[:1] == "_":
521 name = name[1:]
522 if name:
523 name = "_%s__super" % name
524 else:
525 name = "__super"
526 setattr(cls, name, super(cls))
527 return cls
528 class A(metaclass=autosuper):
529 def meth(self):
530 return "A"
531 class B(A):
532 def meth(self):
533 return "B" + self.__super.meth()
534 class C(A):
535 def meth(self):
536 return "C" + self.__super.meth()
537 class D(C, B):
538 def meth(self):
539 return "D" + self.__super.meth()
540 self.assertEqual(D().meth(), "DCBA")
541 class E(B, C):
542 def meth(self):
543 return "E" + self.__super.meth()
544 self.assertEqual(E().meth(), "EBCA")
545
546 class autoproperty(type):
547 # Automatically create property attributes when methods
548 # named _get_x and/or _set_x are found
549 def __new__(metaclass, name, bases, dict):
550 hits = {}
551 for key, val in dict.items():
552 if key.startswith("_get_"):
553 key = key[5:]
554 get, set = hits.get(key, (None, None))
555 get = val
556 hits[key] = get, set
557 elif key.startswith("_set_"):
558 key = key[5:]
559 get, set = hits.get(key, (None, None))
560 set = val
561 hits[key] = get, set
562 for key, (get, set) in hits.items():
563 dict[key] = property(get, set)
564 return super(autoproperty, metaclass).__new__(metaclass,
565 name, bases, dict)
566 class A(metaclass=autoproperty):
567 def _get_x(self):
568 return -self.__x
569 def _set_x(self, x):
570 self.__x = -x
571 a = A()
572 self.assert_(not hasattr(a, "x"))
573 a.x = 12
574 self.assertEqual(a.x, 12)
575 self.assertEqual(a._A__x, -12)
576
577 class multimetaclass(autoproperty, autosuper):
578 # Merge of multiple cooperating metaclasses
579 pass
580 class A(metaclass=multimetaclass):
581 def _get_x(self):
582 return "A"
583 class B(A):
584 def _get_x(self):
585 return "B" + self.__super._get_x()
586 class C(A):
587 def _get_x(self):
588 return "C" + self.__super._get_x()
589 class D(C, B):
590 def _get_x(self):
591 return "D" + self.__super._get_x()
592 self.assertEqual(D().x, "DCBA")
593
594 # Make sure type(x) doesn't call x.__class__.__init__
595 class T(type):
596 counter = 0
597 def __init__(self, *args):
598 T.counter += 1
599 class C(metaclass=T):
600 pass
601 self.assertEqual(T.counter, 1)
602 a = C()
603 self.assertEqual(type(a), C)
604 self.assertEqual(T.counter, 1)
605
606 class C(object): pass
607 c = C()
608 try: c()
609 except TypeError: pass
610 else: self.fail("calling object w/o call method should raise "
611 "TypeError")
612
613 # Testing code to find most derived baseclass
614 class A(type):
615 def __new__(*args, **kwargs):
616 return type.__new__(*args, **kwargs)
617
618 class B(object):
619 pass
620
621 class C(object, metaclass=A):
622 pass
623
624 # The most derived metaclass of D is A rather than type.
625 class D(B, C):
626 pass
627
628 def test_module_subclasses(self):
629 # Testing Python subclass of module...
630 log = []
631 import types, sys
632 MT = type(sys)
633 class MM(MT):
634 def __init__(self, name):
635 MT.__init__(self, name)
636 def __getattribute__(self, name):
637 log.append(("getattr", name))
638 return MT.__getattribute__(self, name)
639 def __setattr__(self, name, value):
640 log.append(("setattr", name, value))
641 MT.__setattr__(self, name, value)
642 def __delattr__(self, name):
643 log.append(("delattr", name))
644 MT.__delattr__(self, name)
645 a = MM("a")
646 a.foo = 12
647 x = a.foo
648 del a.foo
649 self.assertEqual(log, [("setattr", "foo", 12),
650 ("getattr", "foo"),
651 ("delattr", "foo")])
652
653 # http://python.org/sf/1174712
Tim Peters1fc240e2001-10-26 05:06:50 +0000654 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000655 class Module(types.ModuleType, str):
656 pass
657 except TypeError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000658 pass
659 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000660 self.fail("inheriting from ModuleType and str at the same time "
661 "should fail")
Tim Peters1fc240e2001-10-26 05:06:50 +0000662
Georg Brandl479a7e72008-02-05 18:13:15 +0000663 def test_multiple_inheritance(self):
664 # Testing multiple inheritance...
665 class C(object):
666 def __init__(self):
667 self.__state = 0
668 def getstate(self):
669 return self.__state
670 def setstate(self, state):
671 self.__state = state
672 a = C()
673 self.assertEqual(a.getstate(), 0)
674 a.setstate(10)
675 self.assertEqual(a.getstate(), 10)
676 class D(dict, C):
677 def __init__(self):
678 type({}).__init__(self)
679 C.__init__(self)
680 d = D()
681 self.assertEqual(list(d.keys()), [])
682 d["hello"] = "world"
683 self.assertEqual(list(d.items()), [("hello", "world")])
684 self.assertEqual(d["hello"], "world")
685 self.assertEqual(d.getstate(), 0)
686 d.setstate(10)
687 self.assertEqual(d.getstate(), 10)
688 self.assertEqual(D.__mro__, (D, dict, C, object))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000689
Georg Brandl479a7e72008-02-05 18:13:15 +0000690 # SF bug #442833
691 class Node(object):
692 def __int__(self):
693 return int(self.foo())
694 def foo(self):
695 return "23"
696 class Frag(Node, list):
697 def foo(self):
698 return "42"
699 self.assertEqual(Node().__int__(), 23)
700 self.assertEqual(int(Node()), 23)
701 self.assertEqual(Frag().__int__(), 42)
702 self.assertEqual(int(Frag()), 42)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000703
Georg Brandl479a7e72008-02-05 18:13:15 +0000704 def test_diamond_inheritence(self):
705 # Testing multiple inheritance special cases...
706 class A(object):
707 def spam(self): return "A"
708 self.assertEqual(A().spam(), "A")
709 class B(A):
710 def boo(self): return "B"
711 def spam(self): return "B"
712 self.assertEqual(B().spam(), "B")
713 self.assertEqual(B().boo(), "B")
714 class C(A):
715 def boo(self): return "C"
716 self.assertEqual(C().spam(), "A")
717 self.assertEqual(C().boo(), "C")
718 class D(B, C): pass
719 self.assertEqual(D().spam(), "B")
720 self.assertEqual(D().boo(), "B")
721 self.assertEqual(D.__mro__, (D, B, C, A, object))
722 class E(C, B): pass
723 self.assertEqual(E().spam(), "B")
724 self.assertEqual(E().boo(), "C")
725 self.assertEqual(E.__mro__, (E, C, B, A, object))
726 # MRO order disagreement
727 try:
728 class F(D, E): pass
729 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000730 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000731 else:
732 self.fail("expected MRO order disagreement (F)")
733 try:
734 class G(E, D): pass
735 except TypeError:
736 pass
737 else:
738 self.fail("expected MRO order disagreement (G)")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000739
Georg Brandl479a7e72008-02-05 18:13:15 +0000740 # see thread python-dev/2002-October/029035.html
741 def test_ex5_from_c3_switch(self):
742 # Testing ex5 from C3 switch discussion...
743 class A(object): pass
744 class B(object): pass
745 class C(object): pass
746 class X(A): pass
747 class Y(A): pass
748 class Z(X,B,Y,C): pass
749 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000750
Georg Brandl479a7e72008-02-05 18:13:15 +0000751 # see "A Monotonic Superclass Linearization for Dylan",
752 # by Kim Barrett et al. (OOPSLA 1996)
753 def test_monotonicity(self):
754 # Testing MRO monotonicity...
755 class Boat(object): pass
756 class DayBoat(Boat): pass
757 class WheelBoat(Boat): pass
758 class EngineLess(DayBoat): pass
759 class SmallMultihull(DayBoat): pass
760 class PedalWheelBoat(EngineLess,WheelBoat): pass
761 class SmallCatamaran(SmallMultihull): pass
762 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
Guido van Rossume45763a2001-08-10 21:28:46 +0000763
Georg Brandl479a7e72008-02-05 18:13:15 +0000764 self.assertEqual(PedalWheelBoat.__mro__,
765 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
766 self.assertEqual(SmallCatamaran.__mro__,
767 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
768 self.assertEqual(Pedalo.__mro__,
769 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
770 SmallMultihull, DayBoat, WheelBoat, Boat, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000771
Georg Brandl479a7e72008-02-05 18:13:15 +0000772 # see "A Monotonic Superclass Linearization for Dylan",
773 # by Kim Barrett et al. (OOPSLA 1996)
774 def test_consistency_with_epg(self):
775 # Testing consistentcy with EPG...
776 class Pane(object): pass
777 class ScrollingMixin(object): pass
778 class EditingMixin(object): pass
779 class ScrollablePane(Pane,ScrollingMixin): pass
780 class EditablePane(Pane,EditingMixin): pass
781 class EditableScrollablePane(ScrollablePane,EditablePane): pass
Guido van Rossum9a818922002-11-14 19:50:14 +0000782
Georg Brandl479a7e72008-02-05 18:13:15 +0000783 self.assertEqual(EditableScrollablePane.__mro__,
784 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
785 ScrollingMixin, EditingMixin, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000786
Georg Brandl479a7e72008-02-05 18:13:15 +0000787 def test_mro_disagreement(self):
788 # Testing error messages for MRO disagreement...
789 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000790order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000791
Georg Brandl479a7e72008-02-05 18:13:15 +0000792 def raises(exc, expected, callable, *args):
Guido van Rossum58da9312007-11-10 23:39:45 +0000793 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000794 callable(*args)
795 except exc as msg:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000796 # the exact msg is generally considered an impl detail
797 if support.check_impl_detail():
798 if not str(msg).startswith(expected):
799 self.fail("Message %r, expected %r" %
800 (str(msg), expected))
Georg Brandl479a7e72008-02-05 18:13:15 +0000801 else:
802 self.fail("Expected %s" % exc)
Guido van Rossum58da9312007-11-10 23:39:45 +0000803
Georg Brandl479a7e72008-02-05 18:13:15 +0000804 class A(object): pass
805 class B(A): pass
806 class C(object): pass
Christian Heimes9a371592007-12-28 14:08:13 +0000807
Georg Brandl479a7e72008-02-05 18:13:15 +0000808 # Test some very simple errors
809 raises(TypeError, "duplicate base class A",
810 type, "X", (A, A), {})
811 raises(TypeError, mro_err_msg,
812 type, "X", (A, B), {})
813 raises(TypeError, mro_err_msg,
814 type, "X", (A, C, B), {})
815 # Test a slightly more complex error
816 class GridLayout(object): pass
817 class HorizontalGrid(GridLayout): pass
818 class VerticalGrid(GridLayout): pass
819 class HVGrid(HorizontalGrid, VerticalGrid): pass
820 class VHGrid(VerticalGrid, HorizontalGrid): pass
821 raises(TypeError, mro_err_msg,
822 type, "ConfusedGrid", (HVGrid, VHGrid), {})
Guido van Rossum58da9312007-11-10 23:39:45 +0000823
Georg Brandl479a7e72008-02-05 18:13:15 +0000824 def test_object_class(self):
825 # Testing object class...
826 a = object()
827 self.assertEqual(a.__class__, object)
828 self.assertEqual(type(a), object)
829 b = object()
830 self.assertNotEqual(a, b)
831 self.assertFalse(hasattr(a, "foo"))
Tim Peters808b94e2001-09-13 19:33:07 +0000832 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000833 a.foo = 12
834 except (AttributeError, TypeError):
Tim Peters808b94e2001-09-13 19:33:07 +0000835 pass
836 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000837 self.fail("object() should not allow setting a foo attribute")
838 self.assertFalse(hasattr(object(), "__dict__"))
Tim Peters561f8992001-09-13 19:36:36 +0000839
Georg Brandl479a7e72008-02-05 18:13:15 +0000840 class Cdict(object):
Guido van Rossum5c294fb2001-09-25 03:43:42 +0000841 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000842 x = Cdict()
843 self.assertEqual(x.__dict__, {})
844 x.foo = 1
845 self.assertEqual(x.foo, 1)
846 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossumd8faa362007-04-27 19:54:29 +0000847
Georg Brandl479a7e72008-02-05 18:13:15 +0000848 def test_slots(self):
849 # Testing __slots__...
850 class C0(object):
851 __slots__ = []
852 x = C0()
853 self.assertFalse(hasattr(x, "__dict__"))
854 self.assertFalse(hasattr(x, "foo"))
855
856 class C1(object):
857 __slots__ = ['a']
858 x = C1()
859 self.assertFalse(hasattr(x, "__dict__"))
860 self.assertFalse(hasattr(x, "a"))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000861 x.a = 1
Georg Brandl479a7e72008-02-05 18:13:15 +0000862 self.assertEqual(x.a, 1)
863 x.a = None
864 self.assertEqual(x.a, None)
865 del x.a
866 self.assertFalse(hasattr(x, "a"))
Guido van Rossum5c294fb2001-09-25 03:43:42 +0000867
Georg Brandl479a7e72008-02-05 18:13:15 +0000868 class C3(object):
869 __slots__ = ['a', 'b', 'c']
870 x = C3()
871 self.assertFalse(hasattr(x, "__dict__"))
872 self.assertFalse(hasattr(x, 'a'))
873 self.assertFalse(hasattr(x, 'b'))
874 self.assertFalse(hasattr(x, 'c'))
875 x.a = 1
876 x.b = 2
877 x.c = 3
878 self.assertEqual(x.a, 1)
879 self.assertEqual(x.b, 2)
880 self.assertEqual(x.c, 3)
881
882 class C4(object):
883 """Validate name mangling"""
884 __slots__ = ['__a']
885 def __init__(self, value):
886 self.__a = value
887 def get(self):
888 return self.__a
889 x = C4(5)
890 self.assertFalse(hasattr(x, '__dict__'))
891 self.assertFalse(hasattr(x, '__a'))
892 self.assertEqual(x.get(), 5)
Guido van Rossum6661be32001-10-26 04:26:12 +0000893 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000894 x.__a = 6
895 except AttributeError:
Guido van Rossum6661be32001-10-26 04:26:12 +0000896 pass
897 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000898 self.fail("Double underscored names not mangled")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000899
Georg Brandl479a7e72008-02-05 18:13:15 +0000900 # Make sure slot names are proper identifiers
Guido van Rossum360e4b82007-05-14 22:51:27 +0000901 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000902 class C(object):
903 __slots__ = [None]
Guido van Rossum360e4b82007-05-14 22:51:27 +0000904 except TypeError:
905 pass
906 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000907 self.fail("[None] slots not caught")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000908 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000909 class C(object):
910 __slots__ = ["foo bar"]
911 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000912 pass
913 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000914 self.fail("['foo bar'] slots not caught")
915 try:
916 class C(object):
917 __slots__ = ["foo\0bar"]
918 except TypeError:
919 pass
920 else:
921 self.fail("['foo\\0bar'] slots not caught")
922 try:
923 class C(object):
924 __slots__ = ["1"]
925 except TypeError:
926 pass
927 else:
928 self.fail("['1'] slots not caught")
929 try:
930 class C(object):
931 __slots__ = [""]
932 except TypeError:
933 pass
934 else:
935 self.fail("[''] slots not caught")
936 class C(object):
937 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
938 # XXX(nnorwitz): was there supposed to be something tested
939 # from the class above?
Guido van Rossum360e4b82007-05-14 22:51:27 +0000940
Georg Brandl479a7e72008-02-05 18:13:15 +0000941 # Test a single string is not expanded as a sequence.
942 class C(object):
943 __slots__ = "abc"
944 c = C()
945 c.abc = 5
946 self.assertEqual(c.abc, 5)
Guido van Rossum6661be32001-10-26 04:26:12 +0000947
Georg Brandl479a7e72008-02-05 18:13:15 +0000948 # Test unicode slot names
949 # Test a single unicode string is not expanded as a sequence.
950 class C(object):
951 __slots__ = "abc"
952 c = C()
953 c.abc = 5
954 self.assertEqual(c.abc, 5)
Guido van Rossum3926a632001-09-25 16:25:58 +0000955
Georg Brandl479a7e72008-02-05 18:13:15 +0000956 # _unicode_to_string used to modify slots in certain circumstances
957 slots = ("foo", "bar")
958 class C(object):
959 __slots__ = slots
960 x = C()
961 x.foo = 5
962 self.assertEqual(x.foo, 5)
963 self.assert_(type(slots[0]) is str)
964 # this used to leak references
965 try:
966 class C(object):
967 __slots__ = [chr(128)]
968 except (TypeError, UnicodeEncodeError):
969 pass
970 else:
971 raise TestFailed("[chr(128)] slots not caught")
Guido van Rossum3926a632001-09-25 16:25:58 +0000972
Georg Brandl479a7e72008-02-05 18:13:15 +0000973 # Test leaks
974 class Counted(object):
975 counter = 0 # counts the number of instances alive
976 def __init__(self):
977 Counted.counter += 1
978 def __del__(self):
979 Counted.counter -= 1
980 class C(object):
981 __slots__ = ['a', 'b', 'c']
982 x = C()
983 x.a = Counted()
984 x.b = Counted()
985 x.c = Counted()
986 self.assertEqual(Counted.counter, 3)
987 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +0000988 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +0000989 self.assertEqual(Counted.counter, 0)
990 class D(C):
991 pass
992 x = D()
993 x.a = Counted()
994 x.z = Counted()
995 self.assertEqual(Counted.counter, 2)
996 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +0000997 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +0000998 self.assertEqual(Counted.counter, 0)
999 class E(D):
1000 __slots__ = ['e']
1001 x = E()
1002 x.a = Counted()
1003 x.z = Counted()
1004 x.e = Counted()
1005 self.assertEqual(Counted.counter, 3)
1006 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001007 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001008 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001009
Georg Brandl479a7e72008-02-05 18:13:15 +00001010 # Test cyclical leaks [SF bug 519621]
1011 class F(object):
1012 __slots__ = ['a', 'b']
1013 log = []
1014 s = F()
1015 s.a = [Counted(), s]
1016 self.assertEqual(Counted.counter, 1)
1017 s = None
Benjamin Petersone549ead2009-03-28 21:42:05 +00001018 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001019 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001020
Georg Brandl479a7e72008-02-05 18:13:15 +00001021 # Test lookup leaks [SF bug 572567]
1022 import sys,gc
Benjamin Petersone549ead2009-03-28 21:42:05 +00001023 if hasattr(gc, 'get_objects'):
1024 class G(object):
1025 def __cmp__(self, other):
1026 return 0
1027 g = G()
1028 orig_objects = len(gc.get_objects())
1029 for i in range(10):
1030 g==g
1031 new_objects = len(gc.get_objects())
1032 self.assertEqual(orig_objects, new_objects)
1033
Georg Brandl479a7e72008-02-05 18:13:15 +00001034 class H(object):
1035 __slots__ = ['a', 'b']
1036 def __init__(self):
1037 self.a = 1
1038 self.b = 2
1039 def __del__(self_):
1040 self.assertEqual(self_.a, 1)
1041 self.assertEqual(self_.b, 2)
Benjamin Petersonc1de4cc2008-11-03 21:29:09 +00001042 with support.captured_output('stderr') as s:
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001043 h = H()
Georg Brandl479a7e72008-02-05 18:13:15 +00001044 del h
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001045 self.assertEqual(s.getvalue(), '')
Guido van Rossum90c45142001-11-24 21:07:01 +00001046
Georg Brandl479a7e72008-02-05 18:13:15 +00001047 def test_slots_special(self):
1048 # Testing __dict__ and __weakref__ in __slots__...
1049 class D(object):
1050 __slots__ = ["__dict__"]
1051 a = D()
1052 self.assert_(hasattr(a, "__dict__"))
1053 self.assertFalse(hasattr(a, "__weakref__"))
1054 a.foo = 42
1055 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum90c45142001-11-24 21:07:01 +00001056
Georg Brandl479a7e72008-02-05 18:13:15 +00001057 class W(object):
1058 __slots__ = ["__weakref__"]
1059 a = W()
1060 self.assert_(hasattr(a, "__weakref__"))
1061 self.assertFalse(hasattr(a, "__dict__"))
1062 try:
1063 a.foo = 42
1064 except AttributeError:
1065 pass
1066 else:
1067 self.fail("shouldn't be allowed to set a.foo")
1068
1069 class C1(W, D):
1070 __slots__ = []
1071 a = C1()
1072 self.assert_(hasattr(a, "__dict__"))
1073 self.assert_(hasattr(a, "__weakref__"))
1074 a.foo = 42
1075 self.assertEqual(a.__dict__, {"foo": 42})
1076
1077 class C2(D, W):
1078 __slots__ = []
1079 a = C2()
1080 self.assert_(hasattr(a, "__dict__"))
1081 self.assert_(hasattr(a, "__weakref__"))
1082 a.foo = 42
1083 self.assertEqual(a.__dict__, {"foo": 42})
1084
Christian Heimesa156e092008-02-16 07:38:31 +00001085 def test_slots_descriptor(self):
1086 # Issue2115: slot descriptors did not correctly check
1087 # the type of the given object
1088 import abc
1089 class MyABC(metaclass=abc.ABCMeta):
1090 __slots__ = "a"
1091
1092 class Unrelated(object):
1093 pass
1094 MyABC.register(Unrelated)
1095
1096 u = Unrelated()
1097 self.assert_(isinstance(u, MyABC))
1098
1099 # This used to crash
1100 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1101
Georg Brandl479a7e72008-02-05 18:13:15 +00001102 def test_dynamics(self):
1103 # Testing class attribute propagation...
1104 class D(object):
1105 pass
1106 class E(D):
1107 pass
1108 class F(D):
1109 pass
1110 D.foo = 1
1111 self.assertEqual(D.foo, 1)
1112 # Test that dynamic attributes are inherited
1113 self.assertEqual(E.foo, 1)
1114 self.assertEqual(F.foo, 1)
1115 # Test dynamic instances
1116 class C(object):
1117 pass
1118 a = C()
1119 self.assertFalse(hasattr(a, "foobar"))
1120 C.foobar = 2
1121 self.assertEqual(a.foobar, 2)
1122 C.method = lambda self: 42
1123 self.assertEqual(a.method(), 42)
1124 C.__repr__ = lambda self: "C()"
1125 self.assertEqual(repr(a), "C()")
1126 C.__int__ = lambda self: 100
1127 self.assertEqual(int(a), 100)
1128 self.assertEqual(a.foobar, 2)
1129 self.assertFalse(hasattr(a, "spam"))
1130 def mygetattr(self, name):
1131 if name == "spam":
1132 return "spam"
1133 raise AttributeError
1134 C.__getattr__ = mygetattr
1135 self.assertEqual(a.spam, "spam")
1136 a.new = 12
1137 self.assertEqual(a.new, 12)
1138 def mysetattr(self, name, value):
1139 if name == "spam":
1140 raise AttributeError
1141 return object.__setattr__(self, name, value)
1142 C.__setattr__ = mysetattr
1143 try:
1144 a.spam = "not spam"
1145 except AttributeError:
1146 pass
1147 else:
1148 self.fail("expected AttributeError")
1149 self.assertEqual(a.spam, "spam")
1150 class D(C):
1151 pass
1152 d = D()
1153 d.foo = 1
1154 self.assertEqual(d.foo, 1)
1155
1156 # Test handling of int*seq and seq*int
1157 class I(int):
1158 pass
1159 self.assertEqual("a"*I(2), "aa")
1160 self.assertEqual(I(2)*"a", "aa")
1161 self.assertEqual(2*I(3), 6)
1162 self.assertEqual(I(3)*2, 6)
1163 self.assertEqual(I(3)*I(2), 6)
1164
1165 # Test handling of long*seq and seq*long
1166 class L(int):
1167 pass
1168 self.assertEqual("a"*L(2), "aa")
1169 self.assertEqual(L(2)*"a", "aa")
1170 self.assertEqual(2*L(3), 6)
1171 self.assertEqual(L(3)*2, 6)
1172 self.assertEqual(L(3)*L(2), 6)
1173
1174 # Test comparison of classes with dynamic metaclasses
1175 class dynamicmetaclass(type):
1176 pass
1177 class someclass(metaclass=dynamicmetaclass):
1178 pass
1179 self.assertNotEqual(someclass, object)
1180
1181 def test_errors(self):
1182 # Testing errors...
1183 try:
1184 class C(list, dict):
1185 pass
1186 except TypeError:
1187 pass
1188 else:
1189 self.fail("inheritance from both list and dict should be illegal")
1190
1191 try:
1192 class C(object, None):
1193 pass
1194 except TypeError:
1195 pass
1196 else:
1197 self.fail("inheritance from non-type should be illegal")
1198 class Classic:
1199 pass
1200
1201 try:
1202 class C(type(len)):
1203 pass
1204 except TypeError:
1205 pass
1206 else:
1207 self.fail("inheritance from CFunction should be illegal")
1208
1209 try:
1210 class C(object):
1211 __slots__ = 1
1212 except TypeError:
1213 pass
1214 else:
1215 self.fail("__slots__ = 1 should be illegal")
1216
1217 try:
1218 class C(object):
1219 __slots__ = [1]
1220 except TypeError:
1221 pass
1222 else:
1223 self.fail("__slots__ = [1] should be illegal")
1224
1225 class M1(type):
1226 pass
1227 class M2(type):
1228 pass
1229 class A1(object, metaclass=M1):
1230 pass
1231 class A2(object, metaclass=M2):
1232 pass
1233 try:
1234 class B(A1, A2):
1235 pass
1236 except TypeError:
1237 pass
1238 else:
1239 self.fail("finding the most derived metaclass should have failed")
1240
1241 def test_classmethods(self):
1242 # Testing class methods...
1243 class C(object):
1244 def foo(*a): return a
1245 goo = classmethod(foo)
1246 c = C()
1247 self.assertEqual(C.goo(1), (C, 1))
1248 self.assertEqual(c.goo(1), (C, 1))
1249 self.assertEqual(c.foo(1), (c, 1))
1250 class D(C):
1251 pass
1252 d = D()
1253 self.assertEqual(D.goo(1), (D, 1))
1254 self.assertEqual(d.goo(1), (D, 1))
1255 self.assertEqual(d.foo(1), (d, 1))
1256 self.assertEqual(D.foo(d, 1), (d, 1))
1257 # Test for a specific crash (SF bug 528132)
1258 def f(cls, arg): return (cls, arg)
1259 ff = classmethod(f)
1260 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1261 self.assertEqual(ff.__get__(0)(42), (int, 42))
1262
1263 # Test super() with classmethods (SF bug 535444)
1264 self.assertEqual(C.goo.__self__, C)
1265 self.assertEqual(D.goo.__self__, D)
1266 self.assertEqual(super(D,D).goo.__self__, D)
1267 self.assertEqual(super(D,d).goo.__self__, D)
1268 self.assertEqual(super(D,D).goo(), (D,))
1269 self.assertEqual(super(D,d).goo(), (D,))
1270
1271 # Verify that argument is checked for callability (SF bug 753451)
1272 try:
1273 classmethod(1).__get__(1)
1274 except TypeError:
1275 pass
1276 else:
1277 self.fail("classmethod should check for callability")
1278
1279 # Verify that classmethod() doesn't allow keyword args
1280 try:
1281 classmethod(f, kw=1)
1282 except TypeError:
1283 pass
1284 else:
1285 self.fail("classmethod shouldn't accept keyword args")
1286
Benjamin Petersone549ead2009-03-28 21:42:05 +00001287 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001288 def test_classmethods_in_c(self):
1289 # Testing C-based class methods...
1290 import xxsubtype as spam
1291 a = (1, 2, 3)
1292 d = {'abc': 123}
1293 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1294 self.assertEqual(x, spam.spamlist)
1295 self.assertEqual(a, a1)
1296 self.assertEqual(d, d1)
1297 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1298 self.assertEqual(x, spam.spamlist)
1299 self.assertEqual(a, a1)
1300 self.assertEqual(d, d1)
1301
1302 def test_staticmethods(self):
1303 # Testing static methods...
1304 class C(object):
1305 def foo(*a): return a
1306 goo = staticmethod(foo)
1307 c = C()
1308 self.assertEqual(C.goo(1), (1,))
1309 self.assertEqual(c.goo(1), (1,))
1310 self.assertEqual(c.foo(1), (c, 1,))
1311 class D(C):
1312 pass
1313 d = D()
1314 self.assertEqual(D.goo(1), (1,))
1315 self.assertEqual(d.goo(1), (1,))
1316 self.assertEqual(d.foo(1), (d, 1))
1317 self.assertEqual(D.foo(d, 1), (d, 1))
1318
Benjamin Petersone549ead2009-03-28 21:42:05 +00001319 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001320 def test_staticmethods_in_c(self):
1321 # Testing C-based static methods...
1322 import xxsubtype as spam
1323 a = (1, 2, 3)
1324 d = {"abc": 123}
1325 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1326 self.assertEqual(x, None)
1327 self.assertEqual(a, a1)
1328 self.assertEqual(d, d1)
1329 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1330 self.assertEqual(x, None)
1331 self.assertEqual(a, a1)
1332 self.assertEqual(d, d1)
1333
1334 def test_classic(self):
1335 # Testing classic classes...
1336 class C:
1337 def foo(*a): return a
1338 goo = classmethod(foo)
1339 c = C()
1340 self.assertEqual(C.goo(1), (C, 1))
1341 self.assertEqual(c.goo(1), (C, 1))
1342 self.assertEqual(c.foo(1), (c, 1))
1343 class D(C):
1344 pass
1345 d = D()
1346 self.assertEqual(D.goo(1), (D, 1))
1347 self.assertEqual(d.goo(1), (D, 1))
1348 self.assertEqual(d.foo(1), (d, 1))
1349 self.assertEqual(D.foo(d, 1), (d, 1))
1350 class E: # *not* subclassing from C
1351 foo = C.foo
1352 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
1353 self.assert_(repr(C.foo.__get__(C())).startswith("<bound method "))
1354
1355 def test_compattr(self):
1356 # Testing computed attributes...
1357 class C(object):
1358 class computed_attribute(object):
1359 def __init__(self, get, set=None, delete=None):
1360 self.__get = get
1361 self.__set = set
1362 self.__delete = delete
1363 def __get__(self, obj, type=None):
1364 return self.__get(obj)
1365 def __set__(self, obj, value):
1366 return self.__set(obj, value)
1367 def __delete__(self, obj):
1368 return self.__delete(obj)
1369 def __init__(self):
1370 self.__x = 0
1371 def __get_x(self):
1372 x = self.__x
1373 self.__x = x+1
1374 return x
1375 def __set_x(self, x):
1376 self.__x = x
1377 def __delete_x(self):
1378 del self.__x
1379 x = computed_attribute(__get_x, __set_x, __delete_x)
1380 a = C()
1381 self.assertEqual(a.x, 0)
1382 self.assertEqual(a.x, 1)
1383 a.x = 10
1384 self.assertEqual(a.x, 10)
1385 self.assertEqual(a.x, 11)
1386 del a.x
1387 self.assertEqual(hasattr(a, 'x'), 0)
1388
1389 def test_newslots(self):
1390 # Testing __new__ slot override...
1391 class C(list):
1392 def __new__(cls):
1393 self = list.__new__(cls)
1394 self.foo = 1
1395 return self
1396 def __init__(self):
1397 self.foo = self.foo + 2
1398 a = C()
1399 self.assertEqual(a.foo, 3)
1400 self.assertEqual(a.__class__, C)
1401 class D(C):
1402 pass
1403 b = D()
1404 self.assertEqual(b.foo, 3)
1405 self.assertEqual(b.__class__, D)
1406
1407 def test_altmro(self):
1408 # Testing mro() and overriding it...
1409 class A(object):
1410 def f(self): return "A"
1411 class B(A):
1412 pass
1413 class C(A):
1414 def f(self): return "C"
1415 class D(B, C):
1416 pass
1417 self.assertEqual(D.mro(), [D, B, C, A, object])
1418 self.assertEqual(D.__mro__, (D, B, C, A, object))
1419 self.assertEqual(D().f(), "C")
1420
1421 class PerverseMetaType(type):
1422 def mro(cls):
1423 L = type.mro(cls)
1424 L.reverse()
1425 return L
1426 class X(D,B,C,A, metaclass=PerverseMetaType):
1427 pass
1428 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1429 self.assertEqual(X().f(), "A")
1430
1431 try:
1432 class _metaclass(type):
1433 def mro(self):
1434 return [self, dict, object]
1435 class X(object, metaclass=_metaclass):
1436 pass
Benjamin Petersone549ead2009-03-28 21:42:05 +00001437 # In CPython, the class creation above already raises
1438 # TypeError, as a protection against the fact that
1439 # instances of X would segfault it. In other Python
1440 # implementations it would be ok to let the class X
1441 # be created, but instead get a clean TypeError on the
1442 # __setitem__ below.
1443 x = object.__new__(X)
1444 x[5] = 6
Georg Brandl479a7e72008-02-05 18:13:15 +00001445 except TypeError:
1446 pass
1447 else:
1448 self.fail("devious mro() return not caught")
1449
1450 try:
1451 class _metaclass(type):
1452 def mro(self):
1453 return [1]
1454 class X(object, metaclass=_metaclass):
1455 pass
1456 except TypeError:
1457 pass
1458 else:
1459 self.fail("non-class mro() return not caught")
1460
1461 try:
1462 class _metaclass(type):
1463 def mro(self):
1464 return 1
1465 class X(object, metaclass=_metaclass):
1466 pass
1467 except TypeError:
1468 pass
1469 else:
1470 self.fail("non-sequence mro() return not caught")
1471
1472 def test_overloading(self):
1473 # Testing operator overloading...
1474
1475 class B(object):
1476 "Intermediate class because object doesn't have a __setattr__"
1477
1478 class C(B):
1479 def __getattr__(self, name):
1480 if name == "foo":
1481 return ("getattr", name)
1482 else:
1483 raise AttributeError
1484 def __setattr__(self, name, value):
1485 if name == "foo":
1486 self.setattr = (name, value)
1487 else:
1488 return B.__setattr__(self, name, value)
1489 def __delattr__(self, name):
1490 if name == "foo":
1491 self.delattr = name
1492 else:
1493 return B.__delattr__(self, name)
1494
1495 def __getitem__(self, key):
1496 return ("getitem", key)
1497 def __setitem__(self, key, value):
1498 self.setitem = (key, value)
1499 def __delitem__(self, key):
1500 self.delitem = key
1501
1502 a = C()
1503 self.assertEqual(a.foo, ("getattr", "foo"))
1504 a.foo = 12
1505 self.assertEqual(a.setattr, ("foo", 12))
1506 del a.foo
1507 self.assertEqual(a.delattr, "foo")
1508
1509 self.assertEqual(a[12], ("getitem", 12))
1510 a[12] = 21
1511 self.assertEqual(a.setitem, (12, 21))
1512 del a[12]
1513 self.assertEqual(a.delitem, 12)
1514
1515 self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1516 a[0:10] = "foo"
1517 self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1518 del a[0:10]
1519 self.assertEqual(a.delitem, (slice(0, 10)))
1520
1521 def test_methods(self):
1522 # Testing methods...
1523 class C(object):
1524 def __init__(self, x):
1525 self.x = x
1526 def foo(self):
1527 return self.x
1528 c1 = C(1)
1529 self.assertEqual(c1.foo(), 1)
1530 class D(C):
1531 boo = C.foo
1532 goo = c1.foo
1533 d2 = D(2)
1534 self.assertEqual(d2.foo(), 2)
1535 self.assertEqual(d2.boo(), 2)
1536 self.assertEqual(d2.goo(), 1)
1537 class E(object):
1538 foo = C.foo
1539 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
1540 self.assert_(repr(C.foo.__get__(C(1))).startswith("<bound method "))
1541
Benjamin Peterson224205f2009-05-08 03:25:19 +00001542 def test_special_method_lookup(self):
1543 # The lookup of special methods bypasses __getattr__ and
1544 # __getattribute__, but they still can be descriptors.
1545
1546 def run_context(manager):
1547 with manager:
1548 pass
1549 def iden(self):
1550 return self
1551 def hello(self):
1552 return b"hello"
Benjamin Peterson053c61f2009-05-09 17:21:13 +00001553 def empty_seq(self):
1554 return []
Benjamin Petersona5758c02009-05-09 18:15:04 +00001555 def zero(self):
1556 return 0
1557 def stop(self):
1558 raise StopIteration
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001559 def return_true(self, thing=None):
1560 return True
1561 def do_isinstance(obj):
1562 return isinstance(int, obj)
1563 def do_issubclass(obj):
1564 return issubclass(int, obj)
Benjamin Petersona7205592009-05-27 03:08:59 +00001565 def do_dict_missing(checker):
1566 class DictSub(checker.__class__, dict):
1567 pass
1568 self.assertEqual(DictSub()["hi"], 4)
1569 def some_number(self_, key):
1570 self.assertEqual(key, "hi")
1571 return 4
Benjamin Peterson224205f2009-05-08 03:25:19 +00001572
1573 # It would be nice to have every special method tested here, but I'm
1574 # only listing the ones I can remember outside of typeobject.c, since it
1575 # does it right.
1576 specials = [
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001577 ("__bytes__", bytes, hello, set(), {}),
1578 ("__reversed__", reversed, empty_seq, set(), {}),
1579 ("__length_hint__", list, zero, set(),
Benjamin Petersona5758c02009-05-09 18:15:04 +00001580 {"__iter__" : iden, "__next__" : stop}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001581 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1582 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Petersona7205592009-05-27 03:08:59 +00001583 ("__missing__", do_dict_missing, some_number,
1584 set(("__class__",)), {}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001585 ("__subclasscheck__", do_issubclass, return_true,
1586 set(("__bases__",)), {}),
Benjamin Peterson224205f2009-05-08 03:25:19 +00001587 # These two fail because the compiler generates LOAD_ATTR to look
1588 # them up. We'd have to add a new opcode to fix this, and it's
1589 # probably not worth it.
1590 # ("__enter__", run_context, iden),
1591 # ("__exit__", run_context, iden),
1592 ]
1593
1594 class Checker(object):
1595 def __getattr__(self, attr, test=self):
1596 test.fail("__getattr__ called with {0}".format(attr))
1597 def __getattribute__(self, attr, test=self):
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001598 if attr not in ok:
1599 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Petersona7205592009-05-27 03:08:59 +00001600 return object.__getattribute__(self, attr)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001601 class SpecialDescr(object):
1602 def __init__(self, impl):
1603 self.impl = impl
1604 def __get__(self, obj, owner):
1605 record.append(1)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001606 return self.impl.__get__(obj, owner)
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001607 class MyException(Exception):
1608 pass
1609 class ErrDescr(object):
1610 def __get__(self, obj, owner):
1611 raise MyException
Benjamin Peterson224205f2009-05-08 03:25:19 +00001612
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001613 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson224205f2009-05-08 03:25:19 +00001614 class X(Checker):
1615 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001616 for attr, obj in env.items():
1617 setattr(X, attr, obj)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001618 setattr(X, name, meth_impl)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001619 runner(X())
1620
1621 record = []
1622 class X(Checker):
1623 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001624 for attr, obj in env.items():
1625 setattr(X, attr, obj)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001626 setattr(X, name, SpecialDescr(meth_impl))
1627 runner(X())
1628 self.assertEqual(record, [1], name)
1629
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001630 class X(Checker):
1631 pass
1632 for attr, obj in env.items():
1633 setattr(X, attr, obj)
1634 setattr(X, name, ErrDescr())
1635 try:
1636 runner(X())
1637 except MyException:
1638 pass
1639 else:
1640 self.fail("{0!r} didn't raise".format(name))
1641
Georg Brandl479a7e72008-02-05 18:13:15 +00001642 def test_specials(self):
1643 # Testing special operators...
1644 # Test operators like __hash__ for which a built-in default exists
1645
1646 # Test the default behavior for static classes
1647 class C(object):
1648 def __getitem__(self, i):
1649 if 0 <= i < 10: return i
1650 raise IndexError
1651 c1 = C()
1652 c2 = C()
1653 self.assert_(not not c1) # What?
1654 self.assertNotEqual(id(c1), id(c2))
1655 hash(c1)
1656 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001657 self.assertEqual(c1, c1)
1658 self.assert_(c1 != c2)
1659 self.assert_(not c1 != c1)
1660 self.assert_(not c1 == c2)
1661 # Note that the module name appears in str/repr, and that varies
1662 # depending on whether this test is run standalone or from a framework.
1663 self.assert_(str(c1).find('C object at ') >= 0)
1664 self.assertEqual(str(c1), repr(c1))
1665 self.assert_(-1 not in c1)
1666 for i in range(10):
1667 self.assert_(i in c1)
1668 self.assertFalse(10 in c1)
1669 # Test the default behavior for dynamic classes
1670 class D(object):
1671 def __getitem__(self, i):
1672 if 0 <= i < 10: return i
1673 raise IndexError
1674 d1 = D()
1675 d2 = D()
1676 self.assert_(not not d1)
1677 self.assertNotEqual(id(d1), id(d2))
1678 hash(d1)
1679 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001680 self.assertEqual(d1, d1)
1681 self.assertNotEqual(d1, d2)
1682 self.assert_(not d1 != d1)
1683 self.assert_(not d1 == d2)
1684 # Note that the module name appears in str/repr, and that varies
1685 # depending on whether this test is run standalone or from a framework.
1686 self.assert_(str(d1).find('D object at ') >= 0)
1687 self.assertEqual(str(d1), repr(d1))
1688 self.assert_(-1 not in d1)
1689 for i in range(10):
1690 self.assert_(i in d1)
1691 self.assertFalse(10 in d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00001692 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00001693 class Proxy(object):
1694 def __init__(self, x):
1695 self.x = x
1696 def __bool__(self):
1697 return not not self.x
1698 def __hash__(self):
1699 return hash(self.x)
1700 def __eq__(self, other):
1701 return self.x == other
1702 def __ne__(self, other):
1703 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00001704 def __ge__(self, other):
1705 return self.x >= other
1706 def __gt__(self, other):
1707 return self.x > other
1708 def __le__(self, other):
1709 return self.x <= other
1710 def __lt__(self, other):
1711 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00001712 def __str__(self):
1713 return "Proxy:%s" % self.x
1714 def __repr__(self):
1715 return "Proxy(%r)" % self.x
1716 def __contains__(self, value):
1717 return value in self.x
1718 p0 = Proxy(0)
1719 p1 = Proxy(1)
1720 p_1 = Proxy(-1)
1721 self.assertFalse(p0)
1722 self.assert_(not not p1)
1723 self.assertEqual(hash(p0), hash(0))
1724 self.assertEqual(p0, p0)
1725 self.assertNotEqual(p0, p1)
1726 self.assert_(not p0 != p0)
1727 self.assertEqual(not p0, p1)
Benjamin Peterson60192082008-10-16 19:34:46 +00001728 self.assert_(p0 < p1)
1729 self.assert_(p0 <= p1)
1730 self.assert_(p1 > p0)
1731 self.assert_(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001732 self.assertEqual(str(p0), "Proxy:0")
1733 self.assertEqual(repr(p0), "Proxy(0)")
1734 p10 = Proxy(range(10))
1735 self.assertFalse(-1 in p10)
1736 for i in range(10):
1737 self.assert_(i in p10)
1738 self.assertFalse(10 in p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001739
Georg Brandl479a7e72008-02-05 18:13:15 +00001740 def test_weakrefs(self):
1741 # Testing weak references...
1742 import weakref
1743 class C(object):
1744 pass
1745 c = C()
1746 r = weakref.ref(c)
1747 self.assertEqual(r(), c)
1748 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00001749 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001750 self.assertEqual(r(), None)
1751 del r
1752 class NoWeak(object):
1753 __slots__ = ['foo']
1754 no = NoWeak()
1755 try:
1756 weakref.ref(no)
1757 except TypeError as msg:
1758 self.assert_(str(msg).find("weak reference") >= 0)
1759 else:
1760 self.fail("weakref.ref(no) should be illegal")
1761 class Weak(object):
1762 __slots__ = ['foo', '__weakref__']
1763 yes = Weak()
1764 r = weakref.ref(yes)
1765 self.assertEqual(r(), yes)
1766 del yes
Benjamin Petersone549ead2009-03-28 21:42:05 +00001767 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001768 self.assertEqual(r(), None)
1769 del r
1770
1771 def test_properties(self):
1772 # Testing property...
1773 class C(object):
1774 def getx(self):
1775 return self.__x
1776 def setx(self, value):
1777 self.__x = value
1778 def delx(self):
1779 del self.__x
1780 x = property(getx, setx, delx, doc="I'm the x property.")
1781 a = C()
1782 self.assertFalse(hasattr(a, "x"))
1783 a.x = 42
1784 self.assertEqual(a._C__x, 42)
1785 self.assertEqual(a.x, 42)
1786 del a.x
1787 self.assertFalse(hasattr(a, "x"))
1788 self.assertFalse(hasattr(a, "_C__x"))
1789 C.x.__set__(a, 100)
1790 self.assertEqual(C.x.__get__(a), 100)
1791 C.x.__delete__(a)
1792 self.assertFalse(hasattr(a, "x"))
1793
1794 raw = C.__dict__['x']
1795 self.assert_(isinstance(raw, property))
1796
1797 attrs = dir(raw)
1798 self.assert_("__doc__" in attrs)
1799 self.assert_("fget" in attrs)
1800 self.assert_("fset" in attrs)
1801 self.assert_("fdel" in attrs)
1802
1803 self.assertEqual(raw.__doc__, "I'm the x property.")
1804 self.assert_(raw.fget is C.__dict__['getx'])
1805 self.assert_(raw.fset is C.__dict__['setx'])
1806 self.assert_(raw.fdel is C.__dict__['delx'])
1807
1808 for attr in "__doc__", "fget", "fset", "fdel":
1809 try:
1810 setattr(raw, attr, 42)
1811 except AttributeError as msg:
1812 if str(msg).find('readonly') < 0:
1813 self.fail("when setting readonly attr %r on a property, "
1814 "got unexpected AttributeError msg %r" % (attr, str(msg)))
1815 else:
1816 self.fail("expected AttributeError from trying to set readonly %r "
1817 "attr on a property" % attr)
1818
1819 class D(object):
1820 __getitem__ = property(lambda s: 1/0)
1821
1822 d = D()
1823 try:
1824 for i in d:
1825 str(i)
1826 except ZeroDivisionError:
1827 pass
1828 else:
1829 self.fail("expected ZeroDivisionError from bad property")
1830
1831 class E(object):
1832 def getter(self):
1833 "getter method"
1834 return 0
1835 def setter(self_, value):
1836 "setter method"
1837 pass
1838 prop = property(getter)
1839 self.assertEqual(prop.__doc__, "getter method")
1840 prop2 = property(fset=setter)
1841 self.assertEqual(prop2.__doc__, None)
1842
1843 # this segfaulted in 2.5b2
1844 try:
1845 import _testcapi
1846 except ImportError:
1847 pass
1848 else:
1849 class X(object):
1850 p = property(_testcapi.test_with_docstring)
1851
1852 def test_properties_plus(self):
1853 class C(object):
1854 foo = property(doc="hello")
1855 @foo.getter
1856 def foo(self):
1857 return self._foo
1858 @foo.setter
1859 def foo(self, value):
1860 self._foo = abs(value)
1861 @foo.deleter
1862 def foo(self):
1863 del self._foo
1864 c = C()
1865 self.assertEqual(C.foo.__doc__, "hello")
1866 self.assertFalse(hasattr(c, "foo"))
1867 c.foo = -42
1868 self.assert_(hasattr(c, '_foo'))
1869 self.assertEqual(c._foo, 42)
1870 self.assertEqual(c.foo, 42)
1871 del c.foo
1872 self.assertFalse(hasattr(c, '_foo'))
1873 self.assertFalse(hasattr(c, "foo"))
1874
1875 class D(C):
1876 @C.foo.deleter
1877 def foo(self):
1878 try:
1879 del self._foo
1880 except AttributeError:
1881 pass
1882 d = D()
1883 d.foo = 24
1884 self.assertEqual(d.foo, 24)
1885 del d.foo
1886 del d.foo
1887
1888 class E(object):
1889 @property
1890 def foo(self):
1891 return self._foo
1892 @foo.setter
1893 def foo(self, value):
1894 raise RuntimeError
1895 @foo.setter
1896 def foo(self, value):
1897 self._foo = abs(value)
1898 @foo.deleter
1899 def foo(self, value=None):
1900 del self._foo
1901
1902 e = E()
1903 e.foo = -42
1904 self.assertEqual(e.foo, 42)
1905 del e.foo
1906
1907 class F(E):
1908 @E.foo.deleter
1909 def foo(self):
1910 del self._foo
1911 @foo.setter
1912 def foo(self, value):
1913 self._foo = max(0, value)
1914 f = F()
1915 f.foo = -10
1916 self.assertEqual(f.foo, 0)
1917 del f.foo
1918
1919 def test_dict_constructors(self):
1920 # Testing dict constructor ...
1921 d = dict()
1922 self.assertEqual(d, {})
1923 d = dict({})
1924 self.assertEqual(d, {})
1925 d = dict({1: 2, 'a': 'b'})
1926 self.assertEqual(d, {1: 2, 'a': 'b'})
1927 self.assertEqual(d, dict(list(d.items())))
1928 self.assertEqual(d, dict(iter(d.items())))
1929 d = dict({'one':1, 'two':2})
1930 self.assertEqual(d, dict(one=1, two=2))
1931 self.assertEqual(d, dict(**d))
1932 self.assertEqual(d, dict({"one": 1}, two=2))
1933 self.assertEqual(d, dict([("two", 2)], one=1))
1934 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
1935 self.assertEqual(d, dict(**d))
1936
1937 for badarg in 0, 0, 0j, "0", [0], (0,):
1938 try:
1939 dict(badarg)
1940 except TypeError:
1941 pass
1942 except ValueError:
1943 if badarg == "0":
1944 # It's a sequence, and its elements are also sequences (gotta
1945 # love strings <wink>), but they aren't of length 2, so this
1946 # one seemed better as a ValueError than a TypeError.
1947 pass
1948 else:
1949 self.fail("no TypeError from dict(%r)" % badarg)
1950 else:
1951 self.fail("no TypeError from dict(%r)" % badarg)
1952
1953 try:
1954 dict({}, {})
1955 except TypeError:
1956 pass
1957 else:
1958 self.fail("no TypeError from dict({}, {})")
1959
1960 class Mapping:
1961 # Lacks a .keys() method; will be added later.
1962 dict = {1:2, 3:4, 'a':1j}
1963
1964 try:
1965 dict(Mapping())
1966 except TypeError:
1967 pass
1968 else:
1969 self.fail("no TypeError from dict(incomplete mapping)")
1970
1971 Mapping.keys = lambda self: list(self.dict.keys())
1972 Mapping.__getitem__ = lambda self, i: self.dict[i]
1973 d = dict(Mapping())
1974 self.assertEqual(d, Mapping.dict)
1975
1976 # Init from sequence of iterable objects, each producing a 2-sequence.
1977 class AddressBookEntry:
1978 def __init__(self, first, last):
1979 self.first = first
1980 self.last = last
1981 def __iter__(self):
1982 return iter([self.first, self.last])
1983
1984 d = dict([AddressBookEntry('Tim', 'Warsaw'),
1985 AddressBookEntry('Barry', 'Peters'),
1986 AddressBookEntry('Tim', 'Peters'),
1987 AddressBookEntry('Barry', 'Warsaw')])
1988 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
1989
1990 d = dict(zip(range(4), range(1, 5)))
1991 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
1992
1993 # Bad sequence lengths.
1994 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
1995 try:
1996 dict(bad)
1997 except ValueError:
1998 pass
1999 else:
2000 self.fail("no ValueError from dict(%r)" % bad)
2001
2002 def test_dir(self):
2003 # Testing dir() ...
2004 junk = 12
2005 self.assertEqual(dir(), ['junk', 'self'])
2006 del junk
2007
2008 # Just make sure these don't blow up!
2009 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2010 dir(arg)
2011
2012 # Test dir on new-style classes. Since these have object as a
2013 # base class, a lot more gets sucked in.
2014 def interesting(strings):
2015 return [s for s in strings if not s.startswith('_')]
2016
2017 class C(object):
2018 Cdata = 1
2019 def Cmethod(self): pass
2020
2021 cstuff = ['Cdata', 'Cmethod']
2022 self.assertEqual(interesting(dir(C)), cstuff)
2023
2024 c = C()
2025 self.assertEqual(interesting(dir(c)), cstuff)
2026 ## self.assert_('__self__' in dir(C.Cmethod))
2027
2028 c.cdata = 2
2029 c.cmethod = lambda self: 0
2030 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
2031 ## self.assert_('__self__' in dir(c.Cmethod))
2032
2033 class A(C):
2034 Adata = 1
2035 def Amethod(self): pass
2036
2037 astuff = ['Adata', 'Amethod'] + cstuff
2038 self.assertEqual(interesting(dir(A)), astuff)
2039 ## self.assert_('__self__' in dir(A.Amethod))
2040 a = A()
2041 self.assertEqual(interesting(dir(a)), astuff)
2042 a.adata = 42
2043 a.amethod = lambda self: 3
2044 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
2045 ## self.assert_('__self__' in dir(a.Amethod))
2046
2047 # Try a module subclass.
2048 import sys
2049 class M(type(sys)):
2050 pass
2051 minstance = M("m")
2052 minstance.b = 2
2053 minstance.a = 1
2054 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2055 self.assertEqual(names, ['a', 'b'])
2056
2057 class M2(M):
2058 def getdict(self):
2059 return "Not a dict!"
2060 __dict__ = property(getdict)
2061
2062 m2instance = M2("m2")
2063 m2instance.b = 2
2064 m2instance.a = 1
2065 self.assertEqual(m2instance.__dict__, "Not a dict!")
2066 try:
2067 dir(m2instance)
2068 except TypeError:
2069 pass
2070
2071 # Two essentially featureless objects, just inheriting stuff from
2072 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00002073 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
2074 if support.check_impl_detail():
2075 # None differs in PyPy: it has a __nonzero__
2076 self.assertEqual(dir(None), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002077
2078 # Nasty test case for proxied objects
2079 class Wrapper(object):
2080 def __init__(self, obj):
2081 self.__obj = obj
2082 def __repr__(self):
2083 return "Wrapper(%s)" % repr(self.__obj)
2084 def __getitem__(self, key):
2085 return Wrapper(self.__obj[key])
2086 def __len__(self):
2087 return len(self.__obj)
2088 def __getattr__(self, name):
2089 return Wrapper(getattr(self.__obj, name))
2090
2091 class C(object):
2092 def __getclass(self):
2093 return Wrapper(type(self))
2094 __class__ = property(__getclass)
2095
2096 dir(C()) # This used to segfault
2097
2098 def test_supers(self):
2099 # Testing super...
2100
2101 class A(object):
2102 def meth(self, a):
2103 return "A(%r)" % a
2104
2105 self.assertEqual(A().meth(1), "A(1)")
2106
2107 class B(A):
2108 def __init__(self):
2109 self.__super = super(B, self)
2110 def meth(self, a):
2111 return "B(%r)" % a + self.__super.meth(a)
2112
2113 self.assertEqual(B().meth(2), "B(2)A(2)")
2114
2115 class C(A):
2116 def meth(self, a):
2117 return "C(%r)" % a + self.__super.meth(a)
2118 C._C__super = super(C)
2119
2120 self.assertEqual(C().meth(3), "C(3)A(3)")
2121
2122 class D(C, B):
2123 def meth(self, a):
2124 return "D(%r)" % a + super(D, self).meth(a)
2125
2126 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2127
2128 # Test for subclassing super
2129
2130 class mysuper(super):
2131 def __init__(self, *args):
2132 return super(mysuper, self).__init__(*args)
2133
2134 class E(D):
2135 def meth(self, a):
2136 return "E(%r)" % a + mysuper(E, self).meth(a)
2137
2138 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2139
2140 class F(E):
2141 def meth(self, a):
2142 s = self.__super # == mysuper(F, self)
2143 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2144 F._F__super = mysuper(F)
2145
2146 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2147
2148 # Make sure certain errors are raised
2149
2150 try:
2151 super(D, 42)
2152 except TypeError:
2153 pass
2154 else:
2155 self.fail("shouldn't allow super(D, 42)")
2156
2157 try:
2158 super(D, C())
2159 except TypeError:
2160 pass
2161 else:
2162 self.fail("shouldn't allow super(D, C())")
2163
2164 try:
2165 super(D).__get__(12)
2166 except TypeError:
2167 pass
2168 else:
2169 self.fail("shouldn't allow super(D).__get__(12)")
2170
2171 try:
2172 super(D).__get__(C())
2173 except TypeError:
2174 pass
2175 else:
2176 self.fail("shouldn't allow super(D).__get__(C())")
2177
2178 # Make sure data descriptors can be overridden and accessed via super
2179 # (new feature in Python 2.3)
2180
2181 class DDbase(object):
2182 def getx(self): return 42
2183 x = property(getx)
2184
2185 class DDsub(DDbase):
2186 def getx(self): return "hello"
2187 x = property(getx)
2188
2189 dd = DDsub()
2190 self.assertEqual(dd.x, "hello")
2191 self.assertEqual(super(DDsub, dd).x, 42)
2192
2193 # Ensure that super() lookup of descriptor from classmethod
2194 # works (SF ID# 743627)
2195
2196 class Base(object):
2197 aProp = property(lambda self: "foo")
2198
2199 class Sub(Base):
2200 @classmethod
2201 def test(klass):
2202 return super(Sub,klass).aProp
2203
2204 self.assertEqual(Sub.test(), Base.aProp)
2205
2206 # Verify that super() doesn't allow keyword args
2207 try:
2208 super(Base, kw=1)
2209 except TypeError:
2210 pass
2211 else:
2212 self.assertEqual("super shouldn't accept keyword args")
2213
2214 def test_basic_inheritance(self):
2215 # Testing inheritance from basic types...
2216
2217 class hexint(int):
2218 def __repr__(self):
2219 return hex(self)
2220 def __add__(self, other):
2221 return hexint(int.__add__(self, other))
2222 # (Note that overriding __radd__ doesn't work,
2223 # because the int type gets first dibs.)
2224 self.assertEqual(repr(hexint(7) + 9), "0x10")
2225 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2226 a = hexint(12345)
2227 self.assertEqual(a, 12345)
2228 self.assertEqual(int(a), 12345)
2229 self.assert_(int(a).__class__ is int)
2230 self.assertEqual(hash(a), hash(12345))
2231 self.assert_((+a).__class__ is int)
2232 self.assert_((a >> 0).__class__ is int)
2233 self.assert_((a << 0).__class__ is int)
2234 self.assert_((hexint(0) << 12).__class__ is int)
2235 self.assert_((hexint(0) >> 12).__class__ is int)
2236
2237 class octlong(int):
2238 __slots__ = []
2239 def __str__(self):
2240 s = oct(self)
2241 if s[-1] == 'L':
2242 s = s[:-1]
2243 return s
2244 def __add__(self, other):
2245 return self.__class__(super(octlong, self).__add__(other))
2246 __radd__ = __add__
2247 self.assertEqual(str(octlong(3) + 5), "0o10")
2248 # (Note that overriding __radd__ here only seems to work
2249 # because the example uses a short int left argument.)
2250 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2251 a = octlong(12345)
2252 self.assertEqual(a, 12345)
2253 self.assertEqual(int(a), 12345)
2254 self.assertEqual(hash(a), hash(12345))
2255 self.assert_(int(a).__class__ is int)
2256 self.assert_((+a).__class__ is int)
2257 self.assert_((-a).__class__ is int)
2258 self.assert_((-octlong(0)).__class__ is int)
2259 self.assert_((a >> 0).__class__ is int)
2260 self.assert_((a << 0).__class__ is int)
2261 self.assert_((a - 0).__class__ is int)
2262 self.assert_((a * 1).__class__ is int)
2263 self.assert_((a ** 1).__class__ is int)
2264 self.assert_((a // 1).__class__ is int)
2265 self.assert_((1 * a).__class__ is int)
2266 self.assert_((a | 0).__class__ is int)
2267 self.assert_((a ^ 0).__class__ is int)
2268 self.assert_((a & -1).__class__ is int)
2269 self.assert_((octlong(0) << 12).__class__ is int)
2270 self.assert_((octlong(0) >> 12).__class__ is int)
2271 self.assert_(abs(octlong(0)).__class__ is int)
2272
2273 # Because octlong overrides __add__, we can't check the absence of +0
2274 # optimizations using octlong.
2275 class longclone(int):
2276 pass
2277 a = longclone(1)
2278 self.assert_((a + 0).__class__ is int)
2279 self.assert_((0 + a).__class__ is int)
2280
2281 # Check that negative clones don't segfault
2282 a = longclone(-1)
2283 self.assertEqual(a.__dict__, {})
2284 self.assertEqual(int(a), -1) # self.assert_ PyNumber_Long() copies the sign bit
2285
2286 class precfloat(float):
2287 __slots__ = ['prec']
2288 def __init__(self, value=0.0, prec=12):
2289 self.prec = int(prec)
2290 def __repr__(self):
2291 return "%.*g" % (self.prec, self)
2292 self.assertEqual(repr(precfloat(1.1)), "1.1")
2293 a = precfloat(12345)
2294 self.assertEqual(a, 12345.0)
2295 self.assertEqual(float(a), 12345.0)
2296 self.assert_(float(a).__class__ is float)
2297 self.assertEqual(hash(a), hash(12345.0))
2298 self.assert_((+a).__class__ is float)
2299
2300 class madcomplex(complex):
2301 def __repr__(self):
2302 return "%.17gj%+.17g" % (self.imag, self.real)
2303 a = madcomplex(-3, 4)
2304 self.assertEqual(repr(a), "4j-3")
2305 base = complex(-3, 4)
2306 self.assertEqual(base.__class__, complex)
2307 self.assertEqual(a, base)
2308 self.assertEqual(complex(a), base)
2309 self.assertEqual(complex(a).__class__, complex)
2310 a = madcomplex(a) # just trying another form of the constructor
2311 self.assertEqual(repr(a), "4j-3")
2312 self.assertEqual(a, base)
2313 self.assertEqual(complex(a), base)
2314 self.assertEqual(complex(a).__class__, complex)
2315 self.assertEqual(hash(a), hash(base))
2316 self.assertEqual((+a).__class__, complex)
2317 self.assertEqual((a + 0).__class__, complex)
2318 self.assertEqual(a + 0, base)
2319 self.assertEqual((a - 0).__class__, complex)
2320 self.assertEqual(a - 0, base)
2321 self.assertEqual((a * 1).__class__, complex)
2322 self.assertEqual(a * 1, base)
2323 self.assertEqual((a / 1).__class__, complex)
2324 self.assertEqual(a / 1, base)
2325
2326 class madtuple(tuple):
2327 _rev = None
2328 def rev(self):
2329 if self._rev is not None:
2330 return self._rev
2331 L = list(self)
2332 L.reverse()
2333 self._rev = self.__class__(L)
2334 return self._rev
2335 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2336 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2337 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2338 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2339 for i in range(512):
2340 t = madtuple(range(i))
2341 u = t.rev()
2342 v = u.rev()
2343 self.assertEqual(v, t)
2344 a = madtuple((1,2,3,4,5))
2345 self.assertEqual(tuple(a), (1,2,3,4,5))
2346 self.assert_(tuple(a).__class__ is tuple)
2347 self.assertEqual(hash(a), hash((1,2,3,4,5)))
2348 self.assert_(a[:].__class__ is tuple)
2349 self.assert_((a * 1).__class__ is tuple)
2350 self.assert_((a * 0).__class__ is tuple)
2351 self.assert_((a + ()).__class__ is tuple)
2352 a = madtuple(())
2353 self.assertEqual(tuple(a), ())
2354 self.assert_(tuple(a).__class__ is tuple)
2355 self.assert_((a + a).__class__ is tuple)
2356 self.assert_((a * 0).__class__ is tuple)
2357 self.assert_((a * 1).__class__ is tuple)
2358 self.assert_((a * 2).__class__ is tuple)
2359 self.assert_(a[:].__class__ is tuple)
2360
2361 class madstring(str):
2362 _rev = None
2363 def rev(self):
2364 if self._rev is not None:
2365 return self._rev
2366 L = list(self)
2367 L.reverse()
2368 self._rev = self.__class__("".join(L))
2369 return self._rev
2370 s = madstring("abcdefghijklmnopqrstuvwxyz")
2371 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2372 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2373 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2374 for i in range(256):
2375 s = madstring("".join(map(chr, range(i))))
2376 t = s.rev()
2377 u = t.rev()
2378 self.assertEqual(u, s)
2379 s = madstring("12345")
2380 self.assertEqual(str(s), "12345")
2381 self.assert_(str(s).__class__ is str)
2382
2383 base = "\x00" * 5
2384 s = madstring(base)
2385 self.assertEqual(s, base)
2386 self.assertEqual(str(s), base)
2387 self.assert_(str(s).__class__ is str)
2388 self.assertEqual(hash(s), hash(base))
2389 self.assertEqual({s: 1}[base], 1)
2390 self.assertEqual({base: 1}[s], 1)
2391 self.assert_((s + "").__class__ is str)
2392 self.assertEqual(s + "", base)
2393 self.assert_(("" + s).__class__ is str)
2394 self.assertEqual("" + s, base)
2395 self.assert_((s * 0).__class__ is str)
2396 self.assertEqual(s * 0, "")
2397 self.assert_((s * 1).__class__ is str)
2398 self.assertEqual(s * 1, base)
2399 self.assert_((s * 2).__class__ is str)
2400 self.assertEqual(s * 2, base + base)
2401 self.assert_(s[:].__class__ is str)
2402 self.assertEqual(s[:], base)
2403 self.assert_(s[0:0].__class__ is str)
2404 self.assertEqual(s[0:0], "")
2405 self.assert_(s.strip().__class__ is str)
2406 self.assertEqual(s.strip(), base)
2407 self.assert_(s.lstrip().__class__ is str)
2408 self.assertEqual(s.lstrip(), base)
2409 self.assert_(s.rstrip().__class__ is str)
2410 self.assertEqual(s.rstrip(), base)
2411 identitytab = {}
2412 self.assert_(s.translate(identitytab).__class__ is str)
2413 self.assertEqual(s.translate(identitytab), base)
2414 self.assert_(s.replace("x", "x").__class__ is str)
2415 self.assertEqual(s.replace("x", "x"), base)
2416 self.assert_(s.ljust(len(s)).__class__ is str)
2417 self.assertEqual(s.ljust(len(s)), base)
2418 self.assert_(s.rjust(len(s)).__class__ is str)
2419 self.assertEqual(s.rjust(len(s)), base)
2420 self.assert_(s.center(len(s)).__class__ is str)
2421 self.assertEqual(s.center(len(s)), base)
2422 self.assert_(s.lower().__class__ is str)
2423 self.assertEqual(s.lower(), base)
2424
2425 class madunicode(str):
2426 _rev = None
2427 def rev(self):
2428 if self._rev is not None:
2429 return self._rev
2430 L = list(self)
2431 L.reverse()
2432 self._rev = self.__class__("".join(L))
2433 return self._rev
2434 u = madunicode("ABCDEF")
2435 self.assertEqual(u, "ABCDEF")
2436 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2437 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2438 base = "12345"
2439 u = madunicode(base)
2440 self.assertEqual(str(u), base)
2441 self.assert_(str(u).__class__ is str)
2442 self.assertEqual(hash(u), hash(base))
2443 self.assertEqual({u: 1}[base], 1)
2444 self.assertEqual({base: 1}[u], 1)
2445 self.assert_(u.strip().__class__ is str)
2446 self.assertEqual(u.strip(), base)
2447 self.assert_(u.lstrip().__class__ is str)
2448 self.assertEqual(u.lstrip(), base)
2449 self.assert_(u.rstrip().__class__ is str)
2450 self.assertEqual(u.rstrip(), base)
2451 self.assert_(u.replace("x", "x").__class__ is str)
2452 self.assertEqual(u.replace("x", "x"), base)
2453 self.assert_(u.replace("xy", "xy").__class__ is str)
2454 self.assertEqual(u.replace("xy", "xy"), base)
2455 self.assert_(u.center(len(u)).__class__ is str)
2456 self.assertEqual(u.center(len(u)), base)
2457 self.assert_(u.ljust(len(u)).__class__ is str)
2458 self.assertEqual(u.ljust(len(u)), base)
2459 self.assert_(u.rjust(len(u)).__class__ is str)
2460 self.assertEqual(u.rjust(len(u)), base)
2461 self.assert_(u.lower().__class__ is str)
2462 self.assertEqual(u.lower(), base)
2463 self.assert_(u.upper().__class__ is str)
2464 self.assertEqual(u.upper(), base)
2465 self.assert_(u.capitalize().__class__ is str)
2466 self.assertEqual(u.capitalize(), base)
2467 self.assert_(u.title().__class__ is str)
2468 self.assertEqual(u.title(), base)
2469 self.assert_((u + "").__class__ is str)
2470 self.assertEqual(u + "", base)
2471 self.assert_(("" + u).__class__ is str)
2472 self.assertEqual("" + u, base)
2473 self.assert_((u * 0).__class__ is str)
2474 self.assertEqual(u * 0, "")
2475 self.assert_((u * 1).__class__ is str)
2476 self.assertEqual(u * 1, base)
2477 self.assert_((u * 2).__class__ is str)
2478 self.assertEqual(u * 2, base + base)
2479 self.assert_(u[:].__class__ is str)
2480 self.assertEqual(u[:], base)
2481 self.assert_(u[0:0].__class__ is str)
2482 self.assertEqual(u[0:0], "")
2483
2484 class sublist(list):
2485 pass
2486 a = sublist(range(5))
2487 self.assertEqual(a, list(range(5)))
2488 a.append("hello")
2489 self.assertEqual(a, list(range(5)) + ["hello"])
2490 a[5] = 5
2491 self.assertEqual(a, list(range(6)))
2492 a.extend(range(6, 20))
2493 self.assertEqual(a, list(range(20)))
2494 a[-5:] = []
2495 self.assertEqual(a, list(range(15)))
2496 del a[10:15]
2497 self.assertEqual(len(a), 10)
2498 self.assertEqual(a, list(range(10)))
2499 self.assertEqual(list(a), list(range(10)))
2500 self.assertEqual(a[0], 0)
2501 self.assertEqual(a[9], 9)
2502 self.assertEqual(a[-10], 0)
2503 self.assertEqual(a[-1], 9)
2504 self.assertEqual(a[:5], list(range(5)))
2505
2506 ## class CountedInput(file):
2507 ## """Counts lines read by self.readline().
2508 ##
2509 ## self.lineno is the 0-based ordinal of the last line read, up to
2510 ## a maximum of one greater than the number of lines in the file.
2511 ##
2512 ## self.ateof is true if and only if the final "" line has been read,
2513 ## at which point self.lineno stops incrementing, and further calls
2514 ## to readline() continue to return "".
2515 ## """
2516 ##
2517 ## lineno = 0
2518 ## ateof = 0
2519 ## def readline(self):
2520 ## if self.ateof:
2521 ## return ""
2522 ## s = file.readline(self)
2523 ## # Next line works too.
2524 ## # s = super(CountedInput, self).readline()
2525 ## self.lineno += 1
2526 ## if s == "":
2527 ## self.ateof = 1
2528 ## return s
2529 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002530 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002531 ## lines = ['a\n', 'b\n', 'c\n']
2532 ## try:
2533 ## f.writelines(lines)
2534 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002535 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002536 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2537 ## got = f.readline()
2538 ## self.assertEqual(expected, got)
2539 ## self.assertEqual(f.lineno, i)
2540 ## self.assertEqual(f.ateof, (i > len(lines)))
2541 ## f.close()
2542 ## finally:
2543 ## try:
2544 ## f.close()
2545 ## except:
2546 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002547 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002548
2549 def test_keywords(self):
2550 # Testing keyword args to basic type constructors ...
2551 self.assertEqual(int(x=1), 1)
2552 self.assertEqual(float(x=2), 2.0)
2553 self.assertEqual(int(x=3), 3)
2554 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2555 self.assertEqual(str(object=500), '500')
2556 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
2557 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2558 self.assertEqual(list(sequence=(0, 1, 2)), list(range(3)))
2559 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2560
2561 for constructor in (int, float, int, complex, str, str,
2562 tuple, list):
2563 try:
2564 constructor(bogus_keyword_arg=1)
2565 except TypeError:
2566 pass
2567 else:
2568 self.fail("expected TypeError from bogus keyword argument to %r"
2569 % constructor)
2570
2571 def test_str_subclass_as_dict_key(self):
2572 # Testing a str subclass used as dict key ..
2573
2574 class cistr(str):
2575 """Sublcass of str that computes __eq__ case-insensitively.
2576
2577 Also computes a hash code of the string in canonical form.
2578 """
2579
2580 def __init__(self, value):
2581 self.canonical = value.lower()
2582 self.hashcode = hash(self.canonical)
2583
2584 def __eq__(self, other):
2585 if not isinstance(other, cistr):
2586 other = cistr(other)
2587 return self.canonical == other.canonical
2588
2589 def __hash__(self):
2590 return self.hashcode
2591
2592 self.assertEqual(cistr('ABC'), 'abc')
2593 self.assertEqual('aBc', cistr('ABC'))
2594 self.assertEqual(str(cistr('ABC')), 'ABC')
2595
2596 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2597 self.assertEqual(d[cistr('one')], 1)
2598 self.assertEqual(d[cistr('tWo')], 2)
2599 self.assertEqual(d[cistr('THrEE')], 3)
2600 self.assert_(cistr('ONe') in d)
2601 self.assertEqual(d.get(cistr('thrEE')), 3)
2602
2603 def test_classic_comparisons(self):
2604 # Testing classic comparisons...
2605 class classic:
2606 pass
2607
2608 for base in (classic, int, object):
2609 class C(base):
2610 def __init__(self, value):
2611 self.value = int(value)
2612 def __eq__(self, other):
2613 if isinstance(other, C):
2614 return self.value == other.value
2615 if isinstance(other, int) or isinstance(other, int):
2616 return self.value == other
2617 return NotImplemented
2618 def __ne__(self, other):
2619 if isinstance(other, C):
2620 return self.value != other.value
2621 if isinstance(other, int) or isinstance(other, int):
2622 return self.value != other
2623 return NotImplemented
2624 def __lt__(self, other):
2625 if isinstance(other, C):
2626 return self.value < other.value
2627 if isinstance(other, int) or isinstance(other, int):
2628 return self.value < other
2629 return NotImplemented
2630 def __le__(self, other):
2631 if isinstance(other, C):
2632 return self.value <= other.value
2633 if isinstance(other, int) or isinstance(other, int):
2634 return self.value <= other
2635 return NotImplemented
2636 def __gt__(self, other):
2637 if isinstance(other, C):
2638 return self.value > other.value
2639 if isinstance(other, int) or isinstance(other, int):
2640 return self.value > other
2641 return NotImplemented
2642 def __ge__(self, other):
2643 if isinstance(other, C):
2644 return self.value >= other.value
2645 if isinstance(other, int) or isinstance(other, int):
2646 return self.value >= other
2647 return NotImplemented
2648
2649 c1 = C(1)
2650 c2 = C(2)
2651 c3 = C(3)
2652 self.assertEqual(c1, 1)
2653 c = {1: c1, 2: c2, 3: c3}
2654 for x in 1, 2, 3:
2655 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00002656 for op in "<", "<=", "==", "!=", ">", ">=":
Mark Dickinsona56c4672009-01-27 18:17:45 +00002657 self.assert_(eval("c[x] %s c[y]" % op) ==
2658 eval("x %s y" % op),
2659 "x=%d, y=%d" % (x, y))
2660 self.assert_(eval("c[x] %s y" % op) ==
2661 eval("x %s y" % op),
2662 "x=%d, y=%d" % (x, y))
2663 self.assert_(eval("x %s c[y]" % op) ==
2664 eval("x %s y" % op),
2665 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002666
2667 def test_rich_comparisons(self):
2668 # Testing rich comparisons...
2669 class Z(complex):
2670 pass
2671 z = Z(1)
2672 self.assertEqual(z, 1+0j)
2673 self.assertEqual(1+0j, z)
2674 class ZZ(complex):
2675 def __eq__(self, other):
2676 try:
2677 return abs(self - other) <= 1e-6
2678 except:
2679 return NotImplemented
2680 zz = ZZ(1.0000003)
2681 self.assertEqual(zz, 1+0j)
2682 self.assertEqual(1+0j, zz)
2683
2684 class classic:
2685 pass
2686 for base in (classic, int, object, list):
2687 class C(base):
2688 def __init__(self, value):
2689 self.value = int(value)
2690 def __cmp__(self_, other):
2691 self.fail("shouldn't call __cmp__")
2692 def __eq__(self, other):
2693 if isinstance(other, C):
2694 return self.value == other.value
2695 if isinstance(other, int) or isinstance(other, int):
2696 return self.value == other
2697 return NotImplemented
2698 def __ne__(self, other):
2699 if isinstance(other, C):
2700 return self.value != other.value
2701 if isinstance(other, int) or isinstance(other, int):
2702 return self.value != other
2703 return NotImplemented
2704 def __lt__(self, other):
2705 if isinstance(other, C):
2706 return self.value < other.value
2707 if isinstance(other, int) or isinstance(other, int):
2708 return self.value < other
2709 return NotImplemented
2710 def __le__(self, other):
2711 if isinstance(other, C):
2712 return self.value <= other.value
2713 if isinstance(other, int) or isinstance(other, int):
2714 return self.value <= other
2715 return NotImplemented
2716 def __gt__(self, other):
2717 if isinstance(other, C):
2718 return self.value > other.value
2719 if isinstance(other, int) or isinstance(other, int):
2720 return self.value > other
2721 return NotImplemented
2722 def __ge__(self, other):
2723 if isinstance(other, C):
2724 return self.value >= other.value
2725 if isinstance(other, int) or isinstance(other, int):
2726 return self.value >= other
2727 return NotImplemented
2728 c1 = C(1)
2729 c2 = C(2)
2730 c3 = C(3)
2731 self.assertEqual(c1, 1)
2732 c = {1: c1, 2: c2, 3: c3}
2733 for x in 1, 2, 3:
2734 for y in 1, 2, 3:
2735 for op in "<", "<=", "==", "!=", ">", ">=":
2736 self.assert_(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2737 "x=%d, y=%d" % (x, y))
2738 self.assert_(eval("c[x] %s y" % op) == eval("x %s y" % op),
2739 "x=%d, y=%d" % (x, y))
2740 self.assert_(eval("x %s c[y]" % op) == eval("x %s y" % op),
2741 "x=%d, y=%d" % (x, y))
2742
2743 def test_descrdoc(self):
2744 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002745 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00002746 def check(descr, what):
2747 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002748 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00002749 check(complex.real, "the real part of a complex number") # member descriptor
2750
2751 def test_doc_descriptor(self):
2752 # Testing __doc__ descriptor...
2753 # SF bug 542984
2754 class DocDescr(object):
2755 def __get__(self, object, otype):
2756 if object:
2757 object = object.__class__.__name__ + ' instance'
2758 if otype:
2759 otype = otype.__name__
2760 return 'object=%s; type=%s' % (object, otype)
2761 class OldClass:
2762 __doc__ = DocDescr()
2763 class NewClass(object):
2764 __doc__ = DocDescr()
2765 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
2766 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
2767 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
2768 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
2769
2770 def test_set_class(self):
2771 # Testing __class__ assignment...
2772 class C(object): pass
2773 class D(object): pass
2774 class E(object): pass
2775 class F(D, E): pass
2776 for cls in C, D, E, F:
2777 for cls2 in C, D, E, F:
2778 x = cls()
2779 x.__class__ = cls2
2780 self.assert_(x.__class__ is cls2)
2781 x.__class__ = cls
2782 self.assert_(x.__class__ is cls)
2783 def cant(x, C):
2784 try:
2785 x.__class__ = C
2786 except TypeError:
2787 pass
2788 else:
2789 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
2790 try:
2791 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00002792 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00002793 pass
2794 else:
2795 self.fail("shouldn't allow del %r.__class__" % x)
2796 cant(C(), list)
2797 cant(list(), C)
2798 cant(C(), 1)
2799 cant(C(), object)
2800 cant(object(), list)
2801 cant(list(), object)
2802 class Int(int): __slots__ = []
2803 cant(2, Int)
2804 cant(Int(), int)
2805 cant(True, int)
2806 cant(2, bool)
2807 o = object()
2808 cant(o, type(1))
2809 cant(o, type(None))
2810 del o
2811 class G(object):
2812 __slots__ = ["a", "b"]
2813 class H(object):
2814 __slots__ = ["b", "a"]
2815 class I(object):
2816 __slots__ = ["a", "b"]
2817 class J(object):
2818 __slots__ = ["c", "b"]
2819 class K(object):
2820 __slots__ = ["a", "b", "d"]
2821 class L(H):
2822 __slots__ = ["e"]
2823 class M(I):
2824 __slots__ = ["e"]
2825 class N(J):
2826 __slots__ = ["__weakref__"]
2827 class P(J):
2828 __slots__ = ["__dict__"]
2829 class Q(J):
2830 pass
2831 class R(J):
2832 __slots__ = ["__dict__", "__weakref__"]
2833
2834 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
2835 x = cls()
2836 x.a = 1
2837 x.__class__ = cls2
2838 self.assert_(x.__class__ is cls2,
2839 "assigning %r as __class__ for %r silently failed" % (cls2, x))
2840 self.assertEqual(x.a, 1)
2841 x.__class__ = cls
2842 self.assert_(x.__class__ is cls,
2843 "assigning %r as __class__ for %r silently failed" % (cls, x))
2844 self.assertEqual(x.a, 1)
2845 for cls in G, J, K, L, M, N, P, R, list, Int:
2846 for cls2 in G, J, K, L, M, N, P, R, list, Int:
2847 if cls is cls2:
2848 continue
2849 cant(cls(), cls2)
2850
Benjamin Peterson193152c2009-04-25 01:08:45 +00002851 # Issue5283: when __class__ changes in __del__, the wrong
2852 # type gets DECREF'd.
2853 class O(object):
2854 pass
2855 class A(object):
2856 def __del__(self):
2857 self.__class__ = O
2858 l = [A() for x in range(100)]
2859 del l
2860
Georg Brandl479a7e72008-02-05 18:13:15 +00002861 def test_set_dict(self):
2862 # Testing __dict__ assignment...
2863 class C(object): pass
2864 a = C()
2865 a.__dict__ = {'b': 1}
2866 self.assertEqual(a.b, 1)
2867 def cant(x, dict):
2868 try:
2869 x.__dict__ = dict
2870 except (AttributeError, TypeError):
2871 pass
2872 else:
2873 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
2874 cant(a, None)
2875 cant(a, [])
2876 cant(a, 1)
2877 del a.__dict__ # Deleting __dict__ is allowed
2878
2879 class Base(object):
2880 pass
2881 def verify_dict_readonly(x):
2882 """
2883 x has to be an instance of a class inheriting from Base.
2884 """
2885 cant(x, {})
2886 try:
2887 del x.__dict__
2888 except (AttributeError, TypeError):
2889 pass
2890 else:
2891 self.fail("shouldn't allow del %r.__dict__" % x)
2892 dict_descr = Base.__dict__["__dict__"]
2893 try:
2894 dict_descr.__set__(x, {})
2895 except (AttributeError, TypeError):
2896 pass
2897 else:
2898 self.fail("dict_descr allowed access to %r's dict" % x)
2899
2900 # Classes don't allow __dict__ assignment and have readonly dicts
2901 class Meta1(type, Base):
2902 pass
2903 class Meta2(Base, type):
2904 pass
2905 class D(object, metaclass=Meta1):
2906 pass
2907 class E(object, metaclass=Meta2):
2908 pass
2909 for cls in C, D, E:
2910 verify_dict_readonly(cls)
2911 class_dict = cls.__dict__
2912 try:
2913 class_dict["spam"] = "eggs"
2914 except TypeError:
2915 pass
2916 else:
2917 self.fail("%r's __dict__ can be modified" % cls)
2918
2919 # Modules also disallow __dict__ assignment
2920 class Module1(types.ModuleType, Base):
2921 pass
2922 class Module2(Base, types.ModuleType):
2923 pass
2924 for ModuleType in Module1, Module2:
2925 mod = ModuleType("spam")
2926 verify_dict_readonly(mod)
2927 mod.__dict__["spam"] = "eggs"
2928
2929 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00002930 # (at least not any more than regular exception's __dict__ can
2931 # be deleted; on CPython it is not the case, whereas on PyPy they
2932 # can, just like any other new-style instance's __dict__.)
2933 def can_delete_dict(e):
2934 try:
2935 del e.__dict__
2936 except (TypeError, AttributeError):
2937 return False
2938 else:
2939 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00002940 class Exception1(Exception, Base):
2941 pass
2942 class Exception2(Base, Exception):
2943 pass
2944 for ExceptionType in Exception, Exception1, Exception2:
2945 e = ExceptionType()
2946 e.__dict__ = {"a": 1}
2947 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00002948 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00002949
2950 def test_pickles(self):
2951 # Testing pickling and copying new-style classes and objects...
2952 import pickle
2953
2954 def sorteditems(d):
2955 L = list(d.items())
2956 L.sort()
2957 return L
2958
2959 global C
2960 class C(object):
2961 def __init__(self, a, b):
2962 super(C, self).__init__()
2963 self.a = a
2964 self.b = b
2965 def __repr__(self):
2966 return "C(%r, %r)" % (self.a, self.b)
2967
2968 global C1
2969 class C1(list):
2970 def __new__(cls, a, b):
2971 return super(C1, cls).__new__(cls)
2972 def __getnewargs__(self):
2973 return (self.a, self.b)
2974 def __init__(self, a, b):
2975 self.a = a
2976 self.b = b
2977 def __repr__(self):
2978 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2979
2980 global C2
2981 class C2(int):
2982 def __new__(cls, a, b, val=0):
2983 return super(C2, cls).__new__(cls, val)
2984 def __getnewargs__(self):
2985 return (self.a, self.b, int(self))
2986 def __init__(self, a, b, val=0):
2987 self.a = a
2988 self.b = b
2989 def __repr__(self):
2990 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2991
2992 global C3
2993 class C3(object):
2994 def __init__(self, foo):
2995 self.foo = foo
2996 def __getstate__(self):
2997 return self.foo
2998 def __setstate__(self, foo):
2999 self.foo = foo
3000
3001 global C4classic, C4
3002 class C4classic: # classic
3003 pass
3004 class C4(C4classic, object): # mixed inheritance
3005 pass
3006
Guido van Rossum3926a632001-09-25 16:25:58 +00003007 for bin in 0, 1:
Guido van Rossum3926a632001-09-25 16:25:58 +00003008 for cls in C, C1, C2:
Georg Brandl479a7e72008-02-05 18:13:15 +00003009 s = pickle.dumps(cls, bin)
3010 cls2 = pickle.loads(s)
3011 self.assert_(cls2 is cls)
Guido van Rossum3926a632001-09-25 16:25:58 +00003012
3013 a = C1(1, 2); a.append(42); a.append(24)
3014 b = C2("hello", "world", 42)
Georg Brandl479a7e72008-02-05 18:13:15 +00003015 s = pickle.dumps((a, b), bin)
3016 x, y = pickle.loads(s)
3017 self.assertEqual(x.__class__, a.__class__)
3018 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3019 self.assertEqual(y.__class__, b.__class__)
3020 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3021 self.assertEqual(repr(x), repr(a))
3022 self.assertEqual(repr(y), repr(b))
Guido van Rossum90c45142001-11-24 21:07:01 +00003023 # Test for __getstate__ and __setstate__ on new style class
3024 u = C3(42)
Georg Brandl479a7e72008-02-05 18:13:15 +00003025 s = pickle.dumps(u, bin)
3026 v = pickle.loads(s)
3027 self.assertEqual(u.__class__, v.__class__)
3028 self.assertEqual(u.foo, v.foo)
Guido van Rossum90c45142001-11-24 21:07:01 +00003029 # Test for picklability of hybrid class
3030 u = C4()
3031 u.foo = 42
Georg Brandl479a7e72008-02-05 18:13:15 +00003032 s = pickle.dumps(u, bin)
3033 v = pickle.loads(s)
3034 self.assertEqual(u.__class__, v.__class__)
3035 self.assertEqual(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00003036
Georg Brandl479a7e72008-02-05 18:13:15 +00003037 # Testing copy.deepcopy()
3038 import copy
3039 for cls in C, C1, C2:
3040 cls2 = copy.deepcopy(cls)
3041 self.assert_(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003042
Georg Brandl479a7e72008-02-05 18:13:15 +00003043 a = C1(1, 2); a.append(42); a.append(24)
3044 b = C2("hello", "world", 42)
3045 x, y = copy.deepcopy((a, b))
3046 self.assertEqual(x.__class__, a.__class__)
3047 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3048 self.assertEqual(y.__class__, b.__class__)
3049 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3050 self.assertEqual(repr(x), repr(a))
3051 self.assertEqual(repr(y), repr(b))
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003052
Georg Brandl479a7e72008-02-05 18:13:15 +00003053 def test_pickle_slots(self):
3054 # Testing pickling of classes with __slots__ ...
3055 import pickle
3056 # Pickling of classes with __slots__ but without __getstate__ should fail
3057 # (if using protocol 0 or 1)
3058 global B, C, D, E
3059 class B(object):
Guido van Rossum8c842552002-03-14 23:05:54 +00003060 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003061 for base in [object, B]:
3062 class C(base):
3063 __slots__ = ['a']
3064 class D(C):
3065 pass
3066 try:
3067 pickle.dumps(C(), 0)
3068 except TypeError:
3069 pass
3070 else:
3071 self.fail("should fail: pickle C instance - %s" % base)
3072 try:
3073 pickle.dumps(C(), 0)
3074 except TypeError:
3075 pass
3076 else:
3077 self.fail("should fail: pickle D instance - %s" % base)
3078 # Give C a nice generic __getstate__ and __setstate__
3079 class C(base):
3080 __slots__ = ['a']
3081 def __getstate__(self):
3082 try:
3083 d = self.__dict__.copy()
3084 except AttributeError:
3085 d = {}
3086 for cls in self.__class__.__mro__:
3087 for sn in cls.__dict__.get('__slots__', ()):
3088 try:
3089 d[sn] = getattr(self, sn)
3090 except AttributeError:
3091 pass
3092 return d
3093 def __setstate__(self, d):
3094 for k, v in list(d.items()):
3095 setattr(self, k, v)
3096 class D(C):
3097 pass
3098 # Now it should work
3099 x = C()
3100 y = pickle.loads(pickle.dumps(x))
3101 self.assertEqual(hasattr(y, 'a'), 0)
3102 x.a = 42
3103 y = pickle.loads(pickle.dumps(x))
3104 self.assertEqual(y.a, 42)
3105 x = D()
3106 x.a = 42
3107 x.b = 100
3108 y = pickle.loads(pickle.dumps(x))
3109 self.assertEqual(y.a + y.b, 142)
3110 # A subclass that adds a slot should also work
3111 class E(C):
3112 __slots__ = ['b']
3113 x = E()
3114 x.a = 42
3115 x.b = "foo"
3116 y = pickle.loads(pickle.dumps(x))
3117 self.assertEqual(y.a, x.a)
3118 self.assertEqual(y.b, x.b)
3119
3120 def test_binary_operator_override(self):
3121 # Testing overrides of binary operations...
3122 class I(int):
3123 def __repr__(self):
3124 return "I(%r)" % int(self)
3125 def __add__(self, other):
3126 return I(int(self) + int(other))
3127 __radd__ = __add__
3128 def __pow__(self, other, mod=None):
3129 if mod is None:
3130 return I(pow(int(self), int(other)))
3131 else:
3132 return I(pow(int(self), int(other), int(mod)))
3133 def __rpow__(self, other, mod=None):
3134 if mod is None:
3135 return I(pow(int(other), int(self), mod))
3136 else:
3137 return I(pow(int(other), int(self), int(mod)))
3138
3139 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3140 self.assertEqual(repr(I(1) + 2), "I(3)")
3141 self.assertEqual(repr(1 + I(2)), "I(3)")
3142 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3143 self.assertEqual(repr(2 ** I(3)), "I(8)")
3144 self.assertEqual(repr(I(2) ** 3), "I(8)")
3145 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3146 class S(str):
3147 def __eq__(self, other):
3148 return self.lower() == other.lower()
3149
3150 def test_subclass_propagation(self):
3151 # Testing propagation of slot functions to subclasses...
3152 class A(object):
3153 pass
3154 class B(A):
3155 pass
3156 class C(A):
3157 pass
3158 class D(B, C):
3159 pass
3160 d = D()
3161 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3162 A.__hash__ = lambda self: 42
3163 self.assertEqual(hash(d), 42)
3164 C.__hash__ = lambda self: 314
3165 self.assertEqual(hash(d), 314)
3166 B.__hash__ = lambda self: 144
3167 self.assertEqual(hash(d), 144)
3168 D.__hash__ = lambda self: 100
3169 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003170 D.__hash__ = None
3171 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003172 del D.__hash__
3173 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003174 B.__hash__ = None
3175 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003176 del B.__hash__
3177 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003178 C.__hash__ = None
3179 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003180 del C.__hash__
3181 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003182 A.__hash__ = None
3183 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003184 del A.__hash__
3185 self.assertEqual(hash(d), orig_hash)
3186 d.foo = 42
3187 d.bar = 42
3188 self.assertEqual(d.foo, 42)
3189 self.assertEqual(d.bar, 42)
3190 def __getattribute__(self, name):
3191 if name == "foo":
3192 return 24
3193 return object.__getattribute__(self, name)
3194 A.__getattribute__ = __getattribute__
3195 self.assertEqual(d.foo, 24)
3196 self.assertEqual(d.bar, 42)
3197 def __getattr__(self, name):
3198 if name in ("spam", "foo", "bar"):
3199 return "hello"
3200 raise AttributeError(name)
3201 B.__getattr__ = __getattr__
3202 self.assertEqual(d.spam, "hello")
3203 self.assertEqual(d.foo, 24)
3204 self.assertEqual(d.bar, 42)
3205 del A.__getattribute__
3206 self.assertEqual(d.foo, 42)
3207 del d.foo
3208 self.assertEqual(d.foo, "hello")
3209 self.assertEqual(d.bar, 42)
3210 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003211 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003212 d.foo
3213 except AttributeError:
3214 pass
3215 else:
3216 self.fail("d.foo should be undefined now")
3217
3218 # Test a nasty bug in recurse_down_subclasses()
3219 import gc
3220 class A(object):
3221 pass
3222 class B(A):
3223 pass
3224 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003225 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003226 A.__setitem__ = lambda *a: None # crash
3227
3228 def test_buffer_inheritance(self):
3229 # Testing that buffer interface is inherited ...
3230
3231 import binascii
3232 # SF bug [#470040] ParseTuple t# vs subclasses.
3233
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003234 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003235 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003236 base = b'abc'
3237 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003238 # b2a_hex uses the buffer interface to get its argument's value, via
3239 # PyArg_ParseTuple 't#' code.
3240 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3241
Georg Brandl479a7e72008-02-05 18:13:15 +00003242 class MyInt(int):
3243 pass
3244 m = MyInt(42)
3245 try:
3246 binascii.b2a_hex(m)
3247 self.fail('subclass of int should not have a buffer interface')
3248 except TypeError:
3249 pass
3250
3251 def test_str_of_str_subclass(self):
3252 # Testing __str__ defined in subclass of str ...
3253 import binascii
3254 import io
3255
3256 class octetstring(str):
3257 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003258 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003259 def __repr__(self):
3260 return self + " repr"
3261
3262 o = octetstring('A')
3263 self.assertEqual(type(o), octetstring)
3264 self.assertEqual(type(str(o)), str)
3265 self.assertEqual(type(repr(o)), str)
3266 self.assertEqual(ord(o), 0x41)
3267 self.assertEqual(str(o), '41')
3268 self.assertEqual(repr(o), 'A repr')
3269 self.assertEqual(o.__str__(), '41')
3270 self.assertEqual(o.__repr__(), 'A repr')
3271
3272 capture = io.StringIO()
3273 # Calling str() or not exercises different internal paths.
3274 print(o, file=capture)
3275 print(str(o), file=capture)
3276 self.assertEqual(capture.getvalue(), '41\n41\n')
3277 capture.close()
3278
3279 def test_keyword_arguments(self):
3280 # Testing keyword arguments to __init__, __call__...
3281 def f(a): return a
3282 self.assertEqual(f.__call__(a=42), 42)
3283 a = []
3284 list.__init__(a, sequence=[0, 1, 2])
3285 self.assertEqual(a, [0, 1, 2])
3286
3287 def test_recursive_call(self):
3288 # Testing recursive __call__() by setting to instance of class...
3289 class A(object):
3290 pass
3291
3292 A.__call__ = A()
3293 try:
3294 A()()
3295 except RuntimeError:
3296 pass
3297 else:
3298 self.fail("Recursion limit should have been reached for __call__()")
3299
3300 def test_delete_hook(self):
3301 # Testing __del__ hook...
3302 log = []
3303 class C(object):
3304 def __del__(self):
3305 log.append(1)
3306 c = C()
3307 self.assertEqual(log, [])
3308 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003309 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003310 self.assertEqual(log, [1])
3311
3312 class D(object): pass
3313 d = D()
3314 try: del d[0]
3315 except TypeError: pass
3316 else: self.fail("invalid del() didn't raise TypeError")
3317
3318 def test_hash_inheritance(self):
3319 # Testing hash of mutable subclasses...
3320
3321 class mydict(dict):
3322 pass
3323 d = mydict()
3324 try:
3325 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003326 except TypeError:
3327 pass
3328 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003329 self.fail("hash() of dict subclass should fail")
3330
3331 class mylist(list):
3332 pass
3333 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003334 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003335 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003336 except TypeError:
3337 pass
3338 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003339 self.fail("hash() of list subclass should fail")
3340
3341 def test_str_operations(self):
3342 try: 'a' + 5
3343 except TypeError: pass
3344 else: self.fail("'' + 5 doesn't raise TypeError")
3345
3346 try: ''.split('')
3347 except ValueError: pass
3348 else: self.fail("''.split('') doesn't raise ValueError")
3349
3350 try: ''.join([0])
3351 except TypeError: pass
3352 else: self.fail("''.join([0]) doesn't raise TypeError")
3353
3354 try: ''.rindex('5')
3355 except ValueError: pass
3356 else: self.fail("''.rindex('5') doesn't raise ValueError")
3357
3358 try: '%(n)s' % None
3359 except TypeError: pass
3360 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3361
3362 try: '%(n' % {}
3363 except ValueError: pass
3364 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3365
3366 try: '%*s' % ('abc')
3367 except TypeError: pass
3368 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3369
3370 try: '%*.*s' % ('abc', 5)
3371 except TypeError: pass
3372 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3373
3374 try: '%s' % (1, 2)
3375 except TypeError: pass
3376 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3377
3378 try: '%' % None
3379 except ValueError: pass
3380 else: self.fail("'%' % None doesn't raise ValueError")
3381
3382 self.assertEqual('534253'.isdigit(), 1)
3383 self.assertEqual('534253x'.isdigit(), 0)
3384 self.assertEqual('%c' % 5, '\x05')
3385 self.assertEqual('%c' % '5', '5')
3386
3387 def test_deepcopy_recursive(self):
3388 # Testing deepcopy of recursive objects...
3389 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003390 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003391 a = Node()
3392 b = Node()
3393 a.b = b
3394 b.a = a
3395 z = deepcopy(a) # This blew up before
3396
3397 def test_unintialized_modules(self):
3398 # Testing uninitialized module objects...
3399 from types import ModuleType as M
3400 m = M.__new__(M)
3401 str(m)
3402 self.assertEqual(hasattr(m, "__name__"), 0)
3403 self.assertEqual(hasattr(m, "__file__"), 0)
3404 self.assertEqual(hasattr(m, "foo"), 0)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003405 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003406 m.foo = 1
3407 self.assertEqual(m.__dict__, {"foo": 1})
3408
3409 def test_funny_new(self):
3410 # Testing __new__ returning something unexpected...
3411 class C(object):
3412 def __new__(cls, arg):
3413 if isinstance(arg, str): return [1, 2, 3]
3414 elif isinstance(arg, int): return object.__new__(D)
3415 else: return object.__new__(cls)
3416 class D(C):
3417 def __init__(self, arg):
3418 self.foo = arg
3419 self.assertEqual(C("1"), [1, 2, 3])
3420 self.assertEqual(D("1"), [1, 2, 3])
3421 d = D(None)
3422 self.assertEqual(d.foo, None)
3423 d = C(1)
3424 self.assertEqual(isinstance(d, D), True)
3425 self.assertEqual(d.foo, 1)
3426 d = D(1)
3427 self.assertEqual(isinstance(d, D), True)
3428 self.assertEqual(d.foo, 1)
3429
3430 def test_imul_bug(self):
3431 # Testing for __imul__ problems...
3432 # SF bug 544647
3433 class C(object):
3434 def __imul__(self, other):
3435 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003436 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003437 y = x
3438 y *= 1.0
3439 self.assertEqual(y, (x, 1.0))
3440 y = x
3441 y *= 2
3442 self.assertEqual(y, (x, 2))
3443 y = x
3444 y *= 3
3445 self.assertEqual(y, (x, 3))
3446 y = x
3447 y *= 1<<100
3448 self.assertEqual(y, (x, 1<<100))
3449 y = x
3450 y *= None
3451 self.assertEqual(y, (x, None))
3452 y = x
3453 y *= "foo"
3454 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003455
Georg Brandl479a7e72008-02-05 18:13:15 +00003456 def test_copy_setstate(self):
3457 # Testing that copy.*copy() correctly uses __setstate__...
3458 import copy
3459 class C(object):
3460 def __init__(self, foo=None):
3461 self.foo = foo
3462 self.__foo = foo
3463 def setfoo(self, foo=None):
3464 self.foo = foo
3465 def getfoo(self):
3466 return self.__foo
3467 def __getstate__(self):
3468 return [self.foo]
3469 def __setstate__(self_, lst):
3470 self.assertEqual(len(lst), 1)
3471 self_.__foo = self_.foo = lst[0]
3472 a = C(42)
3473 a.setfoo(24)
3474 self.assertEqual(a.foo, 24)
3475 self.assertEqual(a.getfoo(), 42)
3476 b = copy.copy(a)
3477 self.assertEqual(b.foo, 24)
3478 self.assertEqual(b.getfoo(), 24)
3479 b = copy.deepcopy(a)
3480 self.assertEqual(b.foo, 24)
3481 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003482
Georg Brandl479a7e72008-02-05 18:13:15 +00003483 def test_slices(self):
3484 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003485
Georg Brandl479a7e72008-02-05 18:13:15 +00003486 # Strings
3487 self.assertEqual("hello"[:4], "hell")
3488 self.assertEqual("hello"[slice(4)], "hell")
3489 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3490 class S(str):
3491 def __getitem__(self, x):
3492 return str.__getitem__(self, x)
3493 self.assertEqual(S("hello")[:4], "hell")
3494 self.assertEqual(S("hello")[slice(4)], "hell")
3495 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3496 # Tuples
3497 self.assertEqual((1,2,3)[:2], (1,2))
3498 self.assertEqual((1,2,3)[slice(2)], (1,2))
3499 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3500 class T(tuple):
3501 def __getitem__(self, x):
3502 return tuple.__getitem__(self, x)
3503 self.assertEqual(T((1,2,3))[:2], (1,2))
3504 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3505 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3506 # Lists
3507 self.assertEqual([1,2,3][:2], [1,2])
3508 self.assertEqual([1,2,3][slice(2)], [1,2])
3509 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3510 class L(list):
3511 def __getitem__(self, x):
3512 return list.__getitem__(self, x)
3513 self.assertEqual(L([1,2,3])[:2], [1,2])
3514 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3515 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3516 # Now do lists and __setitem__
3517 a = L([1,2,3])
3518 a[slice(1, 3)] = [3,2]
3519 self.assertEqual(a, [1,3,2])
3520 a[slice(0, 2, 1)] = [3,1]
3521 self.assertEqual(a, [3,1,2])
3522 a.__setitem__(slice(1, 3), [2,1])
3523 self.assertEqual(a, [3,2,1])
3524 a.__setitem__(slice(0, 2, 1), [2,3])
3525 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003526
Georg Brandl479a7e72008-02-05 18:13:15 +00003527 def test_subtype_resurrection(self):
3528 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003529
Georg Brandl479a7e72008-02-05 18:13:15 +00003530 class C(object):
3531 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003532
Georg Brandl479a7e72008-02-05 18:13:15 +00003533 def __del__(self):
3534 # resurrect the instance
3535 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003536
Georg Brandl479a7e72008-02-05 18:13:15 +00003537 c = C()
3538 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003539
Benjamin Petersone549ead2009-03-28 21:42:05 +00003540 # The most interesting thing here is whether this blows up, due to
3541 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3542 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003543 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003544
Georg Brandl479a7e72008-02-05 18:13:15 +00003545 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Petersone549ead2009-03-28 21:42:05 +00003546 # the last container slot works: that will attempt to delete c again,
3547 # which will cause c to get appended back to the container again
3548 # "during" the del. (On non-CPython implementations, however, __del__
3549 # is typically not called again.)
3550 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003551 self.assertEqual(len(C.container), 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003552 del C.container[-1]
3553 if support.check_impl_detail():
3554 support.gc_collect()
3555 self.assertEqual(len(C.container), 1)
3556 self.assertEqual(C.container[-1].attr, 42)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003557
Georg Brandl479a7e72008-02-05 18:13:15 +00003558 # Make c mortal again, so that the test framework with -l doesn't report
3559 # it as a leak.
3560 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003561
Georg Brandl479a7e72008-02-05 18:13:15 +00003562 def test_slots_trash(self):
3563 # Testing slot trash...
3564 # Deallocating deeply nested slotted trash caused stack overflows
3565 class trash(object):
3566 __slots__ = ['x']
3567 def __init__(self, x):
3568 self.x = x
3569 o = None
3570 for i in range(50000):
3571 o = trash(o)
3572 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003573
Georg Brandl479a7e72008-02-05 18:13:15 +00003574 def test_slots_multiple_inheritance(self):
3575 # SF bug 575229, multiple inheritance w/ slots dumps core
3576 class A(object):
3577 __slots__=()
3578 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003579 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003580 class C(A,B) :
3581 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003582 if support.check_impl_detail():
3583 self.assertEqual(C.__basicsize__, B.__basicsize__)
Georg Brandl479a7e72008-02-05 18:13:15 +00003584 self.assert_(hasattr(C, '__dict__'))
3585 self.assert_(hasattr(C, '__weakref__'))
3586 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003587
Georg Brandl479a7e72008-02-05 18:13:15 +00003588 def test_rmul(self):
3589 # Testing correct invocation of __rmul__...
3590 # SF patch 592646
3591 class C(object):
3592 def __mul__(self, other):
3593 return "mul"
3594 def __rmul__(self, other):
3595 return "rmul"
3596 a = C()
3597 self.assertEqual(a*2, "mul")
3598 self.assertEqual(a*2.2, "mul")
3599 self.assertEqual(2*a, "rmul")
3600 self.assertEqual(2.2*a, "rmul")
3601
3602 def test_ipow(self):
3603 # Testing correct invocation of __ipow__...
3604 # [SF bug 620179]
3605 class C(object):
3606 def __ipow__(self, other):
3607 pass
3608 a = C()
3609 a **= 2
3610
3611 def test_mutable_bases(self):
3612 # Testing mutable bases...
3613
3614 # stuff that should work:
3615 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003616 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003617 class C2(object):
3618 def __getattribute__(self, attr):
3619 if attr == 'a':
3620 return 2
3621 else:
3622 return super(C2, self).__getattribute__(attr)
3623 def meth(self):
3624 return 1
3625 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003626 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003627 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003628 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003629 d = D()
3630 e = E()
3631 D.__bases__ = (C,)
3632 D.__bases__ = (C2,)
3633 self.assertEqual(d.meth(), 1)
3634 self.assertEqual(e.meth(), 1)
3635 self.assertEqual(d.a, 2)
3636 self.assertEqual(e.a, 2)
3637 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003638
Georg Brandl479a7e72008-02-05 18:13:15 +00003639 try:
3640 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003641 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003642 pass
3643 else:
3644 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003645
Georg Brandl479a7e72008-02-05 18:13:15 +00003646 try:
3647 D.__bases__ = ()
3648 except TypeError as msg:
3649 if str(msg) == "a new-style class can't have only classic bases":
3650 self.fail("wrong error message for .__bases__ = ()")
3651 else:
3652 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003653
Georg Brandl479a7e72008-02-05 18:13:15 +00003654 try:
3655 D.__bases__ = (D,)
3656 except TypeError:
3657 pass
3658 else:
3659 # actually, we'll have crashed by here...
3660 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003661
Georg Brandl479a7e72008-02-05 18:13:15 +00003662 try:
3663 D.__bases__ = (C, C)
3664 except TypeError:
3665 pass
3666 else:
3667 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003668
Georg Brandl479a7e72008-02-05 18:13:15 +00003669 try:
3670 D.__bases__ = (E,)
3671 except TypeError:
3672 pass
3673 else:
3674 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003675
Benjamin Petersonae937c02009-04-18 20:54:08 +00003676 def test_builtin_bases(self):
3677 # Make sure all the builtin types can have their base queried without
3678 # segfaulting. See issue #5787.
3679 builtin_types = [tp for tp in builtins.__dict__.values()
3680 if isinstance(tp, type)]
3681 for tp in builtin_types:
3682 object.__getattribute__(tp, "__bases__")
3683 if tp is not object:
3684 self.assertEqual(len(tp.__bases__), 1, tp)
3685
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003686 class L(list):
3687 pass
3688
3689 class C(object):
3690 pass
3691
3692 class D(C):
3693 pass
3694
3695 try:
3696 L.__bases__ = (dict,)
3697 except TypeError:
3698 pass
3699 else:
3700 self.fail("shouldn't turn list subclass into dict subclass")
3701
3702 try:
3703 list.__bases__ = (dict,)
3704 except TypeError:
3705 pass
3706 else:
3707 self.fail("shouldn't be able to assign to list.__bases__")
3708
3709 try:
3710 D.__bases__ = (C, list)
3711 except TypeError:
3712 pass
3713 else:
3714 assert 0, "best_base calculation found wanting"
3715
Benjamin Petersonae937c02009-04-18 20:54:08 +00003716
Georg Brandl479a7e72008-02-05 18:13:15 +00003717 def test_mutable_bases_with_failing_mro(self):
3718 # Testing mutable bases with failing mro...
3719 class WorkOnce(type):
3720 def __new__(self, name, bases, ns):
3721 self.flag = 0
3722 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3723 def mro(self):
3724 if self.flag > 0:
3725 raise RuntimeError("bozo")
3726 else:
3727 self.flag += 1
3728 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003729
Georg Brandl479a7e72008-02-05 18:13:15 +00003730 class WorkAlways(type):
3731 def mro(self):
3732 # this is here to make sure that .mro()s aren't called
3733 # with an exception set (which was possible at one point).
3734 # An error message will be printed in a debug build.
3735 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003736 return type.mro(self)
3737
Georg Brandl479a7e72008-02-05 18:13:15 +00003738 class C(object):
3739 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003740
Georg Brandl479a7e72008-02-05 18:13:15 +00003741 class C2(object):
3742 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003743
Georg Brandl479a7e72008-02-05 18:13:15 +00003744 class D(C):
3745 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003746
Georg Brandl479a7e72008-02-05 18:13:15 +00003747 class E(D):
3748 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003749
Georg Brandl479a7e72008-02-05 18:13:15 +00003750 class F(D, metaclass=WorkOnce):
3751 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003752
Georg Brandl479a7e72008-02-05 18:13:15 +00003753 class G(D, metaclass=WorkAlways):
3754 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003755
Georg Brandl479a7e72008-02-05 18:13:15 +00003756 # Immediate subclasses have their mro's adjusted in alphabetical
3757 # order, so E's will get adjusted before adjusting F's fails. We
3758 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003759
Georg Brandl479a7e72008-02-05 18:13:15 +00003760 E_mro_before = E.__mro__
3761 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00003762
Armin Rigofd163f92005-12-29 15:59:19 +00003763 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003764 D.__bases__ = (C2,)
3765 except RuntimeError:
3766 self.assertEqual(E.__mro__, E_mro_before)
3767 self.assertEqual(D.__mro__, D_mro_before)
3768 else:
3769 self.fail("exception not propagated")
3770
3771 def test_mutable_bases_catch_mro_conflict(self):
3772 # Testing mutable bases catch mro conflict...
3773 class A(object):
3774 pass
3775
3776 class B(object):
3777 pass
3778
3779 class C(A, B):
3780 pass
3781
3782 class D(A, B):
3783 pass
3784
3785 class E(C, D):
3786 pass
3787
3788 try:
3789 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00003790 except TypeError:
3791 pass
3792 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003793 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00003794
Georg Brandl479a7e72008-02-05 18:13:15 +00003795 def test_mutable_names(self):
3796 # Testing mutable names...
3797 class C(object):
3798 pass
3799
3800 # C.__module__ could be 'test_descr' or '__main__'
3801 mod = C.__module__
3802
3803 C.__name__ = 'D'
3804 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
3805
3806 C.__name__ = 'D.E'
3807 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
3808
3809 def test_subclass_right_op(self):
3810 # Testing correct dispatch of subclass overloading __r<op>__...
3811
3812 # This code tests various cases where right-dispatch of a subclass
3813 # should be preferred over left-dispatch of a base class.
3814
3815 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3816
3817 class B(int):
3818 def __floordiv__(self, other):
3819 return "B.__floordiv__"
3820 def __rfloordiv__(self, other):
3821 return "B.__rfloordiv__"
3822
3823 self.assertEqual(B(1) // 1, "B.__floordiv__")
3824 self.assertEqual(1 // B(1), "B.__rfloordiv__")
3825
3826 # Case 2: subclass of object; this is just the baseline for case 3
3827
3828 class C(object):
3829 def __floordiv__(self, other):
3830 return "C.__floordiv__"
3831 def __rfloordiv__(self, other):
3832 return "C.__rfloordiv__"
3833
3834 self.assertEqual(C() // 1, "C.__floordiv__")
3835 self.assertEqual(1 // C(), "C.__rfloordiv__")
3836
3837 # Case 3: subclass of new-style class; here it gets interesting
3838
3839 class D(C):
3840 def __floordiv__(self, other):
3841 return "D.__floordiv__"
3842 def __rfloordiv__(self, other):
3843 return "D.__rfloordiv__"
3844
3845 self.assertEqual(D() // C(), "D.__floordiv__")
3846 self.assertEqual(C() // D(), "D.__rfloordiv__")
3847
3848 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3849
3850 class E(C):
3851 pass
3852
3853 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
3854
3855 self.assertEqual(E() // 1, "C.__floordiv__")
3856 self.assertEqual(1 // E(), "C.__rfloordiv__")
3857 self.assertEqual(E() // C(), "C.__floordiv__")
3858 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
3859
Benjamin Petersone549ead2009-03-28 21:42:05 +00003860 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00003861 def test_meth_class_get(self):
3862 # Testing __get__ method of METH_CLASS C methods...
3863 # Full coverage of descrobject.c::classmethod_get()
3864
3865 # Baseline
3866 arg = [1, 2, 3]
3867 res = {1: None, 2: None, 3: None}
3868 self.assertEqual(dict.fromkeys(arg), res)
3869 self.assertEqual({}.fromkeys(arg), res)
3870
3871 # Now get the descriptor
3872 descr = dict.__dict__["fromkeys"]
3873
3874 # More baseline using the descriptor directly
3875 self.assertEqual(descr.__get__(None, dict)(arg), res)
3876 self.assertEqual(descr.__get__({})(arg), res)
3877
3878 # Now check various error cases
3879 try:
3880 descr.__get__(None, None)
3881 except TypeError:
3882 pass
3883 else:
3884 self.fail("shouldn't have allowed descr.__get__(None, None)")
3885 try:
3886 descr.__get__(42)
3887 except TypeError:
3888 pass
3889 else:
3890 self.fail("shouldn't have allowed descr.__get__(42)")
3891 try:
3892 descr.__get__(None, 42)
3893 except TypeError:
3894 pass
3895 else:
3896 self.fail("shouldn't have allowed descr.__get__(None, 42)")
3897 try:
3898 descr.__get__(None, int)
3899 except TypeError:
3900 pass
3901 else:
3902 self.fail("shouldn't have allowed descr.__get__(None, int)")
3903
3904 def test_isinst_isclass(self):
3905 # Testing proxy isinstance() and isclass()...
3906 class Proxy(object):
3907 def __init__(self, obj):
3908 self.__obj = obj
3909 def __getattribute__(self, name):
3910 if name.startswith("_Proxy__"):
3911 return object.__getattribute__(self, name)
3912 else:
3913 return getattr(self.__obj, name)
3914 # Test with a classic class
3915 class C:
3916 pass
3917 a = C()
3918 pa = Proxy(a)
3919 self.assert_(isinstance(a, C)) # Baseline
3920 self.assert_(isinstance(pa, C)) # Test
3921 # Test with a classic subclass
3922 class D(C):
3923 pass
3924 a = D()
3925 pa = Proxy(a)
3926 self.assert_(isinstance(a, C)) # Baseline
3927 self.assert_(isinstance(pa, C)) # Test
3928 # Test with a new-style class
3929 class C(object):
3930 pass
3931 a = C()
3932 pa = Proxy(a)
3933 self.assert_(isinstance(a, C)) # Baseline
3934 self.assert_(isinstance(pa, C)) # Test
3935 # Test with a new-style subclass
3936 class D(C):
3937 pass
3938 a = D()
3939 pa = Proxy(a)
3940 self.assert_(isinstance(a, C)) # Baseline
3941 self.assert_(isinstance(pa, C)) # Test
3942
3943 def test_proxy_super(self):
3944 # Testing super() for a proxy object...
3945 class Proxy(object):
3946 def __init__(self, obj):
3947 self.__obj = obj
3948 def __getattribute__(self, name):
3949 if name.startswith("_Proxy__"):
3950 return object.__getattribute__(self, name)
3951 else:
3952 return getattr(self.__obj, name)
3953
3954 class B(object):
3955 def f(self):
3956 return "B.f"
3957
3958 class C(B):
3959 def f(self):
3960 return super(C, self).f() + "->C.f"
3961
3962 obj = C()
3963 p = Proxy(obj)
3964 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
3965
3966 def test_carloverre(self):
3967 # Testing prohibition of Carlo Verre's hack...
3968 try:
3969 object.__setattr__(str, "foo", 42)
3970 except TypeError:
3971 pass
3972 else:
3973 self.fail("Carlo Verre __setattr__ suceeded!")
3974 try:
3975 object.__delattr__(str, "lower")
3976 except TypeError:
3977 pass
3978 else:
3979 self.fail("Carlo Verre __delattr__ succeeded!")
3980
3981 def test_weakref_segfault(self):
3982 # Testing weakref segfault...
3983 # SF 742911
3984 import weakref
3985
3986 class Provoker:
3987 def __init__(self, referrent):
3988 self.ref = weakref.ref(referrent)
3989
3990 def __del__(self):
3991 x = self.ref()
3992
3993 class Oops(object):
3994 pass
3995
3996 o = Oops()
3997 o.whatever = Provoker(o)
3998 del o
3999
4000 def test_wrapper_segfault(self):
4001 # SF 927248: deeply nested wrappers could cause stack overflow
4002 f = lambda:None
4003 for i in range(1000000):
4004 f = f.__call__
4005 f = None
4006
4007 def test_file_fault(self):
4008 # Testing sys.stdout is changed in getattr...
4009 import sys
4010 class StdoutGuard:
4011 def __getattr__(self, attr):
4012 sys.stdout = sys.__stdout__
4013 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4014 sys.stdout = StdoutGuard()
4015 try:
4016 print("Oops!")
4017 except RuntimeError:
4018 pass
4019
4020 def test_vicious_descriptor_nonsense(self):
4021 # Testing vicious_descriptor_nonsense...
4022
4023 # A potential segfault spotted by Thomas Wouters in mail to
4024 # python-dev 2003-04-17, turned into an example & fixed by Michael
4025 # Hudson just less than four months later...
4026
4027 class Evil(object):
4028 def __hash__(self):
4029 return hash('attr')
4030 def __eq__(self, other):
4031 del C.attr
4032 return 0
4033
4034 class Descr(object):
4035 def __get__(self, ob, type=None):
4036 return 1
4037
4038 class C(object):
4039 attr = Descr()
4040
4041 c = C()
4042 c.__dict__[Evil()] = 0
4043
4044 self.assertEqual(c.attr, 1)
4045 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004046 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00004047 self.assertEqual(hasattr(c, 'attr'), False)
4048
4049 def test_init(self):
4050 # SF 1155938
4051 class Foo(object):
4052 def __init__(self):
4053 return 10
4054 try:
4055 Foo()
4056 except TypeError:
4057 pass
4058 else:
4059 self.fail("did not test __init__() for None return")
4060
4061 def test_method_wrapper(self):
4062 # Testing method-wrapper objects...
4063 # <type 'method-wrapper'> did not support any reflection before 2.5
4064
Mark Dickinson211c6252009-02-01 10:28:51 +00004065 # XXX should methods really support __eq__?
Georg Brandl479a7e72008-02-05 18:13:15 +00004066
4067 l = []
4068 self.assertEqual(l.__add__, l.__add__)
4069 self.assertEqual(l.__add__, [].__add__)
4070 self.assert_(l.__add__ != [5].__add__)
4071 self.assert_(l.__add__ != l.__mul__)
4072 self.assert_(l.__add__.__name__ == '__add__')
Benjamin Petersone549ead2009-03-28 21:42:05 +00004073 if hasattr(l.__add__, '__self__'):
4074 # CPython
4075 self.assert_(l.__add__.__self__ is l)
4076 self.assert_(l.__add__.__objclass__ is list)
4077 else:
4078 # Python implementations where [].__add__ is a normal bound method
4079 self.assert_(l.__add__.im_self is l)
4080 self.assert_(l.__add__.im_class is list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004081 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4082 try:
4083 hash(l.__add__)
4084 except TypeError:
4085 pass
4086 else:
4087 self.fail("no TypeError from hash([].__add__)")
4088
4089 t = ()
4090 t += (7,)
4091 self.assertEqual(t.__add__, (7,).__add__)
4092 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4093
4094 def test_not_implemented(self):
4095 # Testing NotImplemented...
4096 # all binary methods should be able to return a NotImplemented
4097 import sys
4098 import types
4099 import operator
4100
4101 def specialmethod(self, other):
4102 return NotImplemented
4103
4104 def check(expr, x, y):
4105 try:
4106 exec(expr, {'x': x, 'y': y, 'operator': operator})
4107 except TypeError:
4108 pass
4109 else:
4110 self.fail("no TypeError from %r" % (expr,))
4111
4112 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4113 # TypeErrors
4114 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4115 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004116 for name, expr, iexpr in [
4117 ('__add__', 'x + y', 'x += y'),
4118 ('__sub__', 'x - y', 'x -= y'),
4119 ('__mul__', 'x * y', 'x *= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004120 ('__truediv__', 'operator.truediv(x, y)', None),
4121 ('__floordiv__', 'operator.floordiv(x, y)', None),
4122 ('__div__', 'x / y', 'x /= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004123 ('__mod__', 'x % y', 'x %= y'),
4124 ('__divmod__', 'divmod(x, y)', None),
4125 ('__pow__', 'x ** y', 'x **= y'),
4126 ('__lshift__', 'x << y', 'x <<= y'),
4127 ('__rshift__', 'x >> y', 'x >>= y'),
4128 ('__and__', 'x & y', 'x &= y'),
4129 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004130 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004131 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004132 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004133 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004134 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004135 check(expr, a, N1)
4136 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004137 if iexpr:
4138 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004139 check(iexpr, a, N1)
4140 check(iexpr, a, N2)
4141 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004142 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004143 c = C()
4144 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004145 check(iexpr, c, N1)
4146 check(iexpr, c, N2)
4147
Georg Brandl479a7e72008-02-05 18:13:15 +00004148 def test_assign_slice(self):
4149 # ceval.c's assign_slice used to check for
4150 # tp->tp_as_sequence->sq_slice instead of
4151 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004152
Georg Brandl479a7e72008-02-05 18:13:15 +00004153 class C(object):
4154 def __setitem__(self, idx, value):
4155 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004156
Georg Brandl479a7e72008-02-05 18:13:15 +00004157 c = C()
4158 c[1:2] = 3
4159 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004160
Benjamin Peterson9262b842008-11-17 22:45:50 +00004161 def test_getattr_hooks(self):
4162 # issue 4230
4163
4164 class Descriptor(object):
4165 counter = 0
4166 def __get__(self, obj, objtype=None):
4167 def getter(name):
4168 self.counter += 1
4169 raise AttributeError(name)
4170 return getter
4171
4172 descr = Descriptor()
4173 class A(object):
4174 __getattribute__ = descr
4175 class B(object):
4176 __getattr__ = descr
4177 class C(object):
4178 __getattribute__ = descr
4179 __getattr__ = descr
4180
4181 self.assertRaises(AttributeError, getattr, A(), "attr")
4182 self.assertEquals(descr.counter, 1)
4183 self.assertRaises(AttributeError, getattr, B(), "attr")
4184 self.assertEquals(descr.counter, 2)
4185 self.assertRaises(AttributeError, getattr, C(), "attr")
4186 self.assertEquals(descr.counter, 4)
4187
4188 import gc
4189 class EvilGetattribute(object):
4190 # This used to segfault
4191 def __getattr__(self, name):
4192 raise AttributeError(name)
4193 def __getattribute__(self, name):
4194 del EvilGetattribute.__getattr__
4195 for i in range(5):
4196 gc.collect()
4197 raise AttributeError(name)
4198
4199 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4200
Christian Heimesbbffeb62008-01-24 09:42:52 +00004201
Georg Brandl479a7e72008-02-05 18:13:15 +00004202class DictProxyTests(unittest.TestCase):
4203 def setUp(self):
4204 class C(object):
4205 def meth(self):
4206 pass
4207 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004208
Georg Brandl479a7e72008-02-05 18:13:15 +00004209 def test_iter_keys(self):
4210 # Testing dict-proxy iterkeys...
4211 keys = [ key for key in self.C.__dict__.keys() ]
4212 keys.sort()
4213 self.assertEquals(keys, ['__dict__', '__doc__', '__module__',
4214 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004215
Georg Brandl479a7e72008-02-05 18:13:15 +00004216 def test_iter_values(self):
4217 # Testing dict-proxy itervalues...
4218 values = [ values for values in self.C.__dict__.values() ]
4219 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004220
Georg Brandl479a7e72008-02-05 18:13:15 +00004221 def test_iter_items(self):
4222 # Testing dict-proxy iteritems...
4223 keys = [ key for (key, value) in self.C.__dict__.items() ]
4224 keys.sort()
4225 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4226 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004227
Georg Brandl479a7e72008-02-05 18:13:15 +00004228 def test_dict_type_with_metaclass(self):
4229 # Testing type of __dict__ when metaclass set...
4230 class B(object):
4231 pass
4232 class M(type):
4233 pass
4234 class C(metaclass=M):
4235 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4236 pass
4237 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004238
Christian Heimesbbffeb62008-01-24 09:42:52 +00004239
Georg Brandl479a7e72008-02-05 18:13:15 +00004240class PTypesLongInitTest(unittest.TestCase):
4241 # This is in its own TestCase so that it can be run before any other tests.
4242 def test_pytype_long_ready(self):
4243 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004244
Georg Brandl479a7e72008-02-05 18:13:15 +00004245 # This dumps core when SF bug 551412 isn't fixed --
4246 # but only when test_descr.py is run separately.
4247 # (That can't be helped -- as soon as PyType_Ready()
4248 # is called for PyLong_Type, the bug is gone.)
4249 class UserLong(object):
4250 def __pow__(self, *args):
4251 pass
4252 try:
4253 pow(0, UserLong(), 0)
4254 except:
4255 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004256
Georg Brandl479a7e72008-02-05 18:13:15 +00004257 # Another segfault only when run early
4258 # (before PyType_Ready(tuple) is called)
4259 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004260
4261
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004262def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00004263 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004264 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Georg Brandl479a7e72008-02-05 18:13:15 +00004265 ClassPropertiesAndMethods, DictProxyTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004266
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004267if __name__ == "__main__":
4268 test_main()