blob: 7137095774da55b912e6a7c58855a600755ce339 [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)
1575 return self
1576 def __call__(self, *args):
1577 return self.impl(*args)
1578
1579
1580 for name, runner, meth_impl in specials:
1581 class X(Checker):
1582 pass
1583 setattr(X, name, staticmethod(meth_impl))
1584 runner(X())
1585
1586 record = []
1587 class X(Checker):
1588 pass
1589 setattr(X, name, SpecialDescr(meth_impl))
1590 runner(X())
1591 self.assertEqual(record, [1], name)
1592
Georg Brandl479a7e72008-02-05 18:13:15 +00001593 def test_specials(self):
1594 # Testing special operators...
1595 # Test operators like __hash__ for which a built-in default exists
1596
1597 # Test the default behavior for static classes
1598 class C(object):
1599 def __getitem__(self, i):
1600 if 0 <= i < 10: return i
1601 raise IndexError
1602 c1 = C()
1603 c2 = C()
1604 self.assert_(not not c1) # What?
1605 self.assertNotEqual(id(c1), id(c2))
1606 hash(c1)
1607 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001608 self.assertEqual(c1, c1)
1609 self.assert_(c1 != c2)
1610 self.assert_(not c1 != c1)
1611 self.assert_(not c1 == c2)
1612 # Note that the module name appears in str/repr, and that varies
1613 # depending on whether this test is run standalone or from a framework.
1614 self.assert_(str(c1).find('C object at ') >= 0)
1615 self.assertEqual(str(c1), repr(c1))
1616 self.assert_(-1 not in c1)
1617 for i in range(10):
1618 self.assert_(i in c1)
1619 self.assertFalse(10 in c1)
1620 # Test the default behavior for dynamic classes
1621 class D(object):
1622 def __getitem__(self, i):
1623 if 0 <= i < 10: return i
1624 raise IndexError
1625 d1 = D()
1626 d2 = D()
1627 self.assert_(not not d1)
1628 self.assertNotEqual(id(d1), id(d2))
1629 hash(d1)
1630 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001631 self.assertEqual(d1, d1)
1632 self.assertNotEqual(d1, d2)
1633 self.assert_(not d1 != d1)
1634 self.assert_(not d1 == d2)
1635 # Note that the module name appears in str/repr, and that varies
1636 # depending on whether this test is run standalone or from a framework.
1637 self.assert_(str(d1).find('D object at ') >= 0)
1638 self.assertEqual(str(d1), repr(d1))
1639 self.assert_(-1 not in d1)
1640 for i in range(10):
1641 self.assert_(i in d1)
1642 self.assertFalse(10 in d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00001643 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00001644 class Proxy(object):
1645 def __init__(self, x):
1646 self.x = x
1647 def __bool__(self):
1648 return not not self.x
1649 def __hash__(self):
1650 return hash(self.x)
1651 def __eq__(self, other):
1652 return self.x == other
1653 def __ne__(self, other):
1654 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00001655 def __ge__(self, other):
1656 return self.x >= other
1657 def __gt__(self, other):
1658 return self.x > other
1659 def __le__(self, other):
1660 return self.x <= other
1661 def __lt__(self, other):
1662 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00001663 def __str__(self):
1664 return "Proxy:%s" % self.x
1665 def __repr__(self):
1666 return "Proxy(%r)" % self.x
1667 def __contains__(self, value):
1668 return value in self.x
1669 p0 = Proxy(0)
1670 p1 = Proxy(1)
1671 p_1 = Proxy(-1)
1672 self.assertFalse(p0)
1673 self.assert_(not not p1)
1674 self.assertEqual(hash(p0), hash(0))
1675 self.assertEqual(p0, p0)
1676 self.assertNotEqual(p0, p1)
1677 self.assert_(not p0 != p0)
1678 self.assertEqual(not p0, p1)
Benjamin Peterson60192082008-10-16 19:34:46 +00001679 self.assert_(p0 < p1)
1680 self.assert_(p0 <= p1)
1681 self.assert_(p1 > p0)
1682 self.assert_(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001683 self.assertEqual(str(p0), "Proxy:0")
1684 self.assertEqual(repr(p0), "Proxy(0)")
1685 p10 = Proxy(range(10))
1686 self.assertFalse(-1 in p10)
1687 for i in range(10):
1688 self.assert_(i in p10)
1689 self.assertFalse(10 in p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001690
Georg Brandl479a7e72008-02-05 18:13:15 +00001691 def test_weakrefs(self):
1692 # Testing weak references...
1693 import weakref
1694 class C(object):
1695 pass
1696 c = C()
1697 r = weakref.ref(c)
1698 self.assertEqual(r(), c)
1699 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00001700 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001701 self.assertEqual(r(), None)
1702 del r
1703 class NoWeak(object):
1704 __slots__ = ['foo']
1705 no = NoWeak()
1706 try:
1707 weakref.ref(no)
1708 except TypeError as msg:
1709 self.assert_(str(msg).find("weak reference") >= 0)
1710 else:
1711 self.fail("weakref.ref(no) should be illegal")
1712 class Weak(object):
1713 __slots__ = ['foo', '__weakref__']
1714 yes = Weak()
1715 r = weakref.ref(yes)
1716 self.assertEqual(r(), yes)
1717 del yes
Benjamin Petersone549ead2009-03-28 21:42:05 +00001718 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001719 self.assertEqual(r(), None)
1720 del r
1721
1722 def test_properties(self):
1723 # Testing property...
1724 class C(object):
1725 def getx(self):
1726 return self.__x
1727 def setx(self, value):
1728 self.__x = value
1729 def delx(self):
1730 del self.__x
1731 x = property(getx, setx, delx, doc="I'm the x property.")
1732 a = C()
1733 self.assertFalse(hasattr(a, "x"))
1734 a.x = 42
1735 self.assertEqual(a._C__x, 42)
1736 self.assertEqual(a.x, 42)
1737 del a.x
1738 self.assertFalse(hasattr(a, "x"))
1739 self.assertFalse(hasattr(a, "_C__x"))
1740 C.x.__set__(a, 100)
1741 self.assertEqual(C.x.__get__(a), 100)
1742 C.x.__delete__(a)
1743 self.assertFalse(hasattr(a, "x"))
1744
1745 raw = C.__dict__['x']
1746 self.assert_(isinstance(raw, property))
1747
1748 attrs = dir(raw)
1749 self.assert_("__doc__" in attrs)
1750 self.assert_("fget" in attrs)
1751 self.assert_("fset" in attrs)
1752 self.assert_("fdel" in attrs)
1753
1754 self.assertEqual(raw.__doc__, "I'm the x property.")
1755 self.assert_(raw.fget is C.__dict__['getx'])
1756 self.assert_(raw.fset is C.__dict__['setx'])
1757 self.assert_(raw.fdel is C.__dict__['delx'])
1758
1759 for attr in "__doc__", "fget", "fset", "fdel":
1760 try:
1761 setattr(raw, attr, 42)
1762 except AttributeError as msg:
1763 if str(msg).find('readonly') < 0:
1764 self.fail("when setting readonly attr %r on a property, "
1765 "got unexpected AttributeError msg %r" % (attr, str(msg)))
1766 else:
1767 self.fail("expected AttributeError from trying to set readonly %r "
1768 "attr on a property" % attr)
1769
1770 class D(object):
1771 __getitem__ = property(lambda s: 1/0)
1772
1773 d = D()
1774 try:
1775 for i in d:
1776 str(i)
1777 except ZeroDivisionError:
1778 pass
1779 else:
1780 self.fail("expected ZeroDivisionError from bad property")
1781
1782 class E(object):
1783 def getter(self):
1784 "getter method"
1785 return 0
1786 def setter(self_, value):
1787 "setter method"
1788 pass
1789 prop = property(getter)
1790 self.assertEqual(prop.__doc__, "getter method")
1791 prop2 = property(fset=setter)
1792 self.assertEqual(prop2.__doc__, None)
1793
1794 # this segfaulted in 2.5b2
1795 try:
1796 import _testcapi
1797 except ImportError:
1798 pass
1799 else:
1800 class X(object):
1801 p = property(_testcapi.test_with_docstring)
1802
1803 def test_properties_plus(self):
1804 class C(object):
1805 foo = property(doc="hello")
1806 @foo.getter
1807 def foo(self):
1808 return self._foo
1809 @foo.setter
1810 def foo(self, value):
1811 self._foo = abs(value)
1812 @foo.deleter
1813 def foo(self):
1814 del self._foo
1815 c = C()
1816 self.assertEqual(C.foo.__doc__, "hello")
1817 self.assertFalse(hasattr(c, "foo"))
1818 c.foo = -42
1819 self.assert_(hasattr(c, '_foo'))
1820 self.assertEqual(c._foo, 42)
1821 self.assertEqual(c.foo, 42)
1822 del c.foo
1823 self.assertFalse(hasattr(c, '_foo'))
1824 self.assertFalse(hasattr(c, "foo"))
1825
1826 class D(C):
1827 @C.foo.deleter
1828 def foo(self):
1829 try:
1830 del self._foo
1831 except AttributeError:
1832 pass
1833 d = D()
1834 d.foo = 24
1835 self.assertEqual(d.foo, 24)
1836 del d.foo
1837 del d.foo
1838
1839 class E(object):
1840 @property
1841 def foo(self):
1842 return self._foo
1843 @foo.setter
1844 def foo(self, value):
1845 raise RuntimeError
1846 @foo.setter
1847 def foo(self, value):
1848 self._foo = abs(value)
1849 @foo.deleter
1850 def foo(self, value=None):
1851 del self._foo
1852
1853 e = E()
1854 e.foo = -42
1855 self.assertEqual(e.foo, 42)
1856 del e.foo
1857
1858 class F(E):
1859 @E.foo.deleter
1860 def foo(self):
1861 del self._foo
1862 @foo.setter
1863 def foo(self, value):
1864 self._foo = max(0, value)
1865 f = F()
1866 f.foo = -10
1867 self.assertEqual(f.foo, 0)
1868 del f.foo
1869
1870 def test_dict_constructors(self):
1871 # Testing dict constructor ...
1872 d = dict()
1873 self.assertEqual(d, {})
1874 d = dict({})
1875 self.assertEqual(d, {})
1876 d = dict({1: 2, 'a': 'b'})
1877 self.assertEqual(d, {1: 2, 'a': 'b'})
1878 self.assertEqual(d, dict(list(d.items())))
1879 self.assertEqual(d, dict(iter(d.items())))
1880 d = dict({'one':1, 'two':2})
1881 self.assertEqual(d, dict(one=1, two=2))
1882 self.assertEqual(d, dict(**d))
1883 self.assertEqual(d, dict({"one": 1}, two=2))
1884 self.assertEqual(d, dict([("two", 2)], one=1))
1885 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
1886 self.assertEqual(d, dict(**d))
1887
1888 for badarg in 0, 0, 0j, "0", [0], (0,):
1889 try:
1890 dict(badarg)
1891 except TypeError:
1892 pass
1893 except ValueError:
1894 if badarg == "0":
1895 # It's a sequence, and its elements are also sequences (gotta
1896 # love strings <wink>), but they aren't of length 2, so this
1897 # one seemed better as a ValueError than a TypeError.
1898 pass
1899 else:
1900 self.fail("no TypeError from dict(%r)" % badarg)
1901 else:
1902 self.fail("no TypeError from dict(%r)" % badarg)
1903
1904 try:
1905 dict({}, {})
1906 except TypeError:
1907 pass
1908 else:
1909 self.fail("no TypeError from dict({}, {})")
1910
1911 class Mapping:
1912 # Lacks a .keys() method; will be added later.
1913 dict = {1:2, 3:4, 'a':1j}
1914
1915 try:
1916 dict(Mapping())
1917 except TypeError:
1918 pass
1919 else:
1920 self.fail("no TypeError from dict(incomplete mapping)")
1921
1922 Mapping.keys = lambda self: list(self.dict.keys())
1923 Mapping.__getitem__ = lambda self, i: self.dict[i]
1924 d = dict(Mapping())
1925 self.assertEqual(d, Mapping.dict)
1926
1927 # Init from sequence of iterable objects, each producing a 2-sequence.
1928 class AddressBookEntry:
1929 def __init__(self, first, last):
1930 self.first = first
1931 self.last = last
1932 def __iter__(self):
1933 return iter([self.first, self.last])
1934
1935 d = dict([AddressBookEntry('Tim', 'Warsaw'),
1936 AddressBookEntry('Barry', 'Peters'),
1937 AddressBookEntry('Tim', 'Peters'),
1938 AddressBookEntry('Barry', 'Warsaw')])
1939 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
1940
1941 d = dict(zip(range(4), range(1, 5)))
1942 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
1943
1944 # Bad sequence lengths.
1945 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
1946 try:
1947 dict(bad)
1948 except ValueError:
1949 pass
1950 else:
1951 self.fail("no ValueError from dict(%r)" % bad)
1952
1953 def test_dir(self):
1954 # Testing dir() ...
1955 junk = 12
1956 self.assertEqual(dir(), ['junk', 'self'])
1957 del junk
1958
1959 # Just make sure these don't blow up!
1960 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
1961 dir(arg)
1962
1963 # Test dir on new-style classes. Since these have object as a
1964 # base class, a lot more gets sucked in.
1965 def interesting(strings):
1966 return [s for s in strings if not s.startswith('_')]
1967
1968 class C(object):
1969 Cdata = 1
1970 def Cmethod(self): pass
1971
1972 cstuff = ['Cdata', 'Cmethod']
1973 self.assertEqual(interesting(dir(C)), cstuff)
1974
1975 c = C()
1976 self.assertEqual(interesting(dir(c)), cstuff)
1977 ## self.assert_('__self__' in dir(C.Cmethod))
1978
1979 c.cdata = 2
1980 c.cmethod = lambda self: 0
1981 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
1982 ## self.assert_('__self__' in dir(c.Cmethod))
1983
1984 class A(C):
1985 Adata = 1
1986 def Amethod(self): pass
1987
1988 astuff = ['Adata', 'Amethod'] + cstuff
1989 self.assertEqual(interesting(dir(A)), astuff)
1990 ## self.assert_('__self__' in dir(A.Amethod))
1991 a = A()
1992 self.assertEqual(interesting(dir(a)), astuff)
1993 a.adata = 42
1994 a.amethod = lambda self: 3
1995 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
1996 ## self.assert_('__self__' in dir(a.Amethod))
1997
1998 # Try a module subclass.
1999 import sys
2000 class M(type(sys)):
2001 pass
2002 minstance = M("m")
2003 minstance.b = 2
2004 minstance.a = 1
2005 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2006 self.assertEqual(names, ['a', 'b'])
2007
2008 class M2(M):
2009 def getdict(self):
2010 return "Not a dict!"
2011 __dict__ = property(getdict)
2012
2013 m2instance = M2("m2")
2014 m2instance.b = 2
2015 m2instance.a = 1
2016 self.assertEqual(m2instance.__dict__, "Not a dict!")
2017 try:
2018 dir(m2instance)
2019 except TypeError:
2020 pass
2021
2022 # Two essentially featureless objects, just inheriting stuff from
2023 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00002024 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
2025 if support.check_impl_detail():
2026 # None differs in PyPy: it has a __nonzero__
2027 self.assertEqual(dir(None), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002028
2029 # Nasty test case for proxied objects
2030 class Wrapper(object):
2031 def __init__(self, obj):
2032 self.__obj = obj
2033 def __repr__(self):
2034 return "Wrapper(%s)" % repr(self.__obj)
2035 def __getitem__(self, key):
2036 return Wrapper(self.__obj[key])
2037 def __len__(self):
2038 return len(self.__obj)
2039 def __getattr__(self, name):
2040 return Wrapper(getattr(self.__obj, name))
2041
2042 class C(object):
2043 def __getclass(self):
2044 return Wrapper(type(self))
2045 __class__ = property(__getclass)
2046
2047 dir(C()) # This used to segfault
2048
2049 def test_supers(self):
2050 # Testing super...
2051
2052 class A(object):
2053 def meth(self, a):
2054 return "A(%r)" % a
2055
2056 self.assertEqual(A().meth(1), "A(1)")
2057
2058 class B(A):
2059 def __init__(self):
2060 self.__super = super(B, self)
2061 def meth(self, a):
2062 return "B(%r)" % a + self.__super.meth(a)
2063
2064 self.assertEqual(B().meth(2), "B(2)A(2)")
2065
2066 class C(A):
2067 def meth(self, a):
2068 return "C(%r)" % a + self.__super.meth(a)
2069 C._C__super = super(C)
2070
2071 self.assertEqual(C().meth(3), "C(3)A(3)")
2072
2073 class D(C, B):
2074 def meth(self, a):
2075 return "D(%r)" % a + super(D, self).meth(a)
2076
2077 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2078
2079 # Test for subclassing super
2080
2081 class mysuper(super):
2082 def __init__(self, *args):
2083 return super(mysuper, self).__init__(*args)
2084
2085 class E(D):
2086 def meth(self, a):
2087 return "E(%r)" % a + mysuper(E, self).meth(a)
2088
2089 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2090
2091 class F(E):
2092 def meth(self, a):
2093 s = self.__super # == mysuper(F, self)
2094 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2095 F._F__super = mysuper(F)
2096
2097 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2098
2099 # Make sure certain errors are raised
2100
2101 try:
2102 super(D, 42)
2103 except TypeError:
2104 pass
2105 else:
2106 self.fail("shouldn't allow super(D, 42)")
2107
2108 try:
2109 super(D, C())
2110 except TypeError:
2111 pass
2112 else:
2113 self.fail("shouldn't allow super(D, C())")
2114
2115 try:
2116 super(D).__get__(12)
2117 except TypeError:
2118 pass
2119 else:
2120 self.fail("shouldn't allow super(D).__get__(12)")
2121
2122 try:
2123 super(D).__get__(C())
2124 except TypeError:
2125 pass
2126 else:
2127 self.fail("shouldn't allow super(D).__get__(C())")
2128
2129 # Make sure data descriptors can be overridden and accessed via super
2130 # (new feature in Python 2.3)
2131
2132 class DDbase(object):
2133 def getx(self): return 42
2134 x = property(getx)
2135
2136 class DDsub(DDbase):
2137 def getx(self): return "hello"
2138 x = property(getx)
2139
2140 dd = DDsub()
2141 self.assertEqual(dd.x, "hello")
2142 self.assertEqual(super(DDsub, dd).x, 42)
2143
2144 # Ensure that super() lookup of descriptor from classmethod
2145 # works (SF ID# 743627)
2146
2147 class Base(object):
2148 aProp = property(lambda self: "foo")
2149
2150 class Sub(Base):
2151 @classmethod
2152 def test(klass):
2153 return super(Sub,klass).aProp
2154
2155 self.assertEqual(Sub.test(), Base.aProp)
2156
2157 # Verify that super() doesn't allow keyword args
2158 try:
2159 super(Base, kw=1)
2160 except TypeError:
2161 pass
2162 else:
2163 self.assertEqual("super shouldn't accept keyword args")
2164
2165 def test_basic_inheritance(self):
2166 # Testing inheritance from basic types...
2167
2168 class hexint(int):
2169 def __repr__(self):
2170 return hex(self)
2171 def __add__(self, other):
2172 return hexint(int.__add__(self, other))
2173 # (Note that overriding __radd__ doesn't work,
2174 # because the int type gets first dibs.)
2175 self.assertEqual(repr(hexint(7) + 9), "0x10")
2176 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2177 a = hexint(12345)
2178 self.assertEqual(a, 12345)
2179 self.assertEqual(int(a), 12345)
2180 self.assert_(int(a).__class__ is int)
2181 self.assertEqual(hash(a), hash(12345))
2182 self.assert_((+a).__class__ is int)
2183 self.assert_((a >> 0).__class__ is int)
2184 self.assert_((a << 0).__class__ is int)
2185 self.assert_((hexint(0) << 12).__class__ is int)
2186 self.assert_((hexint(0) >> 12).__class__ is int)
2187
2188 class octlong(int):
2189 __slots__ = []
2190 def __str__(self):
2191 s = oct(self)
2192 if s[-1] == 'L':
2193 s = s[:-1]
2194 return s
2195 def __add__(self, other):
2196 return self.__class__(super(octlong, self).__add__(other))
2197 __radd__ = __add__
2198 self.assertEqual(str(octlong(3) + 5), "0o10")
2199 # (Note that overriding __radd__ here only seems to work
2200 # because the example uses a short int left argument.)
2201 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2202 a = octlong(12345)
2203 self.assertEqual(a, 12345)
2204 self.assertEqual(int(a), 12345)
2205 self.assertEqual(hash(a), hash(12345))
2206 self.assert_(int(a).__class__ is int)
2207 self.assert_((+a).__class__ is int)
2208 self.assert_((-a).__class__ is int)
2209 self.assert_((-octlong(0)).__class__ is int)
2210 self.assert_((a >> 0).__class__ is int)
2211 self.assert_((a << 0).__class__ is int)
2212 self.assert_((a - 0).__class__ is int)
2213 self.assert_((a * 1).__class__ is int)
2214 self.assert_((a ** 1).__class__ is int)
2215 self.assert_((a // 1).__class__ is int)
2216 self.assert_((1 * a).__class__ is int)
2217 self.assert_((a | 0).__class__ is int)
2218 self.assert_((a ^ 0).__class__ is int)
2219 self.assert_((a & -1).__class__ is int)
2220 self.assert_((octlong(0) << 12).__class__ is int)
2221 self.assert_((octlong(0) >> 12).__class__ is int)
2222 self.assert_(abs(octlong(0)).__class__ is int)
2223
2224 # Because octlong overrides __add__, we can't check the absence of +0
2225 # optimizations using octlong.
2226 class longclone(int):
2227 pass
2228 a = longclone(1)
2229 self.assert_((a + 0).__class__ is int)
2230 self.assert_((0 + a).__class__ is int)
2231
2232 # Check that negative clones don't segfault
2233 a = longclone(-1)
2234 self.assertEqual(a.__dict__, {})
2235 self.assertEqual(int(a), -1) # self.assert_ PyNumber_Long() copies the sign bit
2236
2237 class precfloat(float):
2238 __slots__ = ['prec']
2239 def __init__(self, value=0.0, prec=12):
2240 self.prec = int(prec)
2241 def __repr__(self):
2242 return "%.*g" % (self.prec, self)
2243 self.assertEqual(repr(precfloat(1.1)), "1.1")
2244 a = precfloat(12345)
2245 self.assertEqual(a, 12345.0)
2246 self.assertEqual(float(a), 12345.0)
2247 self.assert_(float(a).__class__ is float)
2248 self.assertEqual(hash(a), hash(12345.0))
2249 self.assert_((+a).__class__ is float)
2250
2251 class madcomplex(complex):
2252 def __repr__(self):
2253 return "%.17gj%+.17g" % (self.imag, self.real)
2254 a = madcomplex(-3, 4)
2255 self.assertEqual(repr(a), "4j-3")
2256 base = complex(-3, 4)
2257 self.assertEqual(base.__class__, complex)
2258 self.assertEqual(a, base)
2259 self.assertEqual(complex(a), base)
2260 self.assertEqual(complex(a).__class__, complex)
2261 a = madcomplex(a) # just trying another form of the constructor
2262 self.assertEqual(repr(a), "4j-3")
2263 self.assertEqual(a, base)
2264 self.assertEqual(complex(a), base)
2265 self.assertEqual(complex(a).__class__, complex)
2266 self.assertEqual(hash(a), hash(base))
2267 self.assertEqual((+a).__class__, complex)
2268 self.assertEqual((a + 0).__class__, complex)
2269 self.assertEqual(a + 0, base)
2270 self.assertEqual((a - 0).__class__, complex)
2271 self.assertEqual(a - 0, base)
2272 self.assertEqual((a * 1).__class__, complex)
2273 self.assertEqual(a * 1, base)
2274 self.assertEqual((a / 1).__class__, complex)
2275 self.assertEqual(a / 1, base)
2276
2277 class madtuple(tuple):
2278 _rev = None
2279 def rev(self):
2280 if self._rev is not None:
2281 return self._rev
2282 L = list(self)
2283 L.reverse()
2284 self._rev = self.__class__(L)
2285 return self._rev
2286 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2287 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2288 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2289 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2290 for i in range(512):
2291 t = madtuple(range(i))
2292 u = t.rev()
2293 v = u.rev()
2294 self.assertEqual(v, t)
2295 a = madtuple((1,2,3,4,5))
2296 self.assertEqual(tuple(a), (1,2,3,4,5))
2297 self.assert_(tuple(a).__class__ is tuple)
2298 self.assertEqual(hash(a), hash((1,2,3,4,5)))
2299 self.assert_(a[:].__class__ is tuple)
2300 self.assert_((a * 1).__class__ is tuple)
2301 self.assert_((a * 0).__class__ is tuple)
2302 self.assert_((a + ()).__class__ is tuple)
2303 a = madtuple(())
2304 self.assertEqual(tuple(a), ())
2305 self.assert_(tuple(a).__class__ is tuple)
2306 self.assert_((a + a).__class__ is tuple)
2307 self.assert_((a * 0).__class__ is tuple)
2308 self.assert_((a * 1).__class__ is tuple)
2309 self.assert_((a * 2).__class__ is tuple)
2310 self.assert_(a[:].__class__ is tuple)
2311
2312 class madstring(str):
2313 _rev = None
2314 def rev(self):
2315 if self._rev is not None:
2316 return self._rev
2317 L = list(self)
2318 L.reverse()
2319 self._rev = self.__class__("".join(L))
2320 return self._rev
2321 s = madstring("abcdefghijklmnopqrstuvwxyz")
2322 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2323 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2324 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2325 for i in range(256):
2326 s = madstring("".join(map(chr, range(i))))
2327 t = s.rev()
2328 u = t.rev()
2329 self.assertEqual(u, s)
2330 s = madstring("12345")
2331 self.assertEqual(str(s), "12345")
2332 self.assert_(str(s).__class__ is str)
2333
2334 base = "\x00" * 5
2335 s = madstring(base)
2336 self.assertEqual(s, base)
2337 self.assertEqual(str(s), base)
2338 self.assert_(str(s).__class__ is str)
2339 self.assertEqual(hash(s), hash(base))
2340 self.assertEqual({s: 1}[base], 1)
2341 self.assertEqual({base: 1}[s], 1)
2342 self.assert_((s + "").__class__ is str)
2343 self.assertEqual(s + "", base)
2344 self.assert_(("" + s).__class__ is str)
2345 self.assertEqual("" + s, base)
2346 self.assert_((s * 0).__class__ is str)
2347 self.assertEqual(s * 0, "")
2348 self.assert_((s * 1).__class__ is str)
2349 self.assertEqual(s * 1, base)
2350 self.assert_((s * 2).__class__ is str)
2351 self.assertEqual(s * 2, base + base)
2352 self.assert_(s[:].__class__ is str)
2353 self.assertEqual(s[:], base)
2354 self.assert_(s[0:0].__class__ is str)
2355 self.assertEqual(s[0:0], "")
2356 self.assert_(s.strip().__class__ is str)
2357 self.assertEqual(s.strip(), base)
2358 self.assert_(s.lstrip().__class__ is str)
2359 self.assertEqual(s.lstrip(), base)
2360 self.assert_(s.rstrip().__class__ is str)
2361 self.assertEqual(s.rstrip(), base)
2362 identitytab = {}
2363 self.assert_(s.translate(identitytab).__class__ is str)
2364 self.assertEqual(s.translate(identitytab), base)
2365 self.assert_(s.replace("x", "x").__class__ is str)
2366 self.assertEqual(s.replace("x", "x"), base)
2367 self.assert_(s.ljust(len(s)).__class__ is str)
2368 self.assertEqual(s.ljust(len(s)), base)
2369 self.assert_(s.rjust(len(s)).__class__ is str)
2370 self.assertEqual(s.rjust(len(s)), base)
2371 self.assert_(s.center(len(s)).__class__ is str)
2372 self.assertEqual(s.center(len(s)), base)
2373 self.assert_(s.lower().__class__ is str)
2374 self.assertEqual(s.lower(), base)
2375
2376 class madunicode(str):
2377 _rev = None
2378 def rev(self):
2379 if self._rev is not None:
2380 return self._rev
2381 L = list(self)
2382 L.reverse()
2383 self._rev = self.__class__("".join(L))
2384 return self._rev
2385 u = madunicode("ABCDEF")
2386 self.assertEqual(u, "ABCDEF")
2387 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2388 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2389 base = "12345"
2390 u = madunicode(base)
2391 self.assertEqual(str(u), base)
2392 self.assert_(str(u).__class__ is str)
2393 self.assertEqual(hash(u), hash(base))
2394 self.assertEqual({u: 1}[base], 1)
2395 self.assertEqual({base: 1}[u], 1)
2396 self.assert_(u.strip().__class__ is str)
2397 self.assertEqual(u.strip(), base)
2398 self.assert_(u.lstrip().__class__ is str)
2399 self.assertEqual(u.lstrip(), base)
2400 self.assert_(u.rstrip().__class__ is str)
2401 self.assertEqual(u.rstrip(), base)
2402 self.assert_(u.replace("x", "x").__class__ is str)
2403 self.assertEqual(u.replace("x", "x"), base)
2404 self.assert_(u.replace("xy", "xy").__class__ is str)
2405 self.assertEqual(u.replace("xy", "xy"), base)
2406 self.assert_(u.center(len(u)).__class__ is str)
2407 self.assertEqual(u.center(len(u)), base)
2408 self.assert_(u.ljust(len(u)).__class__ is str)
2409 self.assertEqual(u.ljust(len(u)), base)
2410 self.assert_(u.rjust(len(u)).__class__ is str)
2411 self.assertEqual(u.rjust(len(u)), base)
2412 self.assert_(u.lower().__class__ is str)
2413 self.assertEqual(u.lower(), base)
2414 self.assert_(u.upper().__class__ is str)
2415 self.assertEqual(u.upper(), base)
2416 self.assert_(u.capitalize().__class__ is str)
2417 self.assertEqual(u.capitalize(), base)
2418 self.assert_(u.title().__class__ is str)
2419 self.assertEqual(u.title(), base)
2420 self.assert_((u + "").__class__ is str)
2421 self.assertEqual(u + "", base)
2422 self.assert_(("" + u).__class__ is str)
2423 self.assertEqual("" + u, base)
2424 self.assert_((u * 0).__class__ is str)
2425 self.assertEqual(u * 0, "")
2426 self.assert_((u * 1).__class__ is str)
2427 self.assertEqual(u * 1, base)
2428 self.assert_((u * 2).__class__ is str)
2429 self.assertEqual(u * 2, base + base)
2430 self.assert_(u[:].__class__ is str)
2431 self.assertEqual(u[:], base)
2432 self.assert_(u[0:0].__class__ is str)
2433 self.assertEqual(u[0:0], "")
2434
2435 class sublist(list):
2436 pass
2437 a = sublist(range(5))
2438 self.assertEqual(a, list(range(5)))
2439 a.append("hello")
2440 self.assertEqual(a, list(range(5)) + ["hello"])
2441 a[5] = 5
2442 self.assertEqual(a, list(range(6)))
2443 a.extend(range(6, 20))
2444 self.assertEqual(a, list(range(20)))
2445 a[-5:] = []
2446 self.assertEqual(a, list(range(15)))
2447 del a[10:15]
2448 self.assertEqual(len(a), 10)
2449 self.assertEqual(a, list(range(10)))
2450 self.assertEqual(list(a), list(range(10)))
2451 self.assertEqual(a[0], 0)
2452 self.assertEqual(a[9], 9)
2453 self.assertEqual(a[-10], 0)
2454 self.assertEqual(a[-1], 9)
2455 self.assertEqual(a[:5], list(range(5)))
2456
2457 ## class CountedInput(file):
2458 ## """Counts lines read by self.readline().
2459 ##
2460 ## self.lineno is the 0-based ordinal of the last line read, up to
2461 ## a maximum of one greater than the number of lines in the file.
2462 ##
2463 ## self.ateof is true if and only if the final "" line has been read,
2464 ## at which point self.lineno stops incrementing, and further calls
2465 ## to readline() continue to return "".
2466 ## """
2467 ##
2468 ## lineno = 0
2469 ## ateof = 0
2470 ## def readline(self):
2471 ## if self.ateof:
2472 ## return ""
2473 ## s = file.readline(self)
2474 ## # Next line works too.
2475 ## # s = super(CountedInput, self).readline()
2476 ## self.lineno += 1
2477 ## if s == "":
2478 ## self.ateof = 1
2479 ## return s
2480 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002481 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002482 ## lines = ['a\n', 'b\n', 'c\n']
2483 ## try:
2484 ## f.writelines(lines)
2485 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002486 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002487 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2488 ## got = f.readline()
2489 ## self.assertEqual(expected, got)
2490 ## self.assertEqual(f.lineno, i)
2491 ## self.assertEqual(f.ateof, (i > len(lines)))
2492 ## f.close()
2493 ## finally:
2494 ## try:
2495 ## f.close()
2496 ## except:
2497 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002498 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002499
2500 def test_keywords(self):
2501 # Testing keyword args to basic type constructors ...
2502 self.assertEqual(int(x=1), 1)
2503 self.assertEqual(float(x=2), 2.0)
2504 self.assertEqual(int(x=3), 3)
2505 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2506 self.assertEqual(str(object=500), '500')
2507 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
2508 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2509 self.assertEqual(list(sequence=(0, 1, 2)), list(range(3)))
2510 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2511
2512 for constructor in (int, float, int, complex, str, str,
2513 tuple, list):
2514 try:
2515 constructor(bogus_keyword_arg=1)
2516 except TypeError:
2517 pass
2518 else:
2519 self.fail("expected TypeError from bogus keyword argument to %r"
2520 % constructor)
2521
2522 def test_str_subclass_as_dict_key(self):
2523 # Testing a str subclass used as dict key ..
2524
2525 class cistr(str):
2526 """Sublcass of str that computes __eq__ case-insensitively.
2527
2528 Also computes a hash code of the string in canonical form.
2529 """
2530
2531 def __init__(self, value):
2532 self.canonical = value.lower()
2533 self.hashcode = hash(self.canonical)
2534
2535 def __eq__(self, other):
2536 if not isinstance(other, cistr):
2537 other = cistr(other)
2538 return self.canonical == other.canonical
2539
2540 def __hash__(self):
2541 return self.hashcode
2542
2543 self.assertEqual(cistr('ABC'), 'abc')
2544 self.assertEqual('aBc', cistr('ABC'))
2545 self.assertEqual(str(cistr('ABC')), 'ABC')
2546
2547 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2548 self.assertEqual(d[cistr('one')], 1)
2549 self.assertEqual(d[cistr('tWo')], 2)
2550 self.assertEqual(d[cistr('THrEE')], 3)
2551 self.assert_(cistr('ONe') in d)
2552 self.assertEqual(d.get(cistr('thrEE')), 3)
2553
2554 def test_classic_comparisons(self):
2555 # Testing classic comparisons...
2556 class classic:
2557 pass
2558
2559 for base in (classic, int, object):
2560 class C(base):
2561 def __init__(self, value):
2562 self.value = int(value)
2563 def __eq__(self, other):
2564 if isinstance(other, C):
2565 return self.value == other.value
2566 if isinstance(other, int) or isinstance(other, int):
2567 return self.value == other
2568 return NotImplemented
2569 def __ne__(self, other):
2570 if isinstance(other, C):
2571 return self.value != other.value
2572 if isinstance(other, int) or isinstance(other, int):
2573 return self.value != other
2574 return NotImplemented
2575 def __lt__(self, other):
2576 if isinstance(other, C):
2577 return self.value < other.value
2578 if isinstance(other, int) or isinstance(other, int):
2579 return self.value < other
2580 return NotImplemented
2581 def __le__(self, other):
2582 if isinstance(other, C):
2583 return self.value <= other.value
2584 if isinstance(other, int) or isinstance(other, int):
2585 return self.value <= other
2586 return NotImplemented
2587 def __gt__(self, other):
2588 if isinstance(other, C):
2589 return self.value > other.value
2590 if isinstance(other, int) or isinstance(other, int):
2591 return self.value > other
2592 return NotImplemented
2593 def __ge__(self, other):
2594 if isinstance(other, C):
2595 return self.value >= other.value
2596 if isinstance(other, int) or isinstance(other, int):
2597 return self.value >= other
2598 return NotImplemented
2599
2600 c1 = C(1)
2601 c2 = C(2)
2602 c3 = C(3)
2603 self.assertEqual(c1, 1)
2604 c = {1: c1, 2: c2, 3: c3}
2605 for x in 1, 2, 3:
2606 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00002607 for op in "<", "<=", "==", "!=", ">", ">=":
Mark Dickinsona56c4672009-01-27 18:17:45 +00002608 self.assert_(eval("c[x] %s c[y]" % op) ==
2609 eval("x %s y" % op),
2610 "x=%d, y=%d" % (x, y))
2611 self.assert_(eval("c[x] %s y" % op) ==
2612 eval("x %s y" % op),
2613 "x=%d, y=%d" % (x, y))
2614 self.assert_(eval("x %s c[y]" % op) ==
2615 eval("x %s y" % op),
2616 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002617
2618 def test_rich_comparisons(self):
2619 # Testing rich comparisons...
2620 class Z(complex):
2621 pass
2622 z = Z(1)
2623 self.assertEqual(z, 1+0j)
2624 self.assertEqual(1+0j, z)
2625 class ZZ(complex):
2626 def __eq__(self, other):
2627 try:
2628 return abs(self - other) <= 1e-6
2629 except:
2630 return NotImplemented
2631 zz = ZZ(1.0000003)
2632 self.assertEqual(zz, 1+0j)
2633 self.assertEqual(1+0j, zz)
2634
2635 class classic:
2636 pass
2637 for base in (classic, int, object, list):
2638 class C(base):
2639 def __init__(self, value):
2640 self.value = int(value)
2641 def __cmp__(self_, other):
2642 self.fail("shouldn't call __cmp__")
2643 def __eq__(self, other):
2644 if isinstance(other, C):
2645 return self.value == other.value
2646 if isinstance(other, int) or isinstance(other, int):
2647 return self.value == other
2648 return NotImplemented
2649 def __ne__(self, other):
2650 if isinstance(other, C):
2651 return self.value != other.value
2652 if isinstance(other, int) or isinstance(other, int):
2653 return self.value != other
2654 return NotImplemented
2655 def __lt__(self, other):
2656 if isinstance(other, C):
2657 return self.value < other.value
2658 if isinstance(other, int) or isinstance(other, int):
2659 return self.value < other
2660 return NotImplemented
2661 def __le__(self, other):
2662 if isinstance(other, C):
2663 return self.value <= other.value
2664 if isinstance(other, int) or isinstance(other, int):
2665 return self.value <= other
2666 return NotImplemented
2667 def __gt__(self, other):
2668 if isinstance(other, C):
2669 return self.value > other.value
2670 if isinstance(other, int) or isinstance(other, int):
2671 return self.value > other
2672 return NotImplemented
2673 def __ge__(self, other):
2674 if isinstance(other, C):
2675 return self.value >= other.value
2676 if isinstance(other, int) or isinstance(other, int):
2677 return self.value >= other
2678 return NotImplemented
2679 c1 = C(1)
2680 c2 = C(2)
2681 c3 = C(3)
2682 self.assertEqual(c1, 1)
2683 c = {1: c1, 2: c2, 3: c3}
2684 for x in 1, 2, 3:
2685 for y in 1, 2, 3:
2686 for op in "<", "<=", "==", "!=", ">", ">=":
2687 self.assert_(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2688 "x=%d, y=%d" % (x, y))
2689 self.assert_(eval("c[x] %s y" % op) == eval("x %s y" % op),
2690 "x=%d, y=%d" % (x, y))
2691 self.assert_(eval("x %s c[y]" % op) == eval("x %s y" % op),
2692 "x=%d, y=%d" % (x, y))
2693
2694 def test_descrdoc(self):
2695 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002696 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00002697 def check(descr, what):
2698 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002699 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00002700 check(complex.real, "the real part of a complex number") # member descriptor
2701
2702 def test_doc_descriptor(self):
2703 # Testing __doc__ descriptor...
2704 # SF bug 542984
2705 class DocDescr(object):
2706 def __get__(self, object, otype):
2707 if object:
2708 object = object.__class__.__name__ + ' instance'
2709 if otype:
2710 otype = otype.__name__
2711 return 'object=%s; type=%s' % (object, otype)
2712 class OldClass:
2713 __doc__ = DocDescr()
2714 class NewClass(object):
2715 __doc__ = DocDescr()
2716 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
2717 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
2718 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
2719 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
2720
2721 def test_set_class(self):
2722 # Testing __class__ assignment...
2723 class C(object): pass
2724 class D(object): pass
2725 class E(object): pass
2726 class F(D, E): pass
2727 for cls in C, D, E, F:
2728 for cls2 in C, D, E, F:
2729 x = cls()
2730 x.__class__ = cls2
2731 self.assert_(x.__class__ is cls2)
2732 x.__class__ = cls
2733 self.assert_(x.__class__ is cls)
2734 def cant(x, C):
2735 try:
2736 x.__class__ = C
2737 except TypeError:
2738 pass
2739 else:
2740 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
2741 try:
2742 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00002743 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00002744 pass
2745 else:
2746 self.fail("shouldn't allow del %r.__class__" % x)
2747 cant(C(), list)
2748 cant(list(), C)
2749 cant(C(), 1)
2750 cant(C(), object)
2751 cant(object(), list)
2752 cant(list(), object)
2753 class Int(int): __slots__ = []
2754 cant(2, Int)
2755 cant(Int(), int)
2756 cant(True, int)
2757 cant(2, bool)
2758 o = object()
2759 cant(o, type(1))
2760 cant(o, type(None))
2761 del o
2762 class G(object):
2763 __slots__ = ["a", "b"]
2764 class H(object):
2765 __slots__ = ["b", "a"]
2766 class I(object):
2767 __slots__ = ["a", "b"]
2768 class J(object):
2769 __slots__ = ["c", "b"]
2770 class K(object):
2771 __slots__ = ["a", "b", "d"]
2772 class L(H):
2773 __slots__ = ["e"]
2774 class M(I):
2775 __slots__ = ["e"]
2776 class N(J):
2777 __slots__ = ["__weakref__"]
2778 class P(J):
2779 __slots__ = ["__dict__"]
2780 class Q(J):
2781 pass
2782 class R(J):
2783 __slots__ = ["__dict__", "__weakref__"]
2784
2785 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
2786 x = cls()
2787 x.a = 1
2788 x.__class__ = cls2
2789 self.assert_(x.__class__ is cls2,
2790 "assigning %r as __class__ for %r silently failed" % (cls2, x))
2791 self.assertEqual(x.a, 1)
2792 x.__class__ = cls
2793 self.assert_(x.__class__ is cls,
2794 "assigning %r as __class__ for %r silently failed" % (cls, x))
2795 self.assertEqual(x.a, 1)
2796 for cls in G, J, K, L, M, N, P, R, list, Int:
2797 for cls2 in G, J, K, L, M, N, P, R, list, Int:
2798 if cls is cls2:
2799 continue
2800 cant(cls(), cls2)
2801
Benjamin Peterson193152c2009-04-25 01:08:45 +00002802 # Issue5283: when __class__ changes in __del__, the wrong
2803 # type gets DECREF'd.
2804 class O(object):
2805 pass
2806 class A(object):
2807 def __del__(self):
2808 self.__class__ = O
2809 l = [A() for x in range(100)]
2810 del l
2811
Georg Brandl479a7e72008-02-05 18:13:15 +00002812 def test_set_dict(self):
2813 # Testing __dict__ assignment...
2814 class C(object): pass
2815 a = C()
2816 a.__dict__ = {'b': 1}
2817 self.assertEqual(a.b, 1)
2818 def cant(x, dict):
2819 try:
2820 x.__dict__ = dict
2821 except (AttributeError, TypeError):
2822 pass
2823 else:
2824 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
2825 cant(a, None)
2826 cant(a, [])
2827 cant(a, 1)
2828 del a.__dict__ # Deleting __dict__ is allowed
2829
2830 class Base(object):
2831 pass
2832 def verify_dict_readonly(x):
2833 """
2834 x has to be an instance of a class inheriting from Base.
2835 """
2836 cant(x, {})
2837 try:
2838 del x.__dict__
2839 except (AttributeError, TypeError):
2840 pass
2841 else:
2842 self.fail("shouldn't allow del %r.__dict__" % x)
2843 dict_descr = Base.__dict__["__dict__"]
2844 try:
2845 dict_descr.__set__(x, {})
2846 except (AttributeError, TypeError):
2847 pass
2848 else:
2849 self.fail("dict_descr allowed access to %r's dict" % x)
2850
2851 # Classes don't allow __dict__ assignment and have readonly dicts
2852 class Meta1(type, Base):
2853 pass
2854 class Meta2(Base, type):
2855 pass
2856 class D(object, metaclass=Meta1):
2857 pass
2858 class E(object, metaclass=Meta2):
2859 pass
2860 for cls in C, D, E:
2861 verify_dict_readonly(cls)
2862 class_dict = cls.__dict__
2863 try:
2864 class_dict["spam"] = "eggs"
2865 except TypeError:
2866 pass
2867 else:
2868 self.fail("%r's __dict__ can be modified" % cls)
2869
2870 # Modules also disallow __dict__ assignment
2871 class Module1(types.ModuleType, Base):
2872 pass
2873 class Module2(Base, types.ModuleType):
2874 pass
2875 for ModuleType in Module1, Module2:
2876 mod = ModuleType("spam")
2877 verify_dict_readonly(mod)
2878 mod.__dict__["spam"] = "eggs"
2879
2880 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00002881 # (at least not any more than regular exception's __dict__ can
2882 # be deleted; on CPython it is not the case, whereas on PyPy they
2883 # can, just like any other new-style instance's __dict__.)
2884 def can_delete_dict(e):
2885 try:
2886 del e.__dict__
2887 except (TypeError, AttributeError):
2888 return False
2889 else:
2890 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00002891 class Exception1(Exception, Base):
2892 pass
2893 class Exception2(Base, Exception):
2894 pass
2895 for ExceptionType in Exception, Exception1, Exception2:
2896 e = ExceptionType()
2897 e.__dict__ = {"a": 1}
2898 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00002899 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00002900
2901 def test_pickles(self):
2902 # Testing pickling and copying new-style classes and objects...
2903 import pickle
2904
2905 def sorteditems(d):
2906 L = list(d.items())
2907 L.sort()
2908 return L
2909
2910 global C
2911 class C(object):
2912 def __init__(self, a, b):
2913 super(C, self).__init__()
2914 self.a = a
2915 self.b = b
2916 def __repr__(self):
2917 return "C(%r, %r)" % (self.a, self.b)
2918
2919 global C1
2920 class C1(list):
2921 def __new__(cls, a, b):
2922 return super(C1, cls).__new__(cls)
2923 def __getnewargs__(self):
2924 return (self.a, self.b)
2925 def __init__(self, a, b):
2926 self.a = a
2927 self.b = b
2928 def __repr__(self):
2929 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2930
2931 global C2
2932 class C2(int):
2933 def __new__(cls, a, b, val=0):
2934 return super(C2, cls).__new__(cls, val)
2935 def __getnewargs__(self):
2936 return (self.a, self.b, int(self))
2937 def __init__(self, a, b, val=0):
2938 self.a = a
2939 self.b = b
2940 def __repr__(self):
2941 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2942
2943 global C3
2944 class C3(object):
2945 def __init__(self, foo):
2946 self.foo = foo
2947 def __getstate__(self):
2948 return self.foo
2949 def __setstate__(self, foo):
2950 self.foo = foo
2951
2952 global C4classic, C4
2953 class C4classic: # classic
2954 pass
2955 class C4(C4classic, object): # mixed inheritance
2956 pass
2957
Guido van Rossum3926a632001-09-25 16:25:58 +00002958 for bin in 0, 1:
Guido van Rossum3926a632001-09-25 16:25:58 +00002959 for cls in C, C1, C2:
Georg Brandl479a7e72008-02-05 18:13:15 +00002960 s = pickle.dumps(cls, bin)
2961 cls2 = pickle.loads(s)
2962 self.assert_(cls2 is cls)
Guido van Rossum3926a632001-09-25 16:25:58 +00002963
2964 a = C1(1, 2); a.append(42); a.append(24)
2965 b = C2("hello", "world", 42)
Georg Brandl479a7e72008-02-05 18:13:15 +00002966 s = pickle.dumps((a, b), bin)
2967 x, y = pickle.loads(s)
2968 self.assertEqual(x.__class__, a.__class__)
2969 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
2970 self.assertEqual(y.__class__, b.__class__)
2971 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
2972 self.assertEqual(repr(x), repr(a))
2973 self.assertEqual(repr(y), repr(b))
Guido van Rossum90c45142001-11-24 21:07:01 +00002974 # Test for __getstate__ and __setstate__ on new style class
2975 u = C3(42)
Georg Brandl479a7e72008-02-05 18:13:15 +00002976 s = pickle.dumps(u, bin)
2977 v = pickle.loads(s)
2978 self.assertEqual(u.__class__, v.__class__)
2979 self.assertEqual(u.foo, v.foo)
Guido van Rossum90c45142001-11-24 21:07:01 +00002980 # Test for picklability of hybrid class
2981 u = C4()
2982 u.foo = 42
Georg Brandl479a7e72008-02-05 18:13:15 +00002983 s = pickle.dumps(u, bin)
2984 v = pickle.loads(s)
2985 self.assertEqual(u.__class__, v.__class__)
2986 self.assertEqual(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00002987
Georg Brandl479a7e72008-02-05 18:13:15 +00002988 # Testing copy.deepcopy()
2989 import copy
2990 for cls in C, C1, C2:
2991 cls2 = copy.deepcopy(cls)
2992 self.assert_(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00002993
Georg Brandl479a7e72008-02-05 18:13:15 +00002994 a = C1(1, 2); a.append(42); a.append(24)
2995 b = C2("hello", "world", 42)
2996 x, y = copy.deepcopy((a, b))
2997 self.assertEqual(x.__class__, a.__class__)
2998 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
2999 self.assertEqual(y.__class__, b.__class__)
3000 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3001 self.assertEqual(repr(x), repr(a))
3002 self.assertEqual(repr(y), repr(b))
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003003
Georg Brandl479a7e72008-02-05 18:13:15 +00003004 def test_pickle_slots(self):
3005 # Testing pickling of classes with __slots__ ...
3006 import pickle
3007 # Pickling of classes with __slots__ but without __getstate__ should fail
3008 # (if using protocol 0 or 1)
3009 global B, C, D, E
3010 class B(object):
Guido van Rossum8c842552002-03-14 23:05:54 +00003011 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003012 for base in [object, B]:
3013 class C(base):
3014 __slots__ = ['a']
3015 class D(C):
3016 pass
3017 try:
3018 pickle.dumps(C(), 0)
3019 except TypeError:
3020 pass
3021 else:
3022 self.fail("should fail: pickle C instance - %s" % base)
3023 try:
3024 pickle.dumps(C(), 0)
3025 except TypeError:
3026 pass
3027 else:
3028 self.fail("should fail: pickle D instance - %s" % base)
3029 # Give C a nice generic __getstate__ and __setstate__
3030 class C(base):
3031 __slots__ = ['a']
3032 def __getstate__(self):
3033 try:
3034 d = self.__dict__.copy()
3035 except AttributeError:
3036 d = {}
3037 for cls in self.__class__.__mro__:
3038 for sn in cls.__dict__.get('__slots__', ()):
3039 try:
3040 d[sn] = getattr(self, sn)
3041 except AttributeError:
3042 pass
3043 return d
3044 def __setstate__(self, d):
3045 for k, v in list(d.items()):
3046 setattr(self, k, v)
3047 class D(C):
3048 pass
3049 # Now it should work
3050 x = C()
3051 y = pickle.loads(pickle.dumps(x))
3052 self.assertEqual(hasattr(y, 'a'), 0)
3053 x.a = 42
3054 y = pickle.loads(pickle.dumps(x))
3055 self.assertEqual(y.a, 42)
3056 x = D()
3057 x.a = 42
3058 x.b = 100
3059 y = pickle.loads(pickle.dumps(x))
3060 self.assertEqual(y.a + y.b, 142)
3061 # A subclass that adds a slot should also work
3062 class E(C):
3063 __slots__ = ['b']
3064 x = E()
3065 x.a = 42
3066 x.b = "foo"
3067 y = pickle.loads(pickle.dumps(x))
3068 self.assertEqual(y.a, x.a)
3069 self.assertEqual(y.b, x.b)
3070
3071 def test_binary_operator_override(self):
3072 # Testing overrides of binary operations...
3073 class I(int):
3074 def __repr__(self):
3075 return "I(%r)" % int(self)
3076 def __add__(self, other):
3077 return I(int(self) + int(other))
3078 __radd__ = __add__
3079 def __pow__(self, other, mod=None):
3080 if mod is None:
3081 return I(pow(int(self), int(other)))
3082 else:
3083 return I(pow(int(self), int(other), int(mod)))
3084 def __rpow__(self, other, mod=None):
3085 if mod is None:
3086 return I(pow(int(other), int(self), mod))
3087 else:
3088 return I(pow(int(other), int(self), int(mod)))
3089
3090 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3091 self.assertEqual(repr(I(1) + 2), "I(3)")
3092 self.assertEqual(repr(1 + I(2)), "I(3)")
3093 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3094 self.assertEqual(repr(2 ** I(3)), "I(8)")
3095 self.assertEqual(repr(I(2) ** 3), "I(8)")
3096 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3097 class S(str):
3098 def __eq__(self, other):
3099 return self.lower() == other.lower()
3100
3101 def test_subclass_propagation(self):
3102 # Testing propagation of slot functions to subclasses...
3103 class A(object):
3104 pass
3105 class B(A):
3106 pass
3107 class C(A):
3108 pass
3109 class D(B, C):
3110 pass
3111 d = D()
3112 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3113 A.__hash__ = lambda self: 42
3114 self.assertEqual(hash(d), 42)
3115 C.__hash__ = lambda self: 314
3116 self.assertEqual(hash(d), 314)
3117 B.__hash__ = lambda self: 144
3118 self.assertEqual(hash(d), 144)
3119 D.__hash__ = lambda self: 100
3120 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003121 D.__hash__ = None
3122 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003123 del D.__hash__
3124 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003125 B.__hash__ = None
3126 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003127 del B.__hash__
3128 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003129 C.__hash__ = None
3130 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003131 del C.__hash__
3132 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003133 A.__hash__ = None
3134 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003135 del A.__hash__
3136 self.assertEqual(hash(d), orig_hash)
3137 d.foo = 42
3138 d.bar = 42
3139 self.assertEqual(d.foo, 42)
3140 self.assertEqual(d.bar, 42)
3141 def __getattribute__(self, name):
3142 if name == "foo":
3143 return 24
3144 return object.__getattribute__(self, name)
3145 A.__getattribute__ = __getattribute__
3146 self.assertEqual(d.foo, 24)
3147 self.assertEqual(d.bar, 42)
3148 def __getattr__(self, name):
3149 if name in ("spam", "foo", "bar"):
3150 return "hello"
3151 raise AttributeError(name)
3152 B.__getattr__ = __getattr__
3153 self.assertEqual(d.spam, "hello")
3154 self.assertEqual(d.foo, 24)
3155 self.assertEqual(d.bar, 42)
3156 del A.__getattribute__
3157 self.assertEqual(d.foo, 42)
3158 del d.foo
3159 self.assertEqual(d.foo, "hello")
3160 self.assertEqual(d.bar, 42)
3161 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003162 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003163 d.foo
3164 except AttributeError:
3165 pass
3166 else:
3167 self.fail("d.foo should be undefined now")
3168
3169 # Test a nasty bug in recurse_down_subclasses()
3170 import gc
3171 class A(object):
3172 pass
3173 class B(A):
3174 pass
3175 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003176 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003177 A.__setitem__ = lambda *a: None # crash
3178
3179 def test_buffer_inheritance(self):
3180 # Testing that buffer interface is inherited ...
3181
3182 import binascii
3183 # SF bug [#470040] ParseTuple t# vs subclasses.
3184
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003185 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003186 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003187 base = b'abc'
3188 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003189 # b2a_hex uses the buffer interface to get its argument's value, via
3190 # PyArg_ParseTuple 't#' code.
3191 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3192
Georg Brandl479a7e72008-02-05 18:13:15 +00003193 class MyInt(int):
3194 pass
3195 m = MyInt(42)
3196 try:
3197 binascii.b2a_hex(m)
3198 self.fail('subclass of int should not have a buffer interface')
3199 except TypeError:
3200 pass
3201
3202 def test_str_of_str_subclass(self):
3203 # Testing __str__ defined in subclass of str ...
3204 import binascii
3205 import io
3206
3207 class octetstring(str):
3208 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003209 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003210 def __repr__(self):
3211 return self + " repr"
3212
3213 o = octetstring('A')
3214 self.assertEqual(type(o), octetstring)
3215 self.assertEqual(type(str(o)), str)
3216 self.assertEqual(type(repr(o)), str)
3217 self.assertEqual(ord(o), 0x41)
3218 self.assertEqual(str(o), '41')
3219 self.assertEqual(repr(o), 'A repr')
3220 self.assertEqual(o.__str__(), '41')
3221 self.assertEqual(o.__repr__(), 'A repr')
3222
3223 capture = io.StringIO()
3224 # Calling str() or not exercises different internal paths.
3225 print(o, file=capture)
3226 print(str(o), file=capture)
3227 self.assertEqual(capture.getvalue(), '41\n41\n')
3228 capture.close()
3229
3230 def test_keyword_arguments(self):
3231 # Testing keyword arguments to __init__, __call__...
3232 def f(a): return a
3233 self.assertEqual(f.__call__(a=42), 42)
3234 a = []
3235 list.__init__(a, sequence=[0, 1, 2])
3236 self.assertEqual(a, [0, 1, 2])
3237
3238 def test_recursive_call(self):
3239 # Testing recursive __call__() by setting to instance of class...
3240 class A(object):
3241 pass
3242
3243 A.__call__ = A()
3244 try:
3245 A()()
3246 except RuntimeError:
3247 pass
3248 else:
3249 self.fail("Recursion limit should have been reached for __call__()")
3250
3251 def test_delete_hook(self):
3252 # Testing __del__ hook...
3253 log = []
3254 class C(object):
3255 def __del__(self):
3256 log.append(1)
3257 c = C()
3258 self.assertEqual(log, [])
3259 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003260 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003261 self.assertEqual(log, [1])
3262
3263 class D(object): pass
3264 d = D()
3265 try: del d[0]
3266 except TypeError: pass
3267 else: self.fail("invalid del() didn't raise TypeError")
3268
3269 def test_hash_inheritance(self):
3270 # Testing hash of mutable subclasses...
3271
3272 class mydict(dict):
3273 pass
3274 d = mydict()
3275 try:
3276 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003277 except TypeError:
3278 pass
3279 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003280 self.fail("hash() of dict subclass should fail")
3281
3282 class mylist(list):
3283 pass
3284 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003285 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003286 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003287 except TypeError:
3288 pass
3289 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003290 self.fail("hash() of list subclass should fail")
3291
3292 def test_str_operations(self):
3293 try: 'a' + 5
3294 except TypeError: pass
3295 else: self.fail("'' + 5 doesn't raise TypeError")
3296
3297 try: ''.split('')
3298 except ValueError: pass
3299 else: self.fail("''.split('') doesn't raise ValueError")
3300
3301 try: ''.join([0])
3302 except TypeError: pass
3303 else: self.fail("''.join([0]) doesn't raise TypeError")
3304
3305 try: ''.rindex('5')
3306 except ValueError: pass
3307 else: self.fail("''.rindex('5') doesn't raise ValueError")
3308
3309 try: '%(n)s' % None
3310 except TypeError: pass
3311 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3312
3313 try: '%(n' % {}
3314 except ValueError: pass
3315 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3316
3317 try: '%*s' % ('abc')
3318 except TypeError: pass
3319 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3320
3321 try: '%*.*s' % ('abc', 5)
3322 except TypeError: pass
3323 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3324
3325 try: '%s' % (1, 2)
3326 except TypeError: pass
3327 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3328
3329 try: '%' % None
3330 except ValueError: pass
3331 else: self.fail("'%' % None doesn't raise ValueError")
3332
3333 self.assertEqual('534253'.isdigit(), 1)
3334 self.assertEqual('534253x'.isdigit(), 0)
3335 self.assertEqual('%c' % 5, '\x05')
3336 self.assertEqual('%c' % '5', '5')
3337
3338 def test_deepcopy_recursive(self):
3339 # Testing deepcopy of recursive objects...
3340 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003341 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003342 a = Node()
3343 b = Node()
3344 a.b = b
3345 b.a = a
3346 z = deepcopy(a) # This blew up before
3347
3348 def test_unintialized_modules(self):
3349 # Testing uninitialized module objects...
3350 from types import ModuleType as M
3351 m = M.__new__(M)
3352 str(m)
3353 self.assertEqual(hasattr(m, "__name__"), 0)
3354 self.assertEqual(hasattr(m, "__file__"), 0)
3355 self.assertEqual(hasattr(m, "foo"), 0)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003356 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003357 m.foo = 1
3358 self.assertEqual(m.__dict__, {"foo": 1})
3359
3360 def test_funny_new(self):
3361 # Testing __new__ returning something unexpected...
3362 class C(object):
3363 def __new__(cls, arg):
3364 if isinstance(arg, str): return [1, 2, 3]
3365 elif isinstance(arg, int): return object.__new__(D)
3366 else: return object.__new__(cls)
3367 class D(C):
3368 def __init__(self, arg):
3369 self.foo = arg
3370 self.assertEqual(C("1"), [1, 2, 3])
3371 self.assertEqual(D("1"), [1, 2, 3])
3372 d = D(None)
3373 self.assertEqual(d.foo, None)
3374 d = C(1)
3375 self.assertEqual(isinstance(d, D), True)
3376 self.assertEqual(d.foo, 1)
3377 d = D(1)
3378 self.assertEqual(isinstance(d, D), True)
3379 self.assertEqual(d.foo, 1)
3380
3381 def test_imul_bug(self):
3382 # Testing for __imul__ problems...
3383 # SF bug 544647
3384 class C(object):
3385 def __imul__(self, other):
3386 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003387 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003388 y = x
3389 y *= 1.0
3390 self.assertEqual(y, (x, 1.0))
3391 y = x
3392 y *= 2
3393 self.assertEqual(y, (x, 2))
3394 y = x
3395 y *= 3
3396 self.assertEqual(y, (x, 3))
3397 y = x
3398 y *= 1<<100
3399 self.assertEqual(y, (x, 1<<100))
3400 y = x
3401 y *= None
3402 self.assertEqual(y, (x, None))
3403 y = x
3404 y *= "foo"
3405 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003406
Georg Brandl479a7e72008-02-05 18:13:15 +00003407 def test_copy_setstate(self):
3408 # Testing that copy.*copy() correctly uses __setstate__...
3409 import copy
3410 class C(object):
3411 def __init__(self, foo=None):
3412 self.foo = foo
3413 self.__foo = foo
3414 def setfoo(self, foo=None):
3415 self.foo = foo
3416 def getfoo(self):
3417 return self.__foo
3418 def __getstate__(self):
3419 return [self.foo]
3420 def __setstate__(self_, lst):
3421 self.assertEqual(len(lst), 1)
3422 self_.__foo = self_.foo = lst[0]
3423 a = C(42)
3424 a.setfoo(24)
3425 self.assertEqual(a.foo, 24)
3426 self.assertEqual(a.getfoo(), 42)
3427 b = copy.copy(a)
3428 self.assertEqual(b.foo, 24)
3429 self.assertEqual(b.getfoo(), 24)
3430 b = copy.deepcopy(a)
3431 self.assertEqual(b.foo, 24)
3432 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003433
Georg Brandl479a7e72008-02-05 18:13:15 +00003434 def test_slices(self):
3435 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003436
Georg Brandl479a7e72008-02-05 18:13:15 +00003437 # Strings
3438 self.assertEqual("hello"[:4], "hell")
3439 self.assertEqual("hello"[slice(4)], "hell")
3440 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3441 class S(str):
3442 def __getitem__(self, x):
3443 return str.__getitem__(self, x)
3444 self.assertEqual(S("hello")[:4], "hell")
3445 self.assertEqual(S("hello")[slice(4)], "hell")
3446 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3447 # Tuples
3448 self.assertEqual((1,2,3)[:2], (1,2))
3449 self.assertEqual((1,2,3)[slice(2)], (1,2))
3450 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3451 class T(tuple):
3452 def __getitem__(self, x):
3453 return tuple.__getitem__(self, x)
3454 self.assertEqual(T((1,2,3))[:2], (1,2))
3455 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3456 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3457 # Lists
3458 self.assertEqual([1,2,3][:2], [1,2])
3459 self.assertEqual([1,2,3][slice(2)], [1,2])
3460 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3461 class L(list):
3462 def __getitem__(self, x):
3463 return list.__getitem__(self, x)
3464 self.assertEqual(L([1,2,3])[:2], [1,2])
3465 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3466 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3467 # Now do lists and __setitem__
3468 a = L([1,2,3])
3469 a[slice(1, 3)] = [3,2]
3470 self.assertEqual(a, [1,3,2])
3471 a[slice(0, 2, 1)] = [3,1]
3472 self.assertEqual(a, [3,1,2])
3473 a.__setitem__(slice(1, 3), [2,1])
3474 self.assertEqual(a, [3,2,1])
3475 a.__setitem__(slice(0, 2, 1), [2,3])
3476 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003477
Georg Brandl479a7e72008-02-05 18:13:15 +00003478 def test_subtype_resurrection(self):
3479 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003480
Georg Brandl479a7e72008-02-05 18:13:15 +00003481 class C(object):
3482 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003483
Georg Brandl479a7e72008-02-05 18:13:15 +00003484 def __del__(self):
3485 # resurrect the instance
3486 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003487
Georg Brandl479a7e72008-02-05 18:13:15 +00003488 c = C()
3489 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003490
Benjamin Petersone549ead2009-03-28 21:42:05 +00003491 # The most interesting thing here is whether this blows up, due to
3492 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3493 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003494 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003495
Georg Brandl479a7e72008-02-05 18:13:15 +00003496 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Petersone549ead2009-03-28 21:42:05 +00003497 # the last container slot works: that will attempt to delete c again,
3498 # which will cause c to get appended back to the container again
3499 # "during" the del. (On non-CPython implementations, however, __del__
3500 # is typically not called again.)
3501 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003502 self.assertEqual(len(C.container), 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003503 del C.container[-1]
3504 if support.check_impl_detail():
3505 support.gc_collect()
3506 self.assertEqual(len(C.container), 1)
3507 self.assertEqual(C.container[-1].attr, 42)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003508
Georg Brandl479a7e72008-02-05 18:13:15 +00003509 # Make c mortal again, so that the test framework with -l doesn't report
3510 # it as a leak.
3511 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003512
Georg Brandl479a7e72008-02-05 18:13:15 +00003513 def test_slots_trash(self):
3514 # Testing slot trash...
3515 # Deallocating deeply nested slotted trash caused stack overflows
3516 class trash(object):
3517 __slots__ = ['x']
3518 def __init__(self, x):
3519 self.x = x
3520 o = None
3521 for i in range(50000):
3522 o = trash(o)
3523 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003524
Georg Brandl479a7e72008-02-05 18:13:15 +00003525 def test_slots_multiple_inheritance(self):
3526 # SF bug 575229, multiple inheritance w/ slots dumps core
3527 class A(object):
3528 __slots__=()
3529 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003530 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003531 class C(A,B) :
3532 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003533 if support.check_impl_detail():
3534 self.assertEqual(C.__basicsize__, B.__basicsize__)
Georg Brandl479a7e72008-02-05 18:13:15 +00003535 self.assert_(hasattr(C, '__dict__'))
3536 self.assert_(hasattr(C, '__weakref__'))
3537 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003538
Georg Brandl479a7e72008-02-05 18:13:15 +00003539 def test_rmul(self):
3540 # Testing correct invocation of __rmul__...
3541 # SF patch 592646
3542 class C(object):
3543 def __mul__(self, other):
3544 return "mul"
3545 def __rmul__(self, other):
3546 return "rmul"
3547 a = C()
3548 self.assertEqual(a*2, "mul")
3549 self.assertEqual(a*2.2, "mul")
3550 self.assertEqual(2*a, "rmul")
3551 self.assertEqual(2.2*a, "rmul")
3552
3553 def test_ipow(self):
3554 # Testing correct invocation of __ipow__...
3555 # [SF bug 620179]
3556 class C(object):
3557 def __ipow__(self, other):
3558 pass
3559 a = C()
3560 a **= 2
3561
3562 def test_mutable_bases(self):
3563 # Testing mutable bases...
3564
3565 # stuff that should work:
3566 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003567 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003568 class C2(object):
3569 def __getattribute__(self, attr):
3570 if attr == 'a':
3571 return 2
3572 else:
3573 return super(C2, self).__getattribute__(attr)
3574 def meth(self):
3575 return 1
3576 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003577 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003578 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003579 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003580 d = D()
3581 e = E()
3582 D.__bases__ = (C,)
3583 D.__bases__ = (C2,)
3584 self.assertEqual(d.meth(), 1)
3585 self.assertEqual(e.meth(), 1)
3586 self.assertEqual(d.a, 2)
3587 self.assertEqual(e.a, 2)
3588 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003589
Georg Brandl479a7e72008-02-05 18:13:15 +00003590 # stuff that shouldn't:
3591 class L(list):
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003592 pass
Guido van Rossum9fc8a292002-05-24 21:40:08 +00003593
Georg Brandl479a7e72008-02-05 18:13:15 +00003594 try:
3595 L.__bases__ = (dict,)
3596 except TypeError:
3597 pass
3598 else:
3599 self.fail("shouldn't turn list subclass into dict subclass")
Guido van Rossuma96b0df2002-06-18 16:49:45 +00003600
Georg Brandl479a7e72008-02-05 18:13:15 +00003601 try:
3602 list.__bases__ = (dict,)
3603 except TypeError:
3604 pass
3605 else:
3606 self.fail("shouldn't be able to assign to list.__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003607
Georg Brandl479a7e72008-02-05 18:13:15 +00003608 try:
3609 D.__bases__ = (C2, list)
3610 except TypeError:
3611 pass
3612 else:
3613 assert 0, "best_base calculation found wanting"
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003614
Georg Brandl479a7e72008-02-05 18:13:15 +00003615 try:
3616 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003617 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003618 pass
3619 else:
3620 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003621
Georg Brandl479a7e72008-02-05 18:13:15 +00003622 try:
3623 D.__bases__ = ()
3624 except TypeError as msg:
3625 if str(msg) == "a new-style class can't have only classic bases":
3626 self.fail("wrong error message for .__bases__ = ()")
3627 else:
3628 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003629
Georg Brandl479a7e72008-02-05 18:13:15 +00003630 try:
3631 D.__bases__ = (D,)
3632 except TypeError:
3633 pass
3634 else:
3635 # actually, we'll have crashed by here...
3636 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003637
Georg Brandl479a7e72008-02-05 18:13:15 +00003638 try:
3639 D.__bases__ = (C, C)
3640 except TypeError:
3641 pass
3642 else:
3643 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003644
Georg Brandl479a7e72008-02-05 18:13:15 +00003645 try:
3646 D.__bases__ = (E,)
3647 except TypeError:
3648 pass
3649 else:
3650 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003651
Benjamin Petersonae937c02009-04-18 20:54:08 +00003652 def test_builtin_bases(self):
3653 # Make sure all the builtin types can have their base queried without
3654 # segfaulting. See issue #5787.
3655 builtin_types = [tp for tp in builtins.__dict__.values()
3656 if isinstance(tp, type)]
3657 for tp in builtin_types:
3658 object.__getattribute__(tp, "__bases__")
3659 if tp is not object:
3660 self.assertEqual(len(tp.__bases__), 1, tp)
3661
3662
Georg Brandl479a7e72008-02-05 18:13:15 +00003663 def test_mutable_bases_with_failing_mro(self):
3664 # Testing mutable bases with failing mro...
3665 class WorkOnce(type):
3666 def __new__(self, name, bases, ns):
3667 self.flag = 0
3668 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3669 def mro(self):
3670 if self.flag > 0:
3671 raise RuntimeError("bozo")
3672 else:
3673 self.flag += 1
3674 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003675
Georg Brandl479a7e72008-02-05 18:13:15 +00003676 class WorkAlways(type):
3677 def mro(self):
3678 # this is here to make sure that .mro()s aren't called
3679 # with an exception set (which was possible at one point).
3680 # An error message will be printed in a debug build.
3681 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003682 return type.mro(self)
3683
Georg Brandl479a7e72008-02-05 18:13:15 +00003684 class C(object):
3685 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003686
Georg Brandl479a7e72008-02-05 18:13:15 +00003687 class C2(object):
3688 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003689
Georg Brandl479a7e72008-02-05 18:13:15 +00003690 class D(C):
3691 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003692
Georg Brandl479a7e72008-02-05 18:13:15 +00003693 class E(D):
3694 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003695
Georg Brandl479a7e72008-02-05 18:13:15 +00003696 class F(D, metaclass=WorkOnce):
3697 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003698
Georg Brandl479a7e72008-02-05 18:13:15 +00003699 class G(D, metaclass=WorkAlways):
3700 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003701
Georg Brandl479a7e72008-02-05 18:13:15 +00003702 # Immediate subclasses have their mro's adjusted in alphabetical
3703 # order, so E's will get adjusted before adjusting F's fails. We
3704 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003705
Georg Brandl479a7e72008-02-05 18:13:15 +00003706 E_mro_before = E.__mro__
3707 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00003708
Armin Rigofd163f92005-12-29 15:59:19 +00003709 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003710 D.__bases__ = (C2,)
3711 except RuntimeError:
3712 self.assertEqual(E.__mro__, E_mro_before)
3713 self.assertEqual(D.__mro__, D_mro_before)
3714 else:
3715 self.fail("exception not propagated")
3716
3717 def test_mutable_bases_catch_mro_conflict(self):
3718 # Testing mutable bases catch mro conflict...
3719 class A(object):
3720 pass
3721
3722 class B(object):
3723 pass
3724
3725 class C(A, B):
3726 pass
3727
3728 class D(A, B):
3729 pass
3730
3731 class E(C, D):
3732 pass
3733
3734 try:
3735 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00003736 except TypeError:
3737 pass
3738 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003739 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00003740
Georg Brandl479a7e72008-02-05 18:13:15 +00003741 def test_mutable_names(self):
3742 # Testing mutable names...
3743 class C(object):
3744 pass
3745
3746 # C.__module__ could be 'test_descr' or '__main__'
3747 mod = C.__module__
3748
3749 C.__name__ = 'D'
3750 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
3751
3752 C.__name__ = 'D.E'
3753 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
3754
3755 def test_subclass_right_op(self):
3756 # Testing correct dispatch of subclass overloading __r<op>__...
3757
3758 # This code tests various cases where right-dispatch of a subclass
3759 # should be preferred over left-dispatch of a base class.
3760
3761 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3762
3763 class B(int):
3764 def __floordiv__(self, other):
3765 return "B.__floordiv__"
3766 def __rfloordiv__(self, other):
3767 return "B.__rfloordiv__"
3768
3769 self.assertEqual(B(1) // 1, "B.__floordiv__")
3770 self.assertEqual(1 // B(1), "B.__rfloordiv__")
3771
3772 # Case 2: subclass of object; this is just the baseline for case 3
3773
3774 class C(object):
3775 def __floordiv__(self, other):
3776 return "C.__floordiv__"
3777 def __rfloordiv__(self, other):
3778 return "C.__rfloordiv__"
3779
3780 self.assertEqual(C() // 1, "C.__floordiv__")
3781 self.assertEqual(1 // C(), "C.__rfloordiv__")
3782
3783 # Case 3: subclass of new-style class; here it gets interesting
3784
3785 class D(C):
3786 def __floordiv__(self, other):
3787 return "D.__floordiv__"
3788 def __rfloordiv__(self, other):
3789 return "D.__rfloordiv__"
3790
3791 self.assertEqual(D() // C(), "D.__floordiv__")
3792 self.assertEqual(C() // D(), "D.__rfloordiv__")
3793
3794 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3795
3796 class E(C):
3797 pass
3798
3799 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
3800
3801 self.assertEqual(E() // 1, "C.__floordiv__")
3802 self.assertEqual(1 // E(), "C.__rfloordiv__")
3803 self.assertEqual(E() // C(), "C.__floordiv__")
3804 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
3805
Benjamin Petersone549ead2009-03-28 21:42:05 +00003806 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00003807 def test_meth_class_get(self):
3808 # Testing __get__ method of METH_CLASS C methods...
3809 # Full coverage of descrobject.c::classmethod_get()
3810
3811 # Baseline
3812 arg = [1, 2, 3]
3813 res = {1: None, 2: None, 3: None}
3814 self.assertEqual(dict.fromkeys(arg), res)
3815 self.assertEqual({}.fromkeys(arg), res)
3816
3817 # Now get the descriptor
3818 descr = dict.__dict__["fromkeys"]
3819
3820 # More baseline using the descriptor directly
3821 self.assertEqual(descr.__get__(None, dict)(arg), res)
3822 self.assertEqual(descr.__get__({})(arg), res)
3823
3824 # Now check various error cases
3825 try:
3826 descr.__get__(None, None)
3827 except TypeError:
3828 pass
3829 else:
3830 self.fail("shouldn't have allowed descr.__get__(None, None)")
3831 try:
3832 descr.__get__(42)
3833 except TypeError:
3834 pass
3835 else:
3836 self.fail("shouldn't have allowed descr.__get__(42)")
3837 try:
3838 descr.__get__(None, 42)
3839 except TypeError:
3840 pass
3841 else:
3842 self.fail("shouldn't have allowed descr.__get__(None, 42)")
3843 try:
3844 descr.__get__(None, int)
3845 except TypeError:
3846 pass
3847 else:
3848 self.fail("shouldn't have allowed descr.__get__(None, int)")
3849
3850 def test_isinst_isclass(self):
3851 # Testing proxy isinstance() and isclass()...
3852 class Proxy(object):
3853 def __init__(self, obj):
3854 self.__obj = obj
3855 def __getattribute__(self, name):
3856 if name.startswith("_Proxy__"):
3857 return object.__getattribute__(self, name)
3858 else:
3859 return getattr(self.__obj, name)
3860 # Test with a classic class
3861 class C:
3862 pass
3863 a = C()
3864 pa = Proxy(a)
3865 self.assert_(isinstance(a, C)) # Baseline
3866 self.assert_(isinstance(pa, C)) # Test
3867 # Test with a classic subclass
3868 class D(C):
3869 pass
3870 a = D()
3871 pa = Proxy(a)
3872 self.assert_(isinstance(a, C)) # Baseline
3873 self.assert_(isinstance(pa, C)) # Test
3874 # Test with a new-style class
3875 class C(object):
3876 pass
3877 a = C()
3878 pa = Proxy(a)
3879 self.assert_(isinstance(a, C)) # Baseline
3880 self.assert_(isinstance(pa, C)) # Test
3881 # Test with a new-style subclass
3882 class D(C):
3883 pass
3884 a = D()
3885 pa = Proxy(a)
3886 self.assert_(isinstance(a, C)) # Baseline
3887 self.assert_(isinstance(pa, C)) # Test
3888
3889 def test_proxy_super(self):
3890 # Testing super() for a proxy object...
3891 class Proxy(object):
3892 def __init__(self, obj):
3893 self.__obj = obj
3894 def __getattribute__(self, name):
3895 if name.startswith("_Proxy__"):
3896 return object.__getattribute__(self, name)
3897 else:
3898 return getattr(self.__obj, name)
3899
3900 class B(object):
3901 def f(self):
3902 return "B.f"
3903
3904 class C(B):
3905 def f(self):
3906 return super(C, self).f() + "->C.f"
3907
3908 obj = C()
3909 p = Proxy(obj)
3910 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
3911
3912 def test_carloverre(self):
3913 # Testing prohibition of Carlo Verre's hack...
3914 try:
3915 object.__setattr__(str, "foo", 42)
3916 except TypeError:
3917 pass
3918 else:
3919 self.fail("Carlo Verre __setattr__ suceeded!")
3920 try:
3921 object.__delattr__(str, "lower")
3922 except TypeError:
3923 pass
3924 else:
3925 self.fail("Carlo Verre __delattr__ succeeded!")
3926
3927 def test_weakref_segfault(self):
3928 # Testing weakref segfault...
3929 # SF 742911
3930 import weakref
3931
3932 class Provoker:
3933 def __init__(self, referrent):
3934 self.ref = weakref.ref(referrent)
3935
3936 def __del__(self):
3937 x = self.ref()
3938
3939 class Oops(object):
3940 pass
3941
3942 o = Oops()
3943 o.whatever = Provoker(o)
3944 del o
3945
3946 def test_wrapper_segfault(self):
3947 # SF 927248: deeply nested wrappers could cause stack overflow
3948 f = lambda:None
3949 for i in range(1000000):
3950 f = f.__call__
3951 f = None
3952
3953 def test_file_fault(self):
3954 # Testing sys.stdout is changed in getattr...
3955 import sys
3956 class StdoutGuard:
3957 def __getattr__(self, attr):
3958 sys.stdout = sys.__stdout__
3959 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
3960 sys.stdout = StdoutGuard()
3961 try:
3962 print("Oops!")
3963 except RuntimeError:
3964 pass
3965
3966 def test_vicious_descriptor_nonsense(self):
3967 # Testing vicious_descriptor_nonsense...
3968
3969 # A potential segfault spotted by Thomas Wouters in mail to
3970 # python-dev 2003-04-17, turned into an example & fixed by Michael
3971 # Hudson just less than four months later...
3972
3973 class Evil(object):
3974 def __hash__(self):
3975 return hash('attr')
3976 def __eq__(self, other):
3977 del C.attr
3978 return 0
3979
3980 class Descr(object):
3981 def __get__(self, ob, type=None):
3982 return 1
3983
3984 class C(object):
3985 attr = Descr()
3986
3987 c = C()
3988 c.__dict__[Evil()] = 0
3989
3990 self.assertEqual(c.attr, 1)
3991 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00003992 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003993 self.assertEqual(hasattr(c, 'attr'), False)
3994
3995 def test_init(self):
3996 # SF 1155938
3997 class Foo(object):
3998 def __init__(self):
3999 return 10
4000 try:
4001 Foo()
4002 except TypeError:
4003 pass
4004 else:
4005 self.fail("did not test __init__() for None return")
4006
4007 def test_method_wrapper(self):
4008 # Testing method-wrapper objects...
4009 # <type 'method-wrapper'> did not support any reflection before 2.5
4010
Mark Dickinson211c6252009-02-01 10:28:51 +00004011 # XXX should methods really support __eq__?
Georg Brandl479a7e72008-02-05 18:13:15 +00004012
4013 l = []
4014 self.assertEqual(l.__add__, l.__add__)
4015 self.assertEqual(l.__add__, [].__add__)
4016 self.assert_(l.__add__ != [5].__add__)
4017 self.assert_(l.__add__ != l.__mul__)
4018 self.assert_(l.__add__.__name__ == '__add__')
Benjamin Petersone549ead2009-03-28 21:42:05 +00004019 if hasattr(l.__add__, '__self__'):
4020 # CPython
4021 self.assert_(l.__add__.__self__ is l)
4022 self.assert_(l.__add__.__objclass__ is list)
4023 else:
4024 # Python implementations where [].__add__ is a normal bound method
4025 self.assert_(l.__add__.im_self is l)
4026 self.assert_(l.__add__.im_class is list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004027 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4028 try:
4029 hash(l.__add__)
4030 except TypeError:
4031 pass
4032 else:
4033 self.fail("no TypeError from hash([].__add__)")
4034
4035 t = ()
4036 t += (7,)
4037 self.assertEqual(t.__add__, (7,).__add__)
4038 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4039
4040 def test_not_implemented(self):
4041 # Testing NotImplemented...
4042 # all binary methods should be able to return a NotImplemented
4043 import sys
4044 import types
4045 import operator
4046
4047 def specialmethod(self, other):
4048 return NotImplemented
4049
4050 def check(expr, x, y):
4051 try:
4052 exec(expr, {'x': x, 'y': y, 'operator': operator})
4053 except TypeError:
4054 pass
4055 else:
4056 self.fail("no TypeError from %r" % (expr,))
4057
4058 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4059 # TypeErrors
4060 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4061 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004062 for name, expr, iexpr in [
4063 ('__add__', 'x + y', 'x += y'),
4064 ('__sub__', 'x - y', 'x -= y'),
4065 ('__mul__', 'x * y', 'x *= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004066 ('__truediv__', 'operator.truediv(x, y)', None),
4067 ('__floordiv__', 'operator.floordiv(x, y)', None),
4068 ('__div__', 'x / y', 'x /= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004069 ('__mod__', 'x % y', 'x %= y'),
4070 ('__divmod__', 'divmod(x, y)', None),
4071 ('__pow__', 'x ** y', 'x **= y'),
4072 ('__lshift__', 'x << y', 'x <<= y'),
4073 ('__rshift__', 'x >> y', 'x >>= y'),
4074 ('__and__', 'x & y', 'x &= y'),
4075 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004076 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004077 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004078 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004079 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004080 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004081 check(expr, a, N1)
4082 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004083 if iexpr:
4084 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004085 check(iexpr, a, N1)
4086 check(iexpr, a, N2)
4087 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004088 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004089 c = C()
4090 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004091 check(iexpr, c, N1)
4092 check(iexpr, c, N2)
4093
Georg Brandl479a7e72008-02-05 18:13:15 +00004094 def test_assign_slice(self):
4095 # ceval.c's assign_slice used to check for
4096 # tp->tp_as_sequence->sq_slice instead of
4097 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004098
Georg Brandl479a7e72008-02-05 18:13:15 +00004099 class C(object):
4100 def __setitem__(self, idx, value):
4101 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004102
Georg Brandl479a7e72008-02-05 18:13:15 +00004103 c = C()
4104 c[1:2] = 3
4105 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004106
Benjamin Peterson9262b842008-11-17 22:45:50 +00004107 def test_getattr_hooks(self):
4108 # issue 4230
4109
4110 class Descriptor(object):
4111 counter = 0
4112 def __get__(self, obj, objtype=None):
4113 def getter(name):
4114 self.counter += 1
4115 raise AttributeError(name)
4116 return getter
4117
4118 descr = Descriptor()
4119 class A(object):
4120 __getattribute__ = descr
4121 class B(object):
4122 __getattr__ = descr
4123 class C(object):
4124 __getattribute__ = descr
4125 __getattr__ = descr
4126
4127 self.assertRaises(AttributeError, getattr, A(), "attr")
4128 self.assertEquals(descr.counter, 1)
4129 self.assertRaises(AttributeError, getattr, B(), "attr")
4130 self.assertEquals(descr.counter, 2)
4131 self.assertRaises(AttributeError, getattr, C(), "attr")
4132 self.assertEquals(descr.counter, 4)
4133
4134 import gc
4135 class EvilGetattribute(object):
4136 # This used to segfault
4137 def __getattr__(self, name):
4138 raise AttributeError(name)
4139 def __getattribute__(self, name):
4140 del EvilGetattribute.__getattr__
4141 for i in range(5):
4142 gc.collect()
4143 raise AttributeError(name)
4144
4145 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4146
Christian Heimesbbffeb62008-01-24 09:42:52 +00004147
Georg Brandl479a7e72008-02-05 18:13:15 +00004148class DictProxyTests(unittest.TestCase):
4149 def setUp(self):
4150 class C(object):
4151 def meth(self):
4152 pass
4153 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004154
Georg Brandl479a7e72008-02-05 18:13:15 +00004155 def test_iter_keys(self):
4156 # Testing dict-proxy iterkeys...
4157 keys = [ key for key in self.C.__dict__.keys() ]
4158 keys.sort()
4159 self.assertEquals(keys, ['__dict__', '__doc__', '__module__',
4160 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004161
Georg Brandl479a7e72008-02-05 18:13:15 +00004162 def test_iter_values(self):
4163 # Testing dict-proxy itervalues...
4164 values = [ values for values in self.C.__dict__.values() ]
4165 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004166
Georg Brandl479a7e72008-02-05 18:13:15 +00004167 def test_iter_items(self):
4168 # Testing dict-proxy iteritems...
4169 keys = [ key for (key, value) in self.C.__dict__.items() ]
4170 keys.sort()
4171 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4172 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004173
Georg Brandl479a7e72008-02-05 18:13:15 +00004174 def test_dict_type_with_metaclass(self):
4175 # Testing type of __dict__ when metaclass set...
4176 class B(object):
4177 pass
4178 class M(type):
4179 pass
4180 class C(metaclass=M):
4181 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4182 pass
4183 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004184
Christian Heimesbbffeb62008-01-24 09:42:52 +00004185
Georg Brandl479a7e72008-02-05 18:13:15 +00004186class PTypesLongInitTest(unittest.TestCase):
4187 # This is in its own TestCase so that it can be run before any other tests.
4188 def test_pytype_long_ready(self):
4189 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004190
Georg Brandl479a7e72008-02-05 18:13:15 +00004191 # This dumps core when SF bug 551412 isn't fixed --
4192 # but only when test_descr.py is run separately.
4193 # (That can't be helped -- as soon as PyType_Ready()
4194 # is called for PyLong_Type, the bug is gone.)
4195 class UserLong(object):
4196 def __pow__(self, *args):
4197 pass
4198 try:
4199 pow(0, UserLong(), 0)
4200 except:
4201 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004202
Georg Brandl479a7e72008-02-05 18:13:15 +00004203 # Another segfault only when run early
4204 # (before PyType_Ready(tuple) is called)
4205 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004206
4207
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004208def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00004209 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004210 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Georg Brandl479a7e72008-02-05 18:13:15 +00004211 ClassPropertiesAndMethods, DictProxyTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004212
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004213if __name__ == "__main__":
4214 test_main()