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