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