Debian Codegraph @

Lib/test/test_descr.py

raw
1 import builtins
2 import copyreg
3 import gc
4 import itertools
5 import math
6 import pickle
7 import random
8 import string
9 import sys
10 import types
11 import unittest
12 import warnings
13 import weakref
14
15 from copy import deepcopy
16 from contextlib import redirect_stdout
17 from test import support
18 from test.support.testcase import ExtraAssertions
19
20 try:
21 import _testcapi
22 except ImportError:
23 _testcapi = None
24
25 try:
26 import xxsubtype
27 except ImportError:
28 xxsubtype = None
29
30
31 class OperatorsTest(unittest.TestCase):
32
33 def __init__(self, *args, **kwargs):
34 unittest.TestCase.__init__(self, *args, **kwargs)
35 self.binops = {
36 'add': '+',
37 'sub': '-',
38 'mul': '*',
39 'matmul': '@',
40 'truediv': '/',
41 'floordiv': '//',
42 'divmod': 'divmod',
43 'pow': '**',
44 'lshift': '<<',
45 'rshift': '>>',
46 'and': '&',
47 'xor': '^',
48 'or': '|',
49 'cmp': 'cmp',
50 'lt': '<',
51 'le': '<=',
52 'eq': '==',
53 'ne': '!=',
54 'gt': '>',
55 'ge': '>=',
56 }
57
58 for name, expr in list(self.binops.items()):
59 if expr.islower():
60 expr = expr + "(a, b)"
61 else:
62 expr = 'a %s b' % expr
63 self.binops[name] = expr
64
65 self.unops = {
66 'pos': '+',
67 'neg': '-',
68 'abs': 'abs',
69 'invert': '~',
70 'int': 'int',
71 'float': 'float',
72 }
73
74 for name, expr in list(self.unops.items()):
75 if expr.islower():
76 expr = expr + "(a)"
77 else:
78 expr = '%s a' % expr
79 self.unops[name] = expr
80
81 def unop_test(self, a, res, expr="len(a)", meth="__len__"):
82 d = {'a': a}
83 self.assertEqual(eval(expr, d), res)
84 t = type(a)
85 m = getattr(t, meth)
86
87 # Find method in parent class
88 while meth not in t.__dict__:
89 t = t.__bases__[0]
90 # 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])
93 self.assertEqual(m(a), res)
94 bm = getattr(a, meth)
95 self.assertEqual(bm(), res)
96
97 def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
98 d = {'a': a, 'b': b}
99
100 self.assertEqual(eval(expr, d), res)
101 t = type(a)
102 m = getattr(t, meth)
103 while meth not in t.__dict__:
104 t = t.__bases__[0]
105 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
106 # method object; the getattr() below obtains its underlying function.
107 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
108 self.assertEqual(m(a, b), res)
109 bm = getattr(a, meth)
110 self.assertEqual(bm(b), res)
111
112 def sliceop_test(self, a, b, c, res, expr="a[b:c]", meth="__getitem__"):
113 d = {'a': a, 'b': b, 'c': c}
114 self.assertEqual(eval(expr, d), res)
115 t = type(a)
116 m = getattr(t, meth)
117 while meth not in t.__dict__:
118 t = t.__bases__[0]
119 # 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])
122 self.assertEqual(m(a, slice(b, c)), res)
123 bm = getattr(a, meth)
124 self.assertEqual(bm(slice(b, c)), res)
125
126 def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
127 d = {'a': deepcopy(a), 'b': b}
128 exec(stmt, d)
129 self.assertEqual(d['a'], res)
130 t = type(a)
131 m = getattr(t, meth)
132 while meth not in t.__dict__:
133 t = t.__bases__[0]
134 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
135 # method object; the getattr() below obtains its underlying function.
136 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
137 d['a'] = deepcopy(a)
138 m(d['a'], b)
139 self.assertEqual(d['a'], res)
140 d['a'] = deepcopy(a)
141 bm = getattr(d['a'], meth)
142 bm(b)
143 self.assertEqual(d['a'], res)
144
145 def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
146 d = {'a': deepcopy(a), 'b': b, 'c': c}
147 exec(stmt, d)
148 self.assertEqual(d['a'], res)
149 t = type(a)
150 m = getattr(t, meth)
151 while meth not in t.__dict__:
152 t = t.__bases__[0]
153 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
154 # method object; the getattr() below obtains its underlying function.
155 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
156 d['a'] = deepcopy(a)
157 m(d['a'], b, c)
158 self.assertEqual(d['a'], res)
159 d['a'] = deepcopy(a)
160 bm = getattr(d['a'], meth)
161 bm(b, c)
162 self.assertEqual(d['a'], res)
163
164 def setsliceop_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setitem__"):
165 dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
166 exec(stmt, dictionary)
167 self.assertEqual(dictionary['a'], res)
168 t = type(a)
169 while meth not in t.__dict__:
170 t = t.__bases__[0]
171 m = getattr(t, meth)
172 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
173 # method object; the getattr() below obtains its underlying function.
174 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
175 dictionary['a'] = deepcopy(a)
176 m(dictionary['a'], slice(b, c), d)
177 self.assertEqual(dictionary['a'], res)
178 dictionary['a'] = deepcopy(a)
179 bm = getattr(dictionary['a'], meth)
180 bm(slice(b, c), d)
181 self.assertEqual(dictionary['a'], res)
182
183 def test_lists(self):
184 # Testing list operations...
185 # Asserts are within individual test methods
186 self.binop_test([1], [2], [1,2], "a+b", "__add__")
187 self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
188 self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
189 self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
190 self.sliceop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getitem__")
191 self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
192 self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
193 self.unop_test([1,2,3], 3, "len(a)", "__len__")
194 self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
195 self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
196 self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
197 self.setsliceop_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
198 "__setitem__")
199
200 def test_dicts(self):
201 # Testing dict operations...
202 self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
203 self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
204 self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
205
206 d = {1:2, 3:4}
207 l1 = []
208 for i in list(d.keys()):
209 l1.append(i)
210 l = []
211 for i in iter(d):
212 l.append(i)
213 self.assertEqual(l, l1)
214 l = []
215 for i in d.__iter__():
216 l.append(i)
217 self.assertEqual(l, l1)
218 l = []
219 for i in dict.__iter__(d):
220 l.append(i)
221 self.assertEqual(l, l1)
222 d = {1:2, 3:4}
223 self.unop_test(d, 2, "len(a)", "__len__")
224 self.assertEqual(eval(repr(d), {}), d)
225 self.assertEqual(eval(d.__repr__(), {}), d)
226 self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
227 "__setitem__")
228
229 # Tests for unary and binary operators
230 def number_operators(self, a, b, skip=[]):
231 dict = {'a': a, 'b': b}
232
233 for name, expr in self.binops.items():
234 if name not in skip:
235 name = "__%s__" % name
236 if hasattr(a, name):
237 res = eval(expr, dict)
238 self.binop_test(a, b, res, expr, name)
239
240 for name, expr in list(self.unops.items()):
241 if name not in skip:
242 name = "__%s__" % name
243 if hasattr(a, name):
244 res = eval(expr, dict)
245 self.unop_test(a, res, expr, name)
246
247 def test_ints(self):
248 # Testing int operations...
249 self.number_operators(100, 3)
250 # The following crashes in Python 2.2
251 self.assertEqual((1).__bool__(), 1)
252 self.assertEqual((0).__bool__(), 0)
253 # This returns 'NotImplemented' in Python 2.2
254 class C(int):
255 def __add__(self, other):
256 return NotImplemented
257 self.assertEqual(C(5), 5)
258 try:
259 C() + ""
260 except TypeError:
261 pass
262 else:
263 self.fail("NotImplemented should have caused TypeError")
264
265 def test_floats(self):
266 # Testing float operations...
267 self.number_operators(100.0, 3.0)
268
269 def test_complexes(self):
270 # Testing complex operations...
271 self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
272 'int', 'float',
273 'floordiv', 'divmod', 'mod'])
274
275 class Number(complex):
276 __slots__ = ['prec']
277 def __new__(cls, *args, **kwds):
278 result = complex.__new__(cls, *args)
279 result.prec = kwds.get('prec', 12)
280 return result
281 def __repr__(self):
282 prec = self.prec
283 if self.imag == 0.0:
284 return "%.*g" % (prec, self.real)
285 if self.real == 0.0:
286 return "%.*gj" % (prec, self.imag)
287 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
288 __str__ = __repr__
289
290 a = Number(3.14, prec=6)
291 self.assertEqual(repr(a), "3.14")
292 self.assertEqual(a.prec, 6)
293
294 a = Number(a, prec=2)
295 self.assertEqual(repr(a), "3.1")
296 self.assertEqual(a.prec, 2)
297
298 a = Number(234.5)
299 self.assertEqual(repr(a), "234.5")
300 self.assertEqual(a.prec, 12)
301
302 def test_explicit_reverse_methods(self):
303 # see issue 9930
304 self.assertEqual(complex.__radd__(3j, 4.0), complex(4.0, 3.0))
305 self.assertEqual(float.__rsub__(3.0, 1), -2.0)
306
307 @support.impl_detail("the module 'xxsubtype' is internal")
308 @unittest.skipIf(xxsubtype is None, "requires xxsubtype module")
309 def test_spam_lists(self):
310 # Testing spamlist operations...
311 import copy, xxsubtype as spam
312
313 def spamlist(l, memo=None):
314 import xxsubtype as spam
315 return spam.spamlist(l)
316
317 # This is an ugly hack:
318 copy._deepcopy_dispatch[spam.spamlist] = spamlist
319
320 self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
321 "__add__")
322 self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
323 self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
324 self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
325 self.sliceop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
326 "__getitem__")
327 self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
328 "__iadd__")
329 self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
330 "__imul__")
331 self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
332 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
333 "__mul__")
334 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
335 "__rmul__")
336 self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
337 "__setitem__")
338 self.setsliceop_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
339 spamlist([1,5,6,4]), "a[b:c]=d", "__setitem__")
340 # Test subclassing
341 class C(spam.spamlist):
342 def foo(self): return 1
343 a = C()
344 self.assertEqual(a, [])
345 self.assertEqual(a.foo(), 1)
346 a.append(100)
347 self.assertEqual(a, [100])
348 self.assertEqual(a.getstate(), 0)
349 a.setstate(42)
350 self.assertEqual(a.getstate(), 42)
351
352 @support.impl_detail("the module 'xxsubtype' is internal")
353 @unittest.skipIf(xxsubtype is None, "requires xxsubtype module")
354 def test_spam_dicts(self):
355 # Testing spamdict operations...
356 import copy, xxsubtype as spam
357 def spamdict(d, memo=None):
358 import xxsubtype as spam
359 sd = spam.spamdict()
360 for k, v in list(d.items()):
361 sd[k] = v
362 return sd
363 # This is an ugly hack:
364 copy._deepcopy_dispatch[spam.spamdict] = spamdict
365
366 self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
367 self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
368 self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
369 d = spamdict({1:2,3:4})
370 l1 = []
371 for i in list(d.keys()):
372 l1.append(i)
373 l = []
374 for i in iter(d):
375 l.append(i)
376 self.assertEqual(l, l1)
377 l = []
378 for i in d.__iter__():
379 l.append(i)
380 self.assertEqual(l, l1)
381 l = []
382 for i in type(spamdict({})).__iter__(d):
383 l.append(i)
384 self.assertEqual(l, l1)
385 straightd = {1:2, 3:4}
386 spamd = spamdict(straightd)
387 self.unop_test(spamd, 2, "len(a)", "__len__")
388 self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
389 self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
390 "a[b]=c", "__setitem__")
391 # Test subclassing
392 class C(spam.spamdict):
393 def foo(self): return 1
394 a = C()
395 self.assertEqual(list(a.items()), [])
396 self.assertEqual(a.foo(), 1)
397 a['foo'] = 'bar'
398 self.assertEqual(list(a.items()), [('foo', 'bar')])
399 self.assertEqual(a.getstate(), 0)
400 a.setstate(100)
401 self.assertEqual(a.getstate(), 100)
402
403 def test_wrap_lenfunc_bad_cast(self):
404 self.assertEqual(range(sys.maxsize).__len__(), sys.maxsize)
405
406
407 class ClassPropertiesAndMethods(unittest.TestCase, ExtraAssertions):
408
409 def test_python_dicts(self):
410 # Testing Python subclass of dict...
411 self.assertTrue(issubclass(dict, dict))
412 self.assertIsInstance({}, dict)
413 d = dict()
414 self.assertEqual(d, {})
415 self.assertIs(d.__class__, dict)
416 self.assertIsInstance(d, dict)
417 class C(dict):
418 state = -1
419 def __init__(self_local, *a, **kw):
420 if a:
421 self.assertEqual(len(a), 1)
422 self_local.state = a[0]
423 if kw:
424 for k, v in list(kw.items()):
425 self_local[v] = k
426 def __getitem__(self, key):
427 return self.get(key, 0)
428 def __setitem__(self_local, key, value):
429 self.assertIsInstance(key, int)
430 dict.__setitem__(self_local, key, value)
431 def setstate(self, state):
432 self.state = state
433 def getstate(self):
434 return self.state
435 self.assertTrue(issubclass(C, dict))
436 a1 = C(12)
437 self.assertEqual(a1.state, 12)
438 a2 = C(foo=1, bar=2)
439 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
440 a = C()
441 self.assertEqual(a.state, -1)
442 self.assertEqual(a.getstate(), -1)
443 a.setstate(0)
444 self.assertEqual(a.state, 0)
445 self.assertEqual(a.getstate(), 0)
446 a.setstate(10)
447 self.assertEqual(a.state, 10)
448 self.assertEqual(a.getstate(), 10)
449 self.assertEqual(a[42], 0)
450 a[42] = 24
451 self.assertEqual(a[42], 24)
452 N = 50
453 for i in range(N):
454 a[i] = C()
455 for j in range(N):
456 a[i][j] = i*j
457 for i in range(N):
458 for j in range(N):
459 self.assertEqual(a[i][j], i*j)
460
461 def test_python_lists(self):
462 # Testing Python subclass of list...
463 class C(list):
464 def __getitem__(self, i):
465 if isinstance(i, slice):
466 return i.start, i.stop
467 return list.__getitem__(self, i) + 100
468 a = C()
469 a.extend([0,1,2])
470 self.assertEqual(a[0], 100)
471 self.assertEqual(a[1], 101)
472 self.assertEqual(a[2], 102)
473 self.assertEqual(a[100:200], (100,200))
474
475 def test_metaclass(self):
476 # Testing metaclasses...
477 class C(metaclass=type):
478 def __init__(self):
479 self.__state = 0
480 def getstate(self):
481 return self.__state
482 def setstate(self, state):
483 self.__state = state
484 a = C()
485 self.assertEqual(a.getstate(), 0)
486 a.setstate(10)
487 self.assertEqual(a.getstate(), 10)
488 class _metaclass(type):
489 def myself(cls): return cls
490 class D(metaclass=_metaclass):
491 pass
492 self.assertEqual(D.myself(), D)
493 d = D()
494 self.assertEqual(d.__class__, D)
495 class M1(type):
496 def __new__(cls, name, bases, dict):
497 dict['__spam__'] = 1
498 return type.__new__(cls, name, bases, dict)
499 class C(metaclass=M1):
500 pass
501 self.assertEqual(C.__spam__, 1)
502 c = C()
503 self.assertEqual(c.__spam__, 1)
504
505 class _instance(object):
506 pass
507 class M2(object):
508 @staticmethod
509 def __new__(cls, name, bases, dict):
510 self = object.__new__(cls)
511 self.name = name
512 self.bases = bases
513 self.dict = dict
514 return self
515 def __call__(self):
516 it = _instance()
517 # Early binding of methods
518 for key in self.dict:
519 if key.startswith("__"):
520 continue
521 setattr(it, key, self.dict[key].__get__(it, self))
522 return it
523 class C(metaclass=M2):
524 def spam(self):
525 return 42
526 self.assertEqual(C.name, 'C')
527 self.assertEqual(C.bases, ())
528 self.assertIn('spam', C.dict)
529 c = C()
530 self.assertEqual(c.spam(), 42)
531
532 # More metaclass examples
533
534 class autosuper(type):
535 # Automatically add __super to the class
536 # This trick only works for dynamic classes
537 def __new__(metaclass, name, bases, dict):
538 cls = super(autosuper, metaclass).__new__(metaclass,
539 name, bases, dict)
540 # Name mangling for __super removes leading underscores
541 while name[:1] == "_":
542 name = name[1:]
543 if name:
544 name = "_%s__super" % name
545 else:
546 name = "__super"
547 setattr(cls, name, super(cls))
548 return cls
549 class A(metaclass=autosuper):
550 def meth(self):
551 return "A"
552 class B(A):
553 def meth(self):
554 return "B" + self.__super.meth()
555 class C(A):
556 def meth(self):
557 return "C" + self.__super.meth()
558 class D(C, B):
559 def meth(self):
560 return "D" + self.__super.meth()
561 self.assertEqual(D().meth(), "DCBA")
562 class E(B, C):
563 def meth(self):
564 return "E" + self.__super.meth()
565 self.assertEqual(E().meth(), "EBCA")
566
567 class autoproperty(type):
568 # Automatically create property attributes when methods
569 # named _get_x and/or _set_x are found
570 def __new__(metaclass, name, bases, dict):
571 hits = {}
572 for key, val in dict.items():
573 if key.startswith("_get_"):
574 key = key[5:]
575 get, set = hits.get(key, (None, None))
576 get = val
577 hits[key] = get, set
578 elif key.startswith("_set_"):
579 key = key[5:]
580 get, set = hits.get(key, (None, None))
581 set = val
582 hits[key] = get, set
583 for key, (get, set) in hits.items():
584 dict[key] = property(get, set)
585 return super(autoproperty, metaclass).__new__(metaclass,
586 name, bases, dict)
587 class A(metaclass=autoproperty):
588 def _get_x(self):
589 return -self.__x
590 def _set_x(self, x):
591 self.__x = -x
592 a = A()
593 self.assertNotHasAttr(a, "x")
594 a.x = 12
595 self.assertEqual(a.x, 12)
596 self.assertEqual(a._A__x, -12)
597
598 class multimetaclass(autoproperty, autosuper):
599 # Merge of multiple cooperating metaclasses
600 pass
601 class A(metaclass=multimetaclass):
602 def _get_x(self):
603 return "A"
604 class B(A):
605 def _get_x(self):
606 return "B" + self.__super._get_x()
607 class C(A):
608 def _get_x(self):
609 return "C" + self.__super._get_x()
610 class D(C, B):
611 def _get_x(self):
612 return "D" + self.__super._get_x()
613 self.assertEqual(D().x, "DCBA")
614
615 # Make sure type(x) doesn't call x.__class__.__init__
616 class T(type):
617 counter = 0
618 def __init__(self, *args):
619 T.counter += 1
620 class C(metaclass=T):
621 pass
622 self.assertEqual(T.counter, 1)
623 a = C()
624 self.assertEqual(type(a), C)
625 self.assertEqual(T.counter, 1)
626
627 class C(object): pass
628 c = C()
629 try: c()
630 except TypeError: pass
631 else: self.fail("calling object w/o call method should raise "
632 "TypeError")
633
634 # Testing code to find most derived baseclass
635 class A(type):
636 def __new__(*args, **kwargs):
637 return type.__new__(*args, **kwargs)
638
639 class B(object):
640 pass
641
642 class C(object, metaclass=A):
643 pass
644
645 # The most derived metaclass of D is A rather than type.
646 class D(B, C):
647 pass
648 self.assertIs(A, type(D))
649
650 # issue1294232: correct metaclass calculation
651 new_calls = [] # to check the order of __new__ calls
652 class AMeta(type):
653 @staticmethod
654 def __new__(mcls, name, bases, ns):
655 new_calls.append('AMeta')
656 return super().__new__(mcls, name, bases, ns)
657 @classmethod
658 def __prepare__(mcls, name, bases):
659 return {}
660
661 class BMeta(AMeta):
662 @staticmethod
663 def __new__(mcls, name, bases, ns):
664 new_calls.append('BMeta')
665 return super().__new__(mcls, name, bases, ns)
666 @classmethod
667 def __prepare__(mcls, name, bases):
668 ns = super().__prepare__(name, bases)
669 ns['BMeta_was_here'] = True
670 return ns
671
672 class A(metaclass=AMeta):
673 pass
674 self.assertEqual(['AMeta'], new_calls)
675 new_calls.clear()
676
677 class B(metaclass=BMeta):
678 pass
679 # BMeta.__new__ calls AMeta.__new__ with super:
680 self.assertEqual(['BMeta', 'AMeta'], new_calls)
681 new_calls.clear()
682
683 class C(A, B):
684 pass
685 # The most derived metaclass is BMeta:
686 self.assertEqual(['BMeta', 'AMeta'], new_calls)
687 new_calls.clear()
688 # BMeta.__prepare__ should've been called:
689 self.assertIn('BMeta_was_here', C.__dict__)
690
691 # The order of the bases shouldn't matter:
692 class C2(B, A):
693 pass
694 self.assertEqual(['BMeta', 'AMeta'], new_calls)
695 new_calls.clear()
696 self.assertIn('BMeta_was_here', C2.__dict__)
697
698 # Check correct metaclass calculation when a metaclass is declared:
699 class D(C, metaclass=type):
700 pass
701 self.assertEqual(['BMeta', 'AMeta'], new_calls)
702 new_calls.clear()
703 self.assertIn('BMeta_was_here', D.__dict__)
704
705 class E(C, metaclass=AMeta):
706 pass
707 self.assertEqual(['BMeta', 'AMeta'], new_calls)
708 new_calls.clear()
709 self.assertIn('BMeta_was_here', E.__dict__)
710
711 # Special case: the given metaclass isn't a class,
712 # so there is no metaclass calculation.
713 marker = object()
714 def func(*args, **kwargs):
715 return marker
716 class X(metaclass=func):
717 pass
718 class Y(object, metaclass=func):
719 pass
720 class Z(D, metaclass=func):
721 pass
722 self.assertIs(marker, X)
723 self.assertIs(marker, Y)
724 self.assertIs(marker, Z)
725
726 # The given metaclass is a class,
727 # but not a descendant of type.
728 prepare_calls = [] # to track __prepare__ calls
729 class ANotMeta:
730 def __new__(mcls, *args, **kwargs):
731 new_calls.append('ANotMeta')
732 return super().__new__(mcls)
733 @classmethod
734 def __prepare__(mcls, name, bases):
735 prepare_calls.append('ANotMeta')
736 return {}
737 class BNotMeta(ANotMeta):
738 def __new__(mcls, *args, **kwargs):
739 new_calls.append('BNotMeta')
740 return super().__new__(mcls)
741 @classmethod
742 def __prepare__(mcls, name, bases):
743 prepare_calls.append('BNotMeta')
744 return super().__prepare__(name, bases)
745
746 class A(metaclass=ANotMeta):
747 pass
748 self.assertIs(ANotMeta, type(A))
749 self.assertEqual(['ANotMeta'], prepare_calls)
750 prepare_calls.clear()
751 self.assertEqual(['ANotMeta'], new_calls)
752 new_calls.clear()
753
754 class B(metaclass=BNotMeta):
755 pass
756 self.assertIs(BNotMeta, type(B))
757 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
758 prepare_calls.clear()
759 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
760 new_calls.clear()
761
762 class C(A, B):
763 pass
764 self.assertIs(BNotMeta, type(C))
765 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
766 new_calls.clear()
767 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
768 prepare_calls.clear()
769
770 class C2(B, A):
771 pass
772 self.assertIs(BNotMeta, type(C2))
773 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
774 new_calls.clear()
775 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
776 prepare_calls.clear()
777
778 # This is a TypeError, because of a metaclass conflict:
779 # BNotMeta is neither a subclass, nor a superclass of type
780 with self.assertRaises(TypeError):
781 class D(C, metaclass=type):
782 pass
783
784 class E(C, metaclass=ANotMeta):
785 pass
786 self.assertIs(BNotMeta, type(E))
787 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
788 new_calls.clear()
789 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
790 prepare_calls.clear()
791
792 class F(object(), C):
793 pass
794 self.assertIs(BNotMeta, type(F))
795 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
796 new_calls.clear()
797 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
798 prepare_calls.clear()
799
800 class F2(C, object()):
801 pass
802 self.assertIs(BNotMeta, type(F2))
803 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
804 new_calls.clear()
805 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
806 prepare_calls.clear()
807
808 # TypeError: BNotMeta is neither a
809 # subclass, nor a superclass of int
810 with self.assertRaises(TypeError):
811 class X(C, int()):
812 pass
813 with self.assertRaises(TypeError):
814 class X(int(), C):
815 pass
816
817 def test_module_subclasses(self):
818 # Testing Python subclass of module...
819 log = []
820 MT = type(sys)
821 class MM(MT):
822 def __init__(self, name):
823 MT.__init__(self, name)
824 def __getattribute__(self, name):
825 log.append(("getattr", name))
826 return MT.__getattribute__(self, name)
827 def __setattr__(self, name, value):
828 log.append(("setattr", name, value))
829 MT.__setattr__(self, name, value)
830 def __delattr__(self, name):
831 log.append(("delattr", name))
832 MT.__delattr__(self, name)
833 a = MM("a")
834 a.foo = 12
835 x = a.foo
836 del a.foo
837 self.assertEqual(log, [("setattr", "foo", 12),
838 ("getattr", "foo"),
839 ("delattr", "foo")])
840
841 # https://bugs.python.org/issue1174712
842 try:
843 class Module(types.ModuleType, str):
844 pass
845 except TypeError:
846 pass
847 else:
848 self.fail("inheriting from ModuleType and str at the same time "
849 "should fail")
850
851 # Issue 34805: Verify that definition order is retained
852 def random_name():
853 return ''.join(random.choices(string.ascii_letters, k=10))
854 class A:
855 pass
856 subclasses = [type(random_name(), (A,), {}) for i in range(100)]
857 self.assertEqual(A.__subclasses__(), subclasses)
858
859 def test_multiple_inheritance(self):
860 # Testing multiple inheritance...
861 class C(object):
862 def __init__(self):
863 self.__state = 0
864 def getstate(self):
865 return self.__state
866 def setstate(self, state):
867 self.__state = state
868 a = C()
869 self.assertEqual(a.getstate(), 0)
870 a.setstate(10)
871 self.assertEqual(a.getstate(), 10)
872 class D(dict, C):
873 def __init__(self):
874 dict.__init__(self)
875 C.__init__(self)
876 d = D()
877 self.assertEqual(list(d.keys()), [])
878 d["hello"] = "world"
879 self.assertEqual(list(d.items()), [("hello", "world")])
880 self.assertEqual(d["hello"], "world")
881 self.assertEqual(d.getstate(), 0)
882 d.setstate(10)
883 self.assertEqual(d.getstate(), 10)
884 self.assertEqual(D.__mro__, (D, dict, C, object))
885
886 # SF bug #442833
887 class Node(object):
888 def __int__(self):
889 return int(self.foo())
890 def foo(self):
891 return "23"
892 class Frag(Node, list):
893 def foo(self):
894 return "42"
895 self.assertEqual(Node().__int__(), 23)
896 self.assertEqual(int(Node()), 23)
897 self.assertEqual(Frag().__int__(), 42)
898 self.assertEqual(int(Frag()), 42)
899
900 def test_diamond_inheritance(self):
901 # Testing multiple inheritance special cases...
902 class A(object):
903 def spam(self): return "A"
904 self.assertEqual(A().spam(), "A")
905 class B(A):
906 def boo(self): return "B"
907 def spam(self): return "B"
908 self.assertEqual(B().spam(), "B")
909 self.assertEqual(B().boo(), "B")
910 class C(A):
911 def boo(self): return "C"
912 self.assertEqual(C().spam(), "A")
913 self.assertEqual(C().boo(), "C")
914 class D(B, C): pass
915 self.assertEqual(D().spam(), "B")
916 self.assertEqual(D().boo(), "B")
917 self.assertEqual(D.__mro__, (D, B, C, A, object))
918 class E(C, B): pass
919 self.assertEqual(E().spam(), "B")
920 self.assertEqual(E().boo(), "C")
921 self.assertEqual(E.__mro__, (E, C, B, A, object))
922 # MRO order disagreement
923 try:
924 class F(D, E): pass
925 except TypeError:
926 pass
927 else:
928 self.fail("expected MRO order disagreement (F)")
929 try:
930 class G(E, D): pass
931 except TypeError:
932 pass
933 else:
934 self.fail("expected MRO order disagreement (G)")
935
936 # see thread python-dev/2002-October/029035.html
937 def test_ex5_from_c3_switch(self):
938 # Testing ex5 from C3 switch discussion...
939 class A(object): pass
940 class B(object): pass
941 class C(object): pass
942 class X(A): pass
943 class Y(A): pass
944 class Z(X,B,Y,C): pass
945 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
946
947 # see "A Monotonic Superclass Linearization for Dylan",
948 # by Kim Barrett et al. (OOPSLA 1996)
949 def test_monotonicity(self):
950 # Testing MRO monotonicity...
951 class Boat(object): pass
952 class DayBoat(Boat): pass
953 class WheelBoat(Boat): pass
954 class EngineLess(DayBoat): pass
955 class SmallMultihull(DayBoat): pass
956 class PedalWheelBoat(EngineLess,WheelBoat): pass
957 class SmallCatamaran(SmallMultihull): pass
958 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
959
960 self.assertEqual(PedalWheelBoat.__mro__,
961 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
962 self.assertEqual(SmallCatamaran.__mro__,
963 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
964 self.assertEqual(Pedalo.__mro__,
965 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
966 SmallMultihull, DayBoat, WheelBoat, Boat, object))
967
968 # see "A Monotonic Superclass Linearization for Dylan",
969 # by Kim Barrett et al. (OOPSLA 1996)
970 def test_consistency_with_epg(self):
971 # Testing consistency with EPG...
972 class Pane(object): pass
973 class ScrollingMixin(object): pass
974 class EditingMixin(object): pass
975 class ScrollablePane(Pane,ScrollingMixin): pass
976 class EditablePane(Pane,EditingMixin): pass
977 class EditableScrollablePane(ScrollablePane,EditablePane): pass
978
979 self.assertEqual(EditableScrollablePane.__mro__,
980 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
981 ScrollingMixin, EditingMixin, object))
982
983 def test_mro_disagreement(self):
984 # Testing error messages for MRO disagreement...
985 mro_err_msg = ("Cannot create a consistent method resolution "
986 "order (MRO) for bases ")
987
988 def raises(exc, expected, callable, *args):
989 try:
990 callable(*args)
991 except exc as msg:
992 # the exact msg is generally considered an impl detail
993 if support.check_impl_detail():
994 if not str(msg).startswith(expected):
995 self.fail("Message %r, expected %r" %
996 (str(msg), expected))
997 else:
998 self.fail("Expected %s" % exc)
999
1000 class A(object): pass
1001 class B(A): pass
1002 class C(object): pass
1003
1004 # Test some very simple errors
1005 raises(TypeError, "duplicate base class A",
1006 type, "X", (A, A), {})
1007 raises(TypeError, mro_err_msg,
1008 type, "X", (A, B), {})
1009 raises(TypeError, mro_err_msg,
1010 type, "X", (A, C, B), {})
1011 # Test a slightly more complex error
1012 class GridLayout(object): pass
1013 class HorizontalGrid(GridLayout): pass
1014 class VerticalGrid(GridLayout): pass
1015 class HVGrid(HorizontalGrid, VerticalGrid): pass
1016 class VHGrid(VerticalGrid, HorizontalGrid): pass
1017 raises(TypeError, mro_err_msg,
1018 type, "ConfusedGrid", (HVGrid, VHGrid), {})
1019
1020 def test_object_class(self):
1021 # Testing object class...
1022 a = object()
1023 self.assertEqual(a.__class__, object)
1024 self.assertEqual(type(a), object)
1025 b = object()
1026 self.assertNotEqual(a, b)
1027 self.assertNotHasAttr(a, "foo")
1028 try:
1029 a.foo = 12
1030 except (AttributeError, TypeError):
1031 pass
1032 else:
1033 self.fail("object() should not allow setting a foo attribute")
1034 self.assertNotHasAttr(object(), "__dict__")
1035
1036 class Cdict(object):
1037 pass
1038 x = Cdict()
1039 self.assertEqual(x.__dict__, {})
1040 x.foo = 1
1041 self.assertEqual(x.foo, 1)
1042 self.assertEqual(x.__dict__, {'foo': 1})
1043
1044 def test_object_class_assignment_between_heaptypes_and_nonheaptypes(self):
1045 class SubType(types.ModuleType):
1046 a = 1
1047
1048 m = types.ModuleType("m")
1049 self.assertTrue(m.__class__ is types.ModuleType)
1050 self.assertFalse(hasattr(m, "a"))
1051
1052 m.__class__ = SubType
1053 self.assertTrue(m.__class__ is SubType)
1054 self.assertTrue(hasattr(m, "a"))
1055
1056 m.__class__ = types.ModuleType
1057 self.assertTrue(m.__class__ is types.ModuleType)
1058 self.assertFalse(hasattr(m, "a"))
1059
1060 # Make sure that builtin immutable objects don't support __class__
1061 # assignment, because the object instances may be interned.
1062 # We set __slots__ = () to ensure that the subclasses are
1063 # memory-layout compatible, and thus otherwise reasonable candidates
1064 # for __class__ assignment.
1065
1066 # The following types have immutable instances, but are not
1067 # subclassable and thus don't need to be checked:
1068 # NoneType, bool
1069
1070 class MyInt(int):
1071 __slots__ = ()
1072 with self.assertRaises(TypeError):
1073 (1).__class__ = MyInt
1074
1075 class MyFloat(float):
1076 __slots__ = ()
1077 with self.assertRaises(TypeError):
1078 (1.0).__class__ = MyFloat
1079
1080 class MyComplex(complex):
1081 __slots__ = ()
1082 with self.assertRaises(TypeError):
1083 (1 + 2j).__class__ = MyComplex
1084
1085 class MyStr(str):
1086 __slots__ = ()
1087 with self.assertRaises(TypeError):
1088 "a".__class__ = MyStr
1089
1090 class MyBytes(bytes):
1091 __slots__ = ()
1092 with self.assertRaises(TypeError):
1093 b"a".__class__ = MyBytes
1094
1095 class MyTuple(tuple):
1096 __slots__ = ()
1097 with self.assertRaises(TypeError):
1098 ().__class__ = MyTuple
1099
1100 class MyFrozenSet(frozenset):
1101 __slots__ = ()
1102 with self.assertRaises(TypeError):
1103 frozenset().__class__ = MyFrozenSet
1104
1105 def test_slots(self):
1106 # Testing __slots__...
1107 class C0(object):
1108 __slots__ = []
1109 x = C0()
1110 self.assertNotHasAttr(x, "__dict__")
1111 self.assertNotHasAttr(x, "foo")
1112
1113 class C1(object):
1114 __slots__ = ['a']
1115 x = C1()
1116 self.assertNotHasAttr(x, "__dict__")
1117 self.assertNotHasAttr(x, "a")
1118 x.a = 1
1119 self.assertEqual(x.a, 1)
1120 x.a = None
1121 self.assertEqual(x.a, None)
1122 del x.a
1123 self.assertNotHasAttr(x, "a")
1124
1125 class C3(object):
1126 __slots__ = ['a', 'b', 'c']
1127 x = C3()
1128 self.assertNotHasAttr(x, "__dict__")
1129 self.assertNotHasAttr(x, 'a')
1130 self.assertNotHasAttr(x, 'b')
1131 self.assertNotHasAttr(x, 'c')
1132 x.a = 1
1133 x.b = 2
1134 x.c = 3
1135 self.assertEqual(x.a, 1)
1136 self.assertEqual(x.b, 2)
1137 self.assertEqual(x.c, 3)
1138
1139 class C4(object):
1140 """Validate name mangling"""
1141 __slots__ = ['__a']
1142 def __init__(self, value):
1143 self.__a = value
1144 def get(self):
1145 return self.__a
1146 x = C4(5)
1147 self.assertNotHasAttr(x, '__dict__')
1148 self.assertNotHasAttr(x, '__a')
1149 self.assertEqual(x.get(), 5)
1150 try:
1151 x.__a = 6
1152 except AttributeError:
1153 pass
1154 else:
1155 self.fail("Double underscored names not mangled")
1156
1157 # Make sure slot names are proper identifiers
1158 try:
1159 class C(object):
1160 __slots__ = [None]
1161 except TypeError:
1162 pass
1163 else:
1164 self.fail("[None] slots not caught")
1165 try:
1166 class C(object):
1167 __slots__ = ["foo bar"]
1168 except TypeError:
1169 pass
1170 else:
1171 self.fail("['foo bar'] slots not caught")
1172 try:
1173 class C(object):
1174 __slots__ = ["foo\0bar"]
1175 except TypeError:
1176 pass
1177 else:
1178 self.fail("['foo\\0bar'] slots not caught")
1179 try:
1180 class C(object):
1181 __slots__ = ["1"]
1182 except TypeError:
1183 pass
1184 else:
1185 self.fail("['1'] slots not caught")
1186 try:
1187 class C(object):
1188 __slots__ = [""]
1189 except TypeError:
1190 pass
1191 else:
1192 self.fail("[''] slots not caught")
1193
1194 class WithValidIdentifiers(object):
1195 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1196
1197 # Test a single string is not expanded as a sequence.
1198 class C(object):
1199 __slots__ = "abc"
1200 c = C()
1201 c.abc = 5
1202 self.assertEqual(c.abc, 5)
1203
1204 # Test unicode slot names
1205 # Test a single unicode string is not expanded as a sequence.
1206 class C(object):
1207 __slots__ = "abc"
1208 c = C()
1209 c.abc = 5
1210 self.assertEqual(c.abc, 5)
1211
1212 # _unicode_to_string used to modify slots in certain circumstances
1213 slots = ("foo", "bar")
1214 class C(object):
1215 __slots__ = slots
1216 x = C()
1217 x.foo = 5
1218 self.assertEqual(x.foo, 5)
1219 self.assertIs(type(slots[0]), str)
1220 # this used to leak references
1221 try:
1222 class C(object):
1223 __slots__ = [chr(128)]
1224 except (TypeError, UnicodeEncodeError):
1225 pass
1226 else:
1227 self.fail("[chr(128)] slots not caught")
1228
1229 # Test leaks
1230 class Counted(object):
1231 counter = 0 # counts the number of instances alive
1232 def __init__(self):
1233 Counted.counter += 1
1234 def __del__(self):
1235 Counted.counter -= 1
1236 class C(object):
1237 __slots__ = ['a', 'b', 'c']
1238 x = C()
1239 x.a = Counted()
1240 x.b = Counted()
1241 x.c = Counted()
1242 self.assertEqual(Counted.counter, 3)
1243 del x
1244 support.gc_collect()
1245 self.assertEqual(Counted.counter, 0)
1246 class D(C):
1247 pass
1248 x = D()
1249 x.a = Counted()
1250 x.z = Counted()
1251 self.assertEqual(Counted.counter, 2)
1252 del x
1253 support.gc_collect()
1254 self.assertEqual(Counted.counter, 0)
1255 class E(D):
1256 __slots__ = ['e']
1257 x = E()
1258 x.a = Counted()
1259 x.z = Counted()
1260 x.e = Counted()
1261 self.assertEqual(Counted.counter, 3)
1262 del x
1263 support.gc_collect()
1264 self.assertEqual(Counted.counter, 0)
1265
1266 # Test cyclical leaks [SF bug 519621]
1267 class F(object):
1268 __slots__ = ['a', 'b']
1269 s = F()
1270 s.a = [Counted(), s]
1271 self.assertEqual(Counted.counter, 1)
1272 s = None
1273 support.gc_collect()
1274 self.assertEqual(Counted.counter, 0)
1275
1276 # Test lookup leaks [SF bug 572567]
1277 if hasattr(gc, 'get_objects'):
1278 class G(object):
1279 def __eq__(self, other):
1280 return False
1281 g = G()
1282 orig_objects = len(gc.get_objects())
1283 for i in range(10):
1284 g==g
1285 new_objects = len(gc.get_objects())
1286 self.assertEqual(orig_objects, new_objects)
1287
1288 class H(object):
1289 __slots__ = ['a', 'b']
1290 def __init__(self):
1291 self.a = 1
1292 self.b = 2
1293 def __del__(self_):
1294 self.assertEqual(self_.a, 1)
1295 self.assertEqual(self_.b, 2)
1296 with support.captured_output('stderr') as s:
1297 h = H()
1298 del h
1299 self.assertEqual(s.getvalue(), '')
1300
1301 class X(object):
1302 __slots__ = "a"
1303 with self.assertRaises(AttributeError):
1304 del X().a
1305
1306 # Inherit from object on purpose to check some backwards compatibility paths
1307 class X(object):
1308 __slots__ = "a"
1309 with self.assertRaisesRegex(AttributeError, "'test.test_descr.ClassPropertiesAndMethods.test_slots.<locals>.X' object has no attribute 'a'"):
1310 X().a
1311
1312 # Test string subclass in `__slots__`, see gh-98783
1313 class SubStr(str):
1314 pass
1315 class X(object):
1316 __slots__ = (SubStr('x'),)
1317 X().x = 1
1318 with self.assertRaisesRegex(AttributeError, "'X' object has no attribute 'a'"):
1319 X().a
1320
1321 def test_slots_special(self):
1322 # Testing __dict__ and __weakref__ in __slots__...
1323 class D(object):
1324 __slots__ = ["__dict__"]
1325 a = D()
1326 self.assertHasAttr(a, "__dict__")
1327 self.assertNotHasAttr(a, "__weakref__")
1328 a.foo = 42
1329 self.assertEqual(a.__dict__, {"foo": 42})
1330
1331 class W(object):
1332 __slots__ = ["__weakref__"]
1333 a = W()
1334 self.assertHasAttr(a, "__weakref__")
1335 self.assertNotHasAttr(a, "__dict__")
1336 try:
1337 a.foo = 42
1338 except AttributeError:
1339 pass
1340 else:
1341 self.fail("shouldn't be allowed to set a.foo")
1342
1343 class C1(W, D):
1344 __slots__ = []
1345 a = C1()
1346 self.assertHasAttr(a, "__dict__")
1347 self.assertHasAttr(a, "__weakref__")
1348 a.foo = 42
1349 self.assertEqual(a.__dict__, {"foo": 42})
1350
1351 class C2(D, W):
1352 __slots__ = []
1353 a = C2()
1354 self.assertHasAttr(a, "__dict__")
1355 self.assertHasAttr(a, "__weakref__")
1356 a.foo = 42
1357 self.assertEqual(a.__dict__, {"foo": 42})
1358
1359 def test_slots_special2(self):
1360 # Testing __qualname__ and __classcell__ in __slots__
1361 class Meta(type):
1362 def __new__(cls, name, bases, namespace, attr):
1363 self.assertIn(attr, namespace)
1364 return super().__new__(cls, name, bases, namespace)
1365
1366 class C1:
1367 def __init__(self):
1368 self.b = 42
1369 class C2(C1, metaclass=Meta, attr="__classcell__"):
1370 __slots__ = ["__classcell__"]
1371 def __init__(self):
1372 super().__init__()
1373 self.assertIsInstance(C2.__dict__["__classcell__"],
1374 types.MemberDescriptorType)
1375 c = C2()
1376 self.assertEqual(c.b, 42)
1377 self.assertNotHasAttr(c, "__classcell__")
1378 c.__classcell__ = 42
1379 self.assertEqual(c.__classcell__, 42)
1380 with self.assertRaises(TypeError):
1381 class C3:
1382 __classcell__ = 42
1383 __slots__ = ["__classcell__"]
1384
1385 class Q1(metaclass=Meta, attr="__qualname__"):
1386 __slots__ = ["__qualname__"]
1387 self.assertEqual(Q1.__qualname__, C1.__qualname__[:-2] + "Q1")
1388 self.assertIsInstance(Q1.__dict__["__qualname__"],
1389 types.MemberDescriptorType)
1390 q = Q1()
1391 self.assertNotHasAttr(q, "__qualname__")
1392 q.__qualname__ = "q"
1393 self.assertEqual(q.__qualname__, "q")
1394 with self.assertRaises(TypeError):
1395 class Q2:
1396 __qualname__ = object()
1397 __slots__ = ["__qualname__"]
1398
1399 def test_slots_descriptor(self):
1400 # Issue2115: slot descriptors did not correctly check
1401 # the type of the given object
1402 import abc
1403 class MyABC(metaclass=abc.ABCMeta):
1404 __slots__ = "a"
1405
1406 class Unrelated(object):
1407 pass
1408 MyABC.register(Unrelated)
1409
1410 u = Unrelated()
1411 self.assertIsInstance(u, MyABC)
1412
1413 # This used to crash
1414 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1415
1416 def test_dynamics(self):
1417 # Testing class attribute propagation...
1418 class D(object):
1419 pass
1420 class E(D):
1421 pass
1422 class F(D):
1423 pass
1424 D.foo = 1
1425 self.assertEqual(D.foo, 1)
1426 # Test that dynamic attributes are inherited
1427 self.assertEqual(E.foo, 1)
1428 self.assertEqual(F.foo, 1)
1429 # Test dynamic instances
1430 class C(object):
1431 pass
1432 a = C()
1433 self.assertNotHasAttr(a, "foobar")
1434 C.foobar = 2
1435 self.assertEqual(a.foobar, 2)
1436 C.method = lambda self: 42
1437 self.assertEqual(a.method(), 42)
1438 C.__repr__ = lambda self: "C()"
1439 self.assertEqual(repr(a), "C()")
1440 C.__int__ = lambda self: 100
1441 self.assertEqual(int(a), 100)
1442 self.assertEqual(a.foobar, 2)
1443 self.assertNotHasAttr(a, "spam")
1444 def mygetattr(self, name):
1445 if name == "spam":
1446 return "spam"
1447 raise AttributeError
1448 C.__getattr__ = mygetattr
1449 self.assertEqual(a.spam, "spam")
1450 a.new = 12
1451 self.assertEqual(a.new, 12)
1452 def mysetattr(self, name, value):
1453 if name == "spam":
1454 raise AttributeError
1455 return object.__setattr__(self, name, value)
1456 C.__setattr__ = mysetattr
1457 with self.assertRaises(AttributeError):
1458 a.spam = "not spam"
1459
1460 self.assertEqual(a.spam, "spam")
1461 class D(C):
1462 pass
1463 d = D()
1464 d.foo = 1
1465 self.assertEqual(d.foo, 1)
1466
1467 # Test handling of int*seq and seq*int
1468 class I(int):
1469 pass
1470 self.assertEqual("a"*I(2), "aa")
1471 self.assertEqual(I(2)*"a", "aa")
1472 self.assertEqual(2*I(3), 6)
1473 self.assertEqual(I(3)*2, 6)
1474 self.assertEqual(I(3)*I(2), 6)
1475
1476 # Test comparison of classes with dynamic metaclasses
1477 class dynamicmetaclass(type):
1478 pass
1479 class someclass(metaclass=dynamicmetaclass):
1480 pass
1481 self.assertNotEqual(someclass, object)
1482
1483 def test_errors(self):
1484 # Testing errors...
1485 try:
1486 class C(list, dict):
1487 pass
1488 except TypeError:
1489 pass
1490 else:
1491 self.fail("inheritance from both list and dict should be illegal")
1492
1493 try:
1494 class C(object, None):
1495 pass
1496 except TypeError:
1497 pass
1498 else:
1499 self.fail("inheritance from non-type should be illegal")
1500 class Classic:
1501 pass
1502
1503 try:
1504 class C(type(len)):
1505 pass
1506 except TypeError:
1507 pass
1508 else:
1509 self.fail("inheritance from CFunction should be illegal")
1510
1511 try:
1512 class C(object):
1513 __slots__ = 1
1514 except TypeError:
1515 pass
1516 else:
1517 self.fail("__slots__ = 1 should be illegal")
1518
1519 try:
1520 class C(object):
1521 __slots__ = [1]
1522 except TypeError:
1523 pass
1524 else:
1525 self.fail("__slots__ = [1] should be illegal")
1526
1527 class M1(type):
1528 pass
1529 class M2(type):
1530 pass
1531 class A1(object, metaclass=M1):
1532 pass
1533 class A2(object, metaclass=M2):
1534 pass
1535 try:
1536 class B(A1, A2):
1537 pass
1538 except TypeError:
1539 pass
1540 else:
1541 self.fail("finding the most derived metaclass should have failed")
1542
1543 def test_classmethods(self):
1544 # Testing class methods...
1545 class C(object):
1546 def foo(*a): return a
1547 goo = classmethod(foo)
1548 c = C()
1549 self.assertEqual(C.goo(1), (C, 1))
1550 self.assertEqual(c.goo(1), (C, 1))
1551 self.assertEqual(c.foo(1), (c, 1))
1552 class D(C):
1553 pass
1554 d = D()
1555 self.assertEqual(D.goo(1), (D, 1))
1556 self.assertEqual(d.goo(1), (D, 1))
1557 self.assertEqual(d.foo(1), (d, 1))
1558 self.assertEqual(D.foo(d, 1), (d, 1))
1559 # Test for a specific crash (SF bug 528132)
1560 def f(cls, arg):
1561 "f docstring"
1562 return (cls, arg)
1563 ff = classmethod(f)
1564 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1565 self.assertEqual(ff.__get__(0)(42), (int, 42))
1566
1567 # Test super() with classmethods (SF bug 535444)
1568 self.assertEqual(C.goo.__self__, C)
1569 self.assertEqual(D.goo.__self__, D)
1570 self.assertEqual(super(D,D).goo.__self__, D)
1571 self.assertEqual(super(D,d).goo.__self__, D)
1572 self.assertEqual(super(D,D).goo(), (D,))
1573 self.assertEqual(super(D,d).goo(), (D,))
1574
1575 # Verify that a non-callable will raise
1576 meth = classmethod(1).__get__(1)
1577 self.assertRaises(TypeError, meth)
1578
1579 # Verify that classmethod() doesn't allow keyword args
1580 try:
1581 classmethod(f, kw=1)
1582 except TypeError:
1583 pass
1584 else:
1585 self.fail("classmethod shouldn't accept keyword args")
1586
1587 cm = classmethod(f)
1588 cm_dict = {'__annotations__': {},
1589 '__doc__': (
1590 "f docstring"
1591 if support.HAVE_PY_DOCSTRINGS
1592 else None
1593 ),
1594 '__module__': __name__,
1595 '__name__': 'f',
1596 '__qualname__': f.__qualname__}
1597 self.assertEqual(cm.__dict__, cm_dict)
1598
1599 cm.x = 42
1600 self.assertEqual(cm.x, 42)
1601 self.assertEqual(cm.__dict__, {"x" : 42, **cm_dict})
1602 del cm.x
1603 self.assertNotHasAttr(cm, "x")
1604
1605 @support.refcount_test
1606 def test_refleaks_in_classmethod___init__(self):
1607 gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount')
1608 cm = classmethod(None)
1609 refs_before = gettotalrefcount()
1610 for i in range(100):
1611 cm.__init__(None)
1612 self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10)
1613
1614 @support.impl_detail("the module 'xxsubtype' is internal")
1615 @unittest.skipIf(xxsubtype is None, "requires xxsubtype module")
1616 def test_classmethods_in_c(self):
1617 # Testing C-based class methods...
1618 import xxsubtype as spam
1619 a = (1, 2, 3)
1620 d = {'abc': 123}
1621 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1622 self.assertEqual(x, spam.spamlist)
1623 self.assertEqual(a, a1)
1624 self.assertEqual(d, d1)
1625 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1626 self.assertEqual(x, spam.spamlist)
1627 self.assertEqual(a, a1)
1628 self.assertEqual(d, d1)
1629 spam_cm = spam.spamlist.__dict__['classmeth']
1630 x2, a2, d2 = spam_cm(spam.spamlist, *a, **d)
1631 self.assertEqual(x2, spam.spamlist)
1632 self.assertEqual(a2, a1)
1633 self.assertEqual(d2, d1)
1634 class SubSpam(spam.spamlist): pass
1635 x2, a2, d2 = spam_cm(SubSpam, *a, **d)
1636 self.assertEqual(x2, SubSpam)
1637 self.assertEqual(a2, a1)
1638 self.assertEqual(d2, d1)
1639
1640 with self.assertRaises(TypeError) as cm:
1641 spam_cm()
1642 self.assertEqual(
1643 str(cm.exception),
1644 "descriptor 'classmeth' of 'xxsubtype.spamlist' "
1645 "object needs an argument")
1646
1647 with self.assertRaises(TypeError) as cm:
1648 spam_cm(spam.spamlist())
1649 self.assertEqual(
1650 str(cm.exception),
1651 "descriptor 'classmeth' for type 'xxsubtype.spamlist' "
1652 "needs a type, not a 'xxsubtype.spamlist' as arg 2")
1653
1654 with self.assertRaises(TypeError) as cm:
1655 spam_cm(list)
1656 expected_errmsg = (
1657 "descriptor 'classmeth' requires a subtype of 'xxsubtype.spamlist' "
1658 "but received 'list'")
1659 self.assertEqual(str(cm.exception), expected_errmsg)
1660
1661 with self.assertRaises(TypeError) as cm:
1662 spam_cm.__get__(None, list)
1663 self.assertEqual(str(cm.exception), expected_errmsg)
1664
1665 def test_staticmethods(self):
1666 # Testing static methods...
1667 class C(object):
1668 def foo(*a): return a
1669 goo = staticmethod(foo)
1670 c = C()
1671 self.assertEqual(C.goo(1), (1,))
1672 self.assertEqual(c.goo(1), (1,))
1673 self.assertEqual(c.foo(1), (c, 1,))
1674 class D(C):
1675 pass
1676 d = D()
1677 self.assertEqual(D.goo(1), (1,))
1678 self.assertEqual(d.goo(1), (1,))
1679 self.assertEqual(d.foo(1), (d, 1))
1680 self.assertEqual(D.foo(d, 1), (d, 1))
1681 sm = staticmethod(None)
1682 self.assertEqual(sm.__dict__, {'__doc__': None.__doc__})
1683 sm.x = 42
1684 self.assertEqual(sm.x, 42)
1685 self.assertEqual(sm.__dict__, {"x" : 42, '__doc__': None.__doc__})
1686 del sm.x
1687 self.assertNotHasAttr(sm, "x")
1688
1689 @support.refcount_test
1690 def test_refleaks_in_staticmethod___init__(self):
1691 gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount')
1692 sm = staticmethod(None)
1693 refs_before = gettotalrefcount()
1694 for i in range(100):
1695 sm.__init__(None)
1696 self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10)
1697
1698 @support.impl_detail("the module 'xxsubtype' is internal")
1699 @unittest.skipIf(xxsubtype is None, "requires xxsubtype module")
1700 def test_staticmethods_in_c(self):
1701 # Testing C-based static methods...
1702 import xxsubtype as spam
1703 a = (1, 2, 3)
1704 d = {"abc": 123}
1705 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1706 self.assertEqual(x, None)
1707 self.assertEqual(a, a1)
1708 self.assertEqual(d, d1)
1709 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1710 self.assertEqual(x, None)
1711 self.assertEqual(a, a1)
1712 self.assertEqual(d, d1)
1713
1714 def test_classic(self):
1715 # Testing classic classes...
1716 class C:
1717 def foo(*a): return a
1718 goo = classmethod(foo)
1719 c = C()
1720 self.assertEqual(C.goo(1), (C, 1))
1721 self.assertEqual(c.goo(1), (C, 1))
1722 self.assertEqual(c.foo(1), (c, 1))
1723 class D(C):
1724 pass
1725 d = D()
1726 self.assertEqual(D.goo(1), (D, 1))
1727 self.assertEqual(d.goo(1), (D, 1))
1728 self.assertEqual(d.foo(1), (d, 1))
1729 self.assertEqual(D.foo(d, 1), (d, 1))
1730 class E: # *not* subclassing from C
1731 foo = C.foo
1732 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
1733 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
1734
1735 def test_compattr(self):
1736 # Testing computed attributes...
1737 class C(object):
1738 class computed_attribute(object):
1739 def __init__(self, get, set=None, delete=None):
1740 self.__get = get
1741 self.__set = set
1742 self.__delete = delete
1743 def __get__(self, obj, type=None):
1744 return self.__get(obj)
1745 def __set__(self, obj, value):
1746 return self.__set(obj, value)
1747 def __delete__(self, obj):
1748 return self.__delete(obj)
1749 def __init__(self):
1750 self.__x = 0
1751 def __get_x(self):
1752 x = self.__x
1753 self.__x = x+1
1754 return x
1755 def __set_x(self, x):
1756 self.__x = x
1757 def __delete_x(self):
1758 del self.__x
1759 x = computed_attribute(__get_x, __set_x, __delete_x)
1760 a = C()
1761 self.assertEqual(a.x, 0)
1762 self.assertEqual(a.x, 1)
1763 a.x = 10
1764 self.assertEqual(a.x, 10)
1765 self.assertEqual(a.x, 11)
1766 del a.x
1767 self.assertNotHasAttr(a, 'x')
1768
1769 def test_newslots(self):
1770 # Testing __new__ slot override...
1771 class C(list):
1772 def __new__(cls):
1773 self = list.__new__(cls)
1774 self.foo = 1
1775 return self
1776 def __init__(self):
1777 self.foo = self.foo + 2
1778 a = C()
1779 self.assertEqual(a.foo, 3)
1780 self.assertEqual(a.__class__, C)
1781 class D(C):
1782 pass
1783 b = D()
1784 self.assertEqual(b.foo, 3)
1785 self.assertEqual(b.__class__, D)
1786
1787 @unittest.expectedFailure
1788 def test_bad_new(self):
1789 self.assertRaises(TypeError, object.__new__)
1790 self.assertRaises(TypeError, object.__new__, '')
1791 self.assertRaises(TypeError, list.__new__, object)
1792 self.assertRaises(TypeError, object.__new__, list)
1793 class C(object):
1794 __new__ = list.__new__
1795 self.assertRaises(TypeError, C)
1796 class C(list):
1797 __new__ = object.__new__
1798 self.assertRaises(TypeError, C)
1799
1800 def test_object_new(self):
1801 class A(object):
1802 pass
1803 object.__new__(A)
1804 self.assertRaises(TypeError, object.__new__, A, 5)
1805 object.__init__(A())
1806 self.assertRaises(TypeError, object.__init__, A(), 5)
1807
1808 class A(object):
1809 def __init__(self, foo):
1810 self.foo = foo
1811 object.__new__(A)
1812 object.__new__(A, 5)
1813 object.__init__(A(3))
1814 self.assertRaises(TypeError, object.__init__, A(3), 5)
1815
1816 class A(object):
1817 def __new__(cls, foo):
1818 return object.__new__(cls)
1819 object.__new__(A)
1820 self.assertRaises(TypeError, object.__new__, A, 5)
1821 object.__init__(A(3))
1822 object.__init__(A(3), 5)
1823
1824 class A(object):
1825 def __new__(cls, foo):
1826 return object.__new__(cls)
1827 def __init__(self, foo):
1828 self.foo = foo
1829 object.__new__(A)
1830 self.assertRaises(TypeError, object.__new__, A, 5)
1831 object.__init__(A(3))
1832 self.assertRaises(TypeError, object.__init__, A(3), 5)
1833
1834 @unittest.expectedFailure
1835 def test_restored_object_new(self):
1836 class A(object):
1837 def __new__(cls, *args, **kwargs):
1838 raise AssertionError
1839 self.assertRaises(AssertionError, A)
1840 class B(A):
1841 __new__ = object.__new__
1842 def __init__(self, foo):
1843 self.foo = foo
1844 with warnings.catch_warnings():
1845 warnings.simplefilter('error', DeprecationWarning)
1846 b = B(3)
1847 self.assertEqual(b.foo, 3)
1848 self.assertEqual(b.__class__, B)
1849 del B.__new__
1850 self.assertRaises(AssertionError, B)
1851 del A.__new__
1852 with warnings.catch_warnings():
1853 warnings.simplefilter('error', DeprecationWarning)
1854 b = B(3)
1855 self.assertEqual(b.foo, 3)
1856 self.assertEqual(b.__class__, B)
1857
1858 def test_altmro(self):
1859 # Testing mro() and overriding it...
1860 class A(object):
1861 def f(self): return "A"
1862 class B(A):
1863 pass
1864 class C(A):
1865 def f(self): return "C"
1866 class D(B, C):
1867 pass
1868 self.assertEqual(A.mro(), [A, object])
1869 self.assertEqual(A.__mro__, (A, object))
1870 self.assertEqual(B.mro(), [B, A, object])
1871 self.assertEqual(B.__mro__, (B, A, object))
1872 self.assertEqual(C.mro(), [C, A, object])
1873 self.assertEqual(C.__mro__, (C, A, object))
1874 self.assertEqual(D.mro(), [D, B, C, A, object])
1875 self.assertEqual(D.__mro__, (D, B, C, A, object))
1876 self.assertEqual(D().f(), "C")
1877
1878 class PerverseMetaType(type):
1879 def mro(cls):
1880 L = type.mro(cls)
1881 L.reverse()
1882 return L
1883 class X(D,B,C,A, metaclass=PerverseMetaType):
1884 pass
1885 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1886 self.assertEqual(X().f(), "A")
1887
1888 try:
1889 class _metaclass(type):
1890 def mro(self):
1891 return [self, dict, object]
1892 class X(object, metaclass=_metaclass):
1893 pass
1894 # In CPython, the class creation above already raises
1895 # TypeError, as a protection against the fact that
1896 # instances of X would segfault it. In other Python
1897 # implementations it would be ok to let the class X
1898 # be created, but instead get a clean TypeError on the
1899 # __setitem__ below.
1900 x = object.__new__(X)
1901 x[5] = 6
1902 except TypeError:
1903 pass
1904 else:
1905 self.fail("devious mro() return not caught")
1906
1907 try:
1908 class _metaclass(type):
1909 def mro(self):
1910 return [1]
1911 class X(object, metaclass=_metaclass):
1912 pass
1913 except TypeError:
1914 pass
1915 else:
1916 self.fail("non-class mro() return not caught")
1917
1918 try:
1919 class _metaclass(type):
1920 def mro(self):
1921 return 1
1922 class X(object, metaclass=_metaclass):
1923 pass
1924 except TypeError:
1925 pass
1926 else:
1927 self.fail("non-sequence mro() return not caught")
1928
1929 def test_overloading(self):
1930 # Testing operator overloading...
1931
1932 class B(object):
1933 "Intermediate class because object doesn't have a __setattr__"
1934
1935 class C(B):
1936 def __getattr__(self, name):
1937 if name == "foo":
1938 return ("getattr", name)
1939 else:
1940 raise AttributeError
1941 def __setattr__(self, name, value):
1942 if name == "foo":
1943 self.setattr = (name, value)
1944 else:
1945 return B.__setattr__(self, name, value)
1946 def __delattr__(self, name):
1947 if name == "foo":
1948 self.delattr = name
1949 else:
1950 return B.__delattr__(self, name)
1951
1952 def __getitem__(self, key):
1953 return ("getitem", key)
1954 def __setitem__(self, key, value):
1955 self.setitem = (key, value)
1956 def __delitem__(self, key):
1957 self.delitem = key
1958
1959 a = C()
1960 self.assertEqual(a.foo, ("getattr", "foo"))
1961 a.foo = 12
1962 self.assertEqual(a.setattr, ("foo", 12))
1963 del a.foo
1964 self.assertEqual(a.delattr, "foo")
1965
1966 self.assertEqual(a[12], ("getitem", 12))
1967 a[12] = 21
1968 self.assertEqual(a.setitem, (12, 21))
1969 del a[12]
1970 self.assertEqual(a.delitem, 12)
1971
1972 self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1973 a[0:10] = "foo"
1974 self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1975 del a[0:10]
1976 self.assertEqual(a.delitem, (slice(0, 10)))
1977
1978 def test_load_attr_extended_arg(self):
1979 # https://github.com/python/cpython/issues/91625
1980 class Numbers:
1981 def __getattr__(self, attr):
1982 return int(attr.lstrip("_"))
1983 attrs = ", ".join(f"Z._{n:03d}" for n in range(280))
1984 code = f"def number_attrs(Z):\n return [ {attrs} ]"
1985 ns = {}
1986 exec(code, ns)
1987 number_attrs = ns["number_attrs"]
1988 # Warm up the function for quickening (PEP 659)
1989 for _ in range(30):
1990 self.assertEqual(number_attrs(Numbers()), list(range(280)))
1991
1992 def test_methods(self):
1993 # Testing methods...
1994 class C(object):
1995 def __init__(self, x):
1996 self.x = x
1997 def foo(self):
1998 return self.x
1999 c1 = C(1)
2000 self.assertEqual(c1.foo(), 1)
2001 class D(C):
2002 boo = C.foo
2003 goo = c1.foo
2004 d2 = D(2)
2005 self.assertEqual(d2.foo(), 2)
2006 self.assertEqual(d2.boo(), 2)
2007 self.assertEqual(d2.goo(), 1)
2008 class E(object):
2009 foo = C.foo
2010 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
2011 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
2012
2013 @support.impl_detail("testing error message from implementation")
2014 def test_methods_in_c(self):
2015 # This test checks error messages in builtin method descriptor.
2016 # It is allowed that other Python implementations use
2017 # different error messages.
2018 set_add = set.add
2019
2020 expected_errmsg = "unbound method set.add() needs an argument"
2021
2022 with self.assertRaises(TypeError) as cm:
2023 set_add()
2024 self.assertEqual(cm.exception.args[0], expected_errmsg)
2025
2026 expected_errmsg = "descriptor 'add' for 'set' objects doesn't apply to a 'int' object"
2027
2028 with self.assertRaises(TypeError) as cm:
2029 set_add(0)
2030 self.assertEqual(cm.exception.args[0], expected_errmsg)
2031
2032 with self.assertRaises(TypeError) as cm:
2033 set_add.__get__(0)
2034 self.assertEqual(cm.exception.args[0], expected_errmsg)
2035
2036 def test_special_method_lookup(self):
2037 # The lookup of special methods bypasses __getattr__ and
2038 # __getattribute__, but they still can be descriptors.
2039
2040 def run_context(manager):
2041 with manager:
2042 pass
2043 def iden(self):
2044 return self
2045 def hello(self):
2046 return b"hello"
2047 def empty_seq(self):
2048 return []
2049 def zero(self):
2050 return 0
2051 def complex_num(self):
2052 return 1j
2053 def stop(self):
2054 raise StopIteration
2055 def return_true(self, thing=None):
2056 return True
2057 def do_isinstance(obj):
2058 return isinstance(int, obj)
2059 def do_issubclass(obj):
2060 return issubclass(int, obj)
2061 def do_dict_missing(checker):
2062 class DictSub(checker.__class__, dict):
2063 pass
2064 self.assertEqual(DictSub()["hi"], 4)
2065 def some_number(self_, key):
2066 self.assertEqual(key, "hi")
2067 return 4
2068 def swallow(*args): pass
2069 def format_impl(self, spec):
2070 return "hello"
2071
2072 # It would be nice to have every special method tested here, but I'm
2073 # only listing the ones I can remember outside of typeobject.c, since it
2074 # does it right.
2075 specials = [
2076 ("__bytes__", bytes, hello, set(), {}),
2077 ("__reversed__", reversed, empty_seq, set(), {}),
2078 ("__length_hint__", list, zero, set(),
2079 {"__iter__" : iden, "__next__" : stop}),
2080 ("__sizeof__", sys.getsizeof, zero, set(), {}),
2081 ("__instancecheck__", do_isinstance, return_true, set(), {}),
2082 ("__missing__", do_dict_missing, some_number,
2083 set(("__class__",)), {}),
2084 ("__subclasscheck__", do_issubclass, return_true,
2085 set(("__bases__",)), {}),
2086 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
2087 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
2088 ("__complex__", complex, complex_num, set(), {}),
2089 ("__format__", format, format_impl, set(), {}),
2090 ("__floor__", math.floor, zero, set(), {}),
2091 ("__trunc__", math.trunc, zero, set(), {}),
2092 ("__ceil__", math.ceil, zero, set(), {}),
2093 ("__dir__", dir, empty_seq, set(), {}),
2094 ("__round__", round, zero, set(), {}),
2095 ]
2096
2097 class Checker(object):
2098 def __getattr__(self, attr, test=self):
2099 test.fail("__getattr__ called with {0}".format(attr))
2100 def __getattribute__(self, attr, test=self):
2101 if attr not in ok:
2102 test.fail("__getattribute__ called with {0}".format(attr))
2103 return object.__getattribute__(self, attr)
2104 class SpecialDescr(object):
2105 def __init__(self, impl):
2106 self.impl = impl
2107 def __get__(self, obj, owner):
2108 record.append(1)
2109 return self.impl.__get__(obj, owner)
2110 class MyException(Exception):
2111 pass
2112 class ErrDescr(object):
2113 def __get__(self, obj, owner):
2114 raise MyException
2115
2116 for name, runner, meth_impl, ok, env in specials:
2117 class X(Checker):
2118 pass
2119 for attr, obj in env.items():
2120 setattr(X, attr, obj)
2121 setattr(X, name, meth_impl)
2122 runner(X())
2123
2124 record = []
2125 class X(Checker):
2126 pass
2127 for attr, obj in env.items():
2128 setattr(X, attr, obj)
2129 setattr(X, name, SpecialDescr(meth_impl))
2130 runner(X())
2131 self.assertEqual(record, [1], name)
2132
2133 class X(Checker):
2134 pass
2135 for attr, obj in env.items():
2136 setattr(X, attr, obj)
2137 setattr(X, name, ErrDescr())
2138 self.assertRaises(MyException, runner, X())
2139
2140 def test_specials(self):
2141 # Testing special operators...
2142 # Test operators like __hash__ for which a built-in default exists
2143
2144 # Test the default behavior for static classes
2145 class C(object):
2146 def __getitem__(self, i):
2147 if 0 <= i < 10: return i
2148 raise IndexError
2149 c1 = C()
2150 c2 = C()
2151 self.assertFalse(not c1)
2152 self.assertNotEqual(id(c1), id(c2))
2153 hash(c1)
2154 hash(c2)
2155 self.assertEqual(c1, c1)
2156 self.assertTrue(c1 != c2)
2157 self.assertFalse(c1 != c1)
2158 self.assertFalse(c1 == c2)
2159 # Note that the module name appears in str/repr, and that varies
2160 # depending on whether this test is run standalone or from a framework.
2161 self.assertGreaterEqual(str(c1).find('C object at '), 0)
2162 self.assertEqual(str(c1), repr(c1))
2163 self.assertNotIn(-1, c1)
2164 for i in range(10):
2165 self.assertIn(i, c1)
2166 self.assertNotIn(10, c1)
2167 # Test the default behavior for dynamic classes
2168 class D(object):
2169 def __getitem__(self, i):
2170 if 0 <= i < 10: return i
2171 raise IndexError
2172 d1 = D()
2173 d2 = D()
2174 self.assertFalse(not d1)
2175 self.assertNotEqual(id(d1), id(d2))
2176 hash(d1)
2177 hash(d2)
2178 self.assertEqual(d1, d1)
2179 self.assertNotEqual(d1, d2)
2180 self.assertFalse(d1 != d1)
2181 self.assertFalse(d1 == d2)
2182 # Note that the module name appears in str/repr, and that varies
2183 # depending on whether this test is run standalone or from a framework.
2184 self.assertGreaterEqual(str(d1).find('D object at '), 0)
2185 self.assertEqual(str(d1), repr(d1))
2186 self.assertNotIn(-1, d1)
2187 for i in range(10):
2188 self.assertIn(i, d1)
2189 self.assertNotIn(10, d1)
2190 # Test overridden behavior
2191 class Proxy(object):
2192 def __init__(self, x):
2193 self.x = x
2194 def __bool__(self):
2195 return not not self.x
2196 def __hash__(self):
2197 return hash(self.x)
2198 def __eq__(self, other):
2199 return self.x == other
2200 def __ne__(self, other):
2201 return self.x != other
2202 def __ge__(self, other):
2203 return self.x >= other
2204 def __gt__(self, other):
2205 return self.x > other
2206 def __le__(self, other):
2207 return self.x <= other
2208 def __lt__(self, other):
2209 return self.x < other
2210 def __str__(self):
2211 return "Proxy:%s" % self.x
2212 def __repr__(self):
2213 return "Proxy(%r)" % self.x
2214 def __contains__(self, value):
2215 return value in self.x
2216 p0 = Proxy(0)
2217 p1 = Proxy(1)
2218 p_1 = Proxy(-1)
2219 self.assertFalse(p0)
2220 self.assertFalse(not p1)
2221 self.assertEqual(hash(p0), hash(0))
2222 self.assertEqual(p0, p0)
2223 self.assertNotEqual(p0, p1)
2224 self.assertFalse(p0 != p0)
2225 self.assertEqual(not p0, p1)
2226 self.assertTrue(p0 < p1)
2227 self.assertTrue(p0 <= p1)
2228 self.assertTrue(p1 > p0)
2229 self.assertTrue(p1 >= p0)
2230 self.assertEqual(str(p0), "Proxy:0")
2231 self.assertEqual(repr(p0), "Proxy(0)")
2232 p10 = Proxy(range(10))
2233 self.assertNotIn(-1, p10)
2234 for i in range(10):
2235 self.assertIn(i, p10)
2236 self.assertNotIn(10, p10)
2237
2238 def test_weakrefs(self):
2239 # Testing weak references...
2240 import weakref
2241 class C(object):
2242 pass
2243 c = C()
2244 r = weakref.ref(c)
2245 self.assertEqual(r(), c)
2246 del c
2247 support.gc_collect()
2248 self.assertEqual(r(), None)
2249 del r
2250 class NoWeak(object):
2251 __slots__ = ['foo']
2252 no = NoWeak()
2253 try:
2254 weakref.ref(no)
2255 except TypeError as msg:
2256 self.assertIn("weak reference", str(msg))
2257 else:
2258 self.fail("weakref.ref(no) should be illegal")
2259 class Weak(object):
2260 __slots__ = ['foo', '__weakref__']
2261 yes = Weak()
2262 r = weakref.ref(yes)
2263 self.assertEqual(r(), yes)
2264 del yes
2265 support.gc_collect()
2266 self.assertEqual(r(), None)
2267 del r
2268
2269 def test_properties(self):
2270 # Testing property...
2271 class C(object):
2272 def getx(self):
2273 return self.__x
2274 def setx(self, value):
2275 self.__x = value
2276 def delx(self):
2277 del self.__x
2278 x = property(getx, setx, delx, doc="I'm the x property.")
2279 a = C()
2280 self.assertNotHasAttr(a, "x")
2281 a.x = 42
2282 self.assertEqual(a._C__x, 42)
2283 self.assertEqual(a.x, 42)
2284 del a.x
2285 self.assertNotHasAttr(a, "x")
2286 self.assertNotHasAttr(a, "_C__x")
2287 C.x.__set__(a, 100)
2288 self.assertEqual(C.x.__get__(a), 100)
2289 C.x.__delete__(a)
2290 self.assertNotHasAttr(a, "x")
2291
2292 raw = C.__dict__['x']
2293 self.assertIsInstance(raw, property)
2294
2295 attrs = dir(raw)
2296 self.assertIn("__doc__", attrs)
2297 self.assertIn("fget", attrs)
2298 self.assertIn("fset", attrs)
2299 self.assertIn("fdel", attrs)
2300
2301 self.assertEqual(raw.__doc__, "I'm the x property.")
2302 self.assertIs(raw.fget, C.__dict__['getx'])
2303 self.assertIs(raw.fset, C.__dict__['setx'])
2304 self.assertIs(raw.fdel, C.__dict__['delx'])
2305
2306 for attr in "fget", "fset", "fdel":
2307 try:
2308 setattr(raw, attr, 42)
2309 except AttributeError as msg:
2310 if str(msg).find('readonly') < 0:
2311 self.fail("when setting readonly attr %r on a property, "
2312 "got unexpected AttributeError msg %r" % (attr, str(msg)))
2313 else:
2314 self.fail("expected AttributeError from trying to set readonly %r "
2315 "attr on a property" % attr)
2316
2317 raw.__doc__ = 42
2318 self.assertEqual(raw.__doc__, 42)
2319
2320 class D(object):
2321 __getitem__ = property(lambda s: 1/0)
2322
2323 d = D()
2324 try:
2325 for i in d:
2326 str(i)
2327 except ZeroDivisionError:
2328 pass
2329 else:
2330 self.fail("expected ZeroDivisionError from bad property")
2331
2332 @unittest.skipIf(sys.flags.optimize >= 2,
2333 "Docstrings are omitted with -O2 and above")
2334 def test_properties_doc_attrib(self):
2335 class E(object):
2336 def getter(self):
2337 "getter method"
2338 return 0
2339 def setter(self_, value):
2340 "setter method"
2341 pass
2342 prop = property(getter)
2343 self.assertEqual(prop.__doc__, "getter method")
2344 prop2 = property(fset=setter)
2345 self.assertEqual(prop2.__doc__, None)
2346
2347 @support.cpython_only
2348 def test_testcapi_no_segfault(self):
2349 # this segfaulted in 2.5b2
2350 try:
2351 import _testcapi
2352 except ImportError:
2353 pass
2354 else:
2355 class X(object):
2356 p = property(_testcapi.test_with_docstring)
2357
2358 def test_properties_plus(self):
2359 class C(object):
2360 foo = property(doc="hello")
2361 @foo.getter
2362 def foo(self):
2363 return self._foo
2364 @foo.setter
2365 def foo(self, value):
2366 self._foo = abs(value)
2367 @foo.deleter
2368 def foo(self):
2369 del self._foo
2370 c = C()
2371 self.assertEqual(C.foo.__doc__, "hello")
2372 self.assertNotHasAttr(c, "foo")
2373 c.foo = -42
2374 self.assertHasAttr(c, '_foo')
2375 self.assertEqual(c._foo, 42)
2376 self.assertEqual(c.foo, 42)
2377 del c.foo
2378 self.assertNotHasAttr(c, '_foo')
2379 self.assertNotHasAttr(c, "foo")
2380
2381 class D(C):
2382 @C.foo.deleter
2383 def foo(self):
2384 try:
2385 del self._foo
2386 except AttributeError:
2387 pass
2388 d = D()
2389 d.foo = 24
2390 self.assertEqual(d.foo, 24)
2391 del d.foo
2392 del d.foo
2393
2394 class E(object):
2395 @property
2396 def foo(self):
2397 return self._foo
2398 @foo.setter
2399 def foo(self, value):
2400 raise RuntimeError
2401 @foo.setter
2402 def foo(self, value):
2403 self._foo = abs(value)
2404 @foo.deleter
2405 def foo(self, value=None):
2406 del self._foo
2407
2408 e = E()
2409 e.foo = -42
2410 self.assertEqual(e.foo, 42)
2411 del e.foo
2412
2413 class F(E):
2414 @E.foo.deleter
2415 def foo(self):
2416 del self._foo
2417 @foo.setter
2418 def foo(self, value):
2419 self._foo = max(0, value)
2420 f = F()
2421 f.foo = -10
2422 self.assertEqual(f.foo, 0)
2423 del f.foo
2424
2425 def test_dict_constructors(self):
2426 # Testing dict constructor ...
2427 d = dict()
2428 self.assertEqual(d, {})
2429 d = dict({})
2430 self.assertEqual(d, {})
2431 d = dict({1: 2, 'a': 'b'})
2432 self.assertEqual(d, {1: 2, 'a': 'b'})
2433 self.assertEqual(d, dict(list(d.items())))
2434 self.assertEqual(d, dict(iter(d.items())))
2435 d = dict({'one':1, 'two':2})
2436 self.assertEqual(d, dict(one=1, two=2))
2437 self.assertEqual(d, dict(**d))
2438 self.assertEqual(d, dict({"one": 1}, two=2))
2439 self.assertEqual(d, dict([("two", 2)], one=1))
2440 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2441 self.assertEqual(d, dict(**d))
2442
2443 for badarg in 0, 0, 0j, "0", [0], (0,):
2444 try:
2445 dict(badarg)
2446 except TypeError:
2447 pass
2448 except ValueError:
2449 if badarg == "0":
2450 # It's a sequence, and its elements are also sequences (gotta
2451 # love strings <wink>), but they aren't of length 2, so this
2452 # one seemed better as a ValueError than a TypeError.
2453 pass
2454 else:
2455 self.fail("no TypeError from dict(%r)" % badarg)
2456 else:
2457 self.fail("no TypeError from dict(%r)" % badarg)
2458
2459 with self.assertRaises(TypeError):
2460 dict({}, {})
2461
2462 class Mapping:
2463 # Lacks a .keys() method; will be added later.
2464 dict = {1:2, 3:4, 'a':1j}
2465
2466 try:
2467 dict(Mapping())
2468 except TypeError:
2469 pass
2470 else:
2471 self.fail("no TypeError from dict(incomplete mapping)")
2472
2473 Mapping.keys = lambda self: list(self.dict.keys())
2474 Mapping.__getitem__ = lambda self, i: self.dict[i]
2475 d = dict(Mapping())
2476 self.assertEqual(d, Mapping.dict)
2477
2478 # Init from sequence of iterable objects, each producing a 2-sequence.
2479 class AddressBookEntry:
2480 def __init__(self, first, last):
2481 self.first = first
2482 self.last = last
2483 def __iter__(self):
2484 return iter([self.first, self.last])
2485
2486 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2487 AddressBookEntry('Barry', 'Peters'),
2488 AddressBookEntry('Tim', 'Peters'),
2489 AddressBookEntry('Barry', 'Warsaw')])
2490 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2491
2492 d = dict(zip(range(4), range(1, 5)))
2493 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2494
2495 # Bad sequence lengths.
2496 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2497 try:
2498 dict(bad)
2499 except ValueError:
2500 pass
2501 else:
2502 self.fail("no ValueError from dict(%r)" % bad)
2503
2504 def test_dir(self):
2505 # Testing dir() ...
2506 junk = 12
2507 self.assertEqual(dir(), ['junk', 'self'])
2508 del junk
2509
2510 # Just make sure these don't blow up!
2511 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2512 dir(arg)
2513
2514 # Test dir on new-style classes. Since these have object as a
2515 # base class, a lot more gets sucked in.
2516 def interesting(strings):
2517 return [s for s in strings if not s.startswith('_')]
2518
2519 class C(object):
2520 Cdata = 1
2521 def Cmethod(self): pass
2522
2523 cstuff = ['Cdata', 'Cmethod']
2524 self.assertEqual(interesting(dir(C)), cstuff)
2525
2526 c = C()
2527 self.assertEqual(interesting(dir(c)), cstuff)
2528 ## self.assertIn('__self__', dir(C.Cmethod))
2529
2530 c.cdata = 2
2531 c.cmethod = lambda self: 0
2532 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
2533 ## self.assertIn('__self__', dir(c.Cmethod))
2534
2535 class A(C):
2536 Adata = 1
2537 def Amethod(self): pass
2538
2539 astuff = ['Adata', 'Amethod'] + cstuff
2540 self.assertEqual(interesting(dir(A)), astuff)
2541 ## self.assertIn('__self__', dir(A.Amethod))
2542 a = A()
2543 self.assertEqual(interesting(dir(a)), astuff)
2544 a.adata = 42
2545 a.amethod = lambda self: 3
2546 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
2547 ## self.assertIn('__self__', dir(a.Amethod))
2548
2549 # Try a module subclass.
2550 class M(type(sys)):
2551 pass
2552 minstance = M("m")
2553 minstance.b = 2
2554 minstance.a = 1
2555 default_attributes = ['__name__', '__doc__', '__package__',
2556 '__loader__', '__spec__']
2557 names = [x for x in dir(minstance) if x not in default_attributes]
2558 self.assertEqual(names, ['a', 'b'])
2559
2560 class M2(M):
2561 def getdict(self):
2562 return "Not a dict!"
2563 __dict__ = property(getdict)
2564
2565 m2instance = M2("m2")
2566 m2instance.b = 2
2567 m2instance.a = 1
2568 self.assertEqual(m2instance.__dict__, "Not a dict!")
2569 with self.assertRaises(TypeError):
2570 dir(m2instance)
2571
2572 # Two essentially featureless objects, (Ellipsis just inherits stuff
2573 # from object.
2574 self.assertEqual(dir(object()), dir(Ellipsis))
2575
2576 # Nasty test case for proxied objects
2577 class Wrapper(object):
2578 def __init__(self, obj):
2579 self.__obj = obj
2580 def __repr__(self):
2581 return "Wrapper(%s)" % repr(self.__obj)
2582 def __getitem__(self, key):
2583 return Wrapper(self.__obj[key])
2584 def __len__(self):
2585 return len(self.__obj)
2586 def __getattr__(self, name):
2587 return Wrapper(getattr(self.__obj, name))
2588
2589 class C(object):
2590 def __getclass(self):
2591 return Wrapper(type(self))
2592 __class__ = property(__getclass)
2593
2594 dir(C()) # This used to segfault
2595
2596 def test_supers(self):
2597 # Testing super...
2598
2599 class A(object):
2600 def meth(self, a):
2601 return "A(%r)" % a
2602
2603 self.assertEqual(A().meth(1), "A(1)")
2604
2605 class B(A):
2606 def __init__(self):
2607 self.__super = super(B, self)
2608 def meth(self, a):
2609 return "B(%r)" % a + self.__super.meth(a)
2610
2611 self.assertEqual(B().meth(2), "B(2)A(2)")
2612
2613 class C(A):
2614 def meth(self, a):
2615 return "C(%r)" % a + self.__super.meth(a)
2616 C._C__super = super(C)
2617
2618 self.assertEqual(C().meth(3), "C(3)A(3)")
2619
2620 class D(C, B):
2621 def meth(self, a):
2622 return "D(%r)" % a + super(D, self).meth(a)
2623
2624 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2625
2626 # Test for subclassing super
2627
2628 class mysuper(super):
2629 def __init__(self, *args):
2630 return super(mysuper, self).__init__(*args)
2631
2632 class E(D):
2633 def meth(self, a):
2634 return "E(%r)" % a + mysuper(E, self).meth(a)
2635
2636 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2637
2638 class F(E):
2639 def meth(self, a):
2640 s = self.__super # == mysuper(F, self)
2641 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2642 F._F__super = mysuper(F)
2643
2644 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2645
2646 # Make sure certain errors are raised
2647
2648 try:
2649 super(D, 42)
2650 except TypeError:
2651 pass
2652 else:
2653 self.fail("shouldn't allow super(D, 42)")
2654
2655 try:
2656 super(D, C())
2657 except TypeError:
2658 pass
2659 else:
2660 self.fail("shouldn't allow super(D, C())")
2661
2662 try:
2663 super(D).__get__(12)
2664 except TypeError:
2665 pass
2666 else:
2667 self.fail("shouldn't allow super(D).__get__(12)")
2668
2669 try:
2670 super(D).__get__(C())
2671 except TypeError:
2672 pass
2673 else:
2674 self.fail("shouldn't allow super(D).__get__(C())")
2675
2676 # Make sure data descriptors can be overridden and accessed via super
2677 # (new feature in Python 2.3)
2678
2679 class DDbase(object):
2680 def getx(self): return 42
2681 x = property(getx)
2682
2683 class DDsub(DDbase):
2684 def getx(self): return "hello"
2685 x = property(getx)
2686
2687 dd = DDsub()
2688 self.assertEqual(dd.x, "hello")
2689 self.assertEqual(super(DDsub, dd).x, 42)
2690
2691 # Ensure that super() lookup of descriptor from classmethod
2692 # works (SF ID# 743627)
2693
2694 class Base(object):
2695 aProp = property(lambda self: "foo")
2696
2697 class Sub(Base):
2698 @classmethod
2699 def test(klass):
2700 return super(Sub,klass).aProp
2701
2702 self.assertEqual(Sub.test(), Base.aProp)
2703
2704 # Verify that super() doesn't allow keyword args
2705 with self.assertRaises(TypeError):
2706 super(Base, kw=1)
2707
2708 def test_basic_inheritance(self):
2709 # Testing inheritance from basic types...
2710
2711 class hexint(int):
2712 def __repr__(self):
2713 return hex(self)
2714 def __add__(self, other):
2715 return hexint(int.__add__(self, other))
2716 # (Note that overriding __radd__ doesn't work,
2717 # because the int type gets first dibs.)
2718 self.assertEqual(repr(hexint(7) + 9), "0x10")
2719 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2720 a = hexint(12345)
2721 self.assertEqual(a, 12345)
2722 self.assertEqual(int(a), 12345)
2723 self.assertIs(int(a).__class__, int)
2724 self.assertEqual(hash(a), hash(12345))
2725 self.assertIs((+a).__class__, int)
2726 self.assertIs((a >> 0).__class__, int)
2727 self.assertIs((a << 0).__class__, int)
2728 self.assertIs((hexint(0) << 12).__class__, int)
2729 self.assertIs((hexint(0) >> 12).__class__, int)
2730
2731 class octlong(int):
2732 __slots__ = []
2733 def __str__(self):
2734 return oct(self)
2735 def __add__(self, other):
2736 return self.__class__(super(octlong, self).__add__(other))
2737 __radd__ = __add__
2738 self.assertEqual(str(octlong(3) + 5), "0o10")
2739 # (Note that overriding __radd__ here only seems to work
2740 # because the example uses a short int left argument.)
2741 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2742 a = octlong(12345)
2743 self.assertEqual(a, 12345)
2744 self.assertEqual(int(a), 12345)
2745 self.assertEqual(hash(a), hash(12345))
2746 self.assertIs(int(a).__class__, int)
2747 self.assertIs((+a).__class__, int)
2748 self.assertIs((-a).__class__, int)
2749 self.assertIs((-octlong(0)).__class__, int)
2750 self.assertIs((a >> 0).__class__, int)
2751 self.assertIs((a << 0).__class__, int)
2752 self.assertIs((a - 0).__class__, int)
2753 self.assertIs((a * 1).__class__, int)
2754 self.assertIs((a ** 1).__class__, int)
2755 self.assertIs((a // 1).__class__, int)
2756 self.assertIs((1 * a).__class__, int)
2757 self.assertIs((a | 0).__class__, int)
2758 self.assertIs((a ^ 0).__class__, int)
2759 self.assertIs((a & -1).__class__, int)
2760 self.assertIs((octlong(0) << 12).__class__, int)
2761 self.assertIs((octlong(0) >> 12).__class__, int)
2762 self.assertIs(abs(octlong(0)).__class__, int)
2763
2764 # Because octlong overrides __add__, we can't check the absence of +0
2765 # optimizations using octlong.
2766 class longclone(int):
2767 pass
2768 a = longclone(1)
2769 self.assertIs((a + 0).__class__, int)
2770 self.assertIs((0 + a).__class__, int)
2771
2772 # Check that negative clones don't segfault
2773 a = longclone(-1)
2774 self.assertEqual(a.__dict__, {})
2775 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
2776
2777 class precfloat(float):
2778 __slots__ = ['prec']
2779 def __init__(self, value=0.0, prec=12):
2780 self.prec = int(prec)
2781 def __repr__(self):
2782 return "%.*g" % (self.prec, self)
2783 self.assertEqual(repr(precfloat(1.1)), "1.1")
2784 a = precfloat(12345)
2785 self.assertEqual(a, 12345.0)
2786 self.assertEqual(float(a), 12345.0)
2787 self.assertIs(float(a).__class__, float)
2788 self.assertEqual(hash(a), hash(12345.0))
2789 self.assertIs((+a).__class__, float)
2790
2791 class madcomplex(complex):
2792 def __repr__(self):
2793 return "%.17gj%+.17g" % (self.imag, self.real)
2794 a = madcomplex(-3, 4)
2795 self.assertEqual(repr(a), "4j-3")
2796 base = complex(-3, 4)
2797 self.assertEqual(base.__class__, complex)
2798 self.assertEqual(a, base)
2799 self.assertEqual(complex(a), base)
2800 self.assertEqual(complex(a).__class__, complex)
2801 a = madcomplex(a) # just trying another form of the constructor
2802 self.assertEqual(repr(a), "4j-3")
2803 self.assertEqual(a, base)
2804 self.assertEqual(complex(a), base)
2805 self.assertEqual(complex(a).__class__, complex)
2806 self.assertEqual(hash(a), hash(base))
2807 self.assertEqual((+a).__class__, complex)
2808 self.assertEqual((a + 0).__class__, complex)
2809 self.assertEqual(a + 0, base)
2810 self.assertEqual((a - 0).__class__, complex)
2811 self.assertEqual(a - 0, base)
2812 self.assertEqual((a * 1).__class__, complex)
2813 self.assertEqual(a * 1, base)
2814 self.assertEqual((a / 1).__class__, complex)
2815 self.assertEqual(a / 1, base)
2816
2817 class madtuple(tuple):
2818 _rev = None
2819 def rev(self):
2820 if self._rev is not None:
2821 return self._rev
2822 L = list(self)
2823 L.reverse()
2824 self._rev = self.__class__(L)
2825 return self._rev
2826 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2827 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2828 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2829 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2830 for i in range(512):
2831 t = madtuple(range(i))
2832 u = t.rev()
2833 v = u.rev()
2834 self.assertEqual(v, t)
2835 a = madtuple((1,2,3,4,5))
2836 self.assertEqual(tuple(a), (1,2,3,4,5))
2837 self.assertIs(tuple(a).__class__, tuple)
2838 self.assertEqual(hash(a), hash((1,2,3,4,5)))
2839 self.assertIs(a[:].__class__, tuple)
2840 self.assertIs((a * 1).__class__, tuple)
2841 self.assertIs((a * 0).__class__, tuple)
2842 self.assertIs((a + ()).__class__, tuple)
2843 a = madtuple(())
2844 self.assertEqual(tuple(a), ())
2845 self.assertIs(tuple(a).__class__, tuple)
2846 self.assertIs((a + a).__class__, tuple)
2847 self.assertIs((a * 0).__class__, tuple)
2848 self.assertIs((a * 1).__class__, tuple)
2849 self.assertIs((a * 2).__class__, tuple)
2850 self.assertIs(a[:].__class__, tuple)
2851
2852 class madstring(str):
2853 _rev = None
2854 def rev(self):
2855 if self._rev is not None:
2856 return self._rev
2857 L = list(self)
2858 L.reverse()
2859 self._rev = self.__class__("".join(L))
2860 return self._rev
2861 s = madstring("abcdefghijklmnopqrstuvwxyz")
2862 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2863 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2864 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2865 for i in range(256):
2866 s = madstring("".join(map(chr, range(i))))
2867 t = s.rev()
2868 u = t.rev()
2869 self.assertEqual(u, s)
2870 s = madstring("12345")
2871 self.assertEqual(str(s), "12345")
2872 self.assertIs(str(s).__class__, str)
2873
2874 base = "\x00" * 5
2875 s = madstring(base)
2876 self.assertEqual(s, base)
2877 self.assertEqual(str(s), base)
2878 self.assertIs(str(s).__class__, str)
2879 self.assertEqual(hash(s), hash(base))
2880 self.assertEqual({s: 1}[base], 1)
2881 self.assertEqual({base: 1}[s], 1)
2882 self.assertIs((s + "").__class__, str)
2883 self.assertEqual(s + "", base)
2884 self.assertIs(("" + s).__class__, str)
2885 self.assertEqual("" + s, base)
2886 self.assertIs((s * 0).__class__, str)
2887 self.assertEqual(s * 0, "")
2888 self.assertIs((s * 1).__class__, str)
2889 self.assertEqual(s * 1, base)
2890 self.assertIs((s * 2).__class__, str)
2891 self.assertEqual(s * 2, base + base)
2892 self.assertIs(s[:].__class__, str)
2893 self.assertEqual(s[:], base)
2894 self.assertIs(s[0:0].__class__, str)
2895 self.assertEqual(s[0:0], "")
2896 self.assertIs(s.strip().__class__, str)
2897 self.assertEqual(s.strip(), base)
2898 self.assertIs(s.lstrip().__class__, str)
2899 self.assertEqual(s.lstrip(), base)
2900 self.assertIs(s.rstrip().__class__, str)
2901 self.assertEqual(s.rstrip(), base)
2902 identitytab = {}
2903 self.assertIs(s.translate(identitytab).__class__, str)
2904 self.assertEqual(s.translate(identitytab), base)
2905 self.assertIs(s.replace("x", "x").__class__, str)
2906 self.assertEqual(s.replace("x", "x"), base)
2907 self.assertIs(s.ljust(len(s)).__class__, str)
2908 self.assertEqual(s.ljust(len(s)), base)
2909 self.assertIs(s.rjust(len(s)).__class__, str)
2910 self.assertEqual(s.rjust(len(s)), base)
2911 self.assertIs(s.center(len(s)).__class__, str)
2912 self.assertEqual(s.center(len(s)), base)
2913 self.assertIs(s.lower().__class__, str)
2914 self.assertEqual(s.lower(), base)
2915
2916 class madunicode(str):
2917 _rev = None
2918 def rev(self):
2919 if self._rev is not None:
2920 return self._rev
2921 L = list(self)
2922 L.reverse()
2923 self._rev = self.__class__("".join(L))
2924 return self._rev
2925 u = madunicode("ABCDEF")
2926 self.assertEqual(u, "ABCDEF")
2927 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2928 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2929 base = "12345"
2930 u = madunicode(base)
2931 self.assertEqual(str(u), base)
2932 self.assertIs(str(u).__class__, str)
2933 self.assertEqual(hash(u), hash(base))
2934 self.assertEqual({u: 1}[base], 1)
2935 self.assertEqual({base: 1}[u], 1)
2936 self.assertIs(u.strip().__class__, str)
2937 self.assertEqual(u.strip(), base)
2938 self.assertIs(u.lstrip().__class__, str)
2939 self.assertEqual(u.lstrip(), base)
2940 self.assertIs(u.rstrip().__class__, str)
2941 self.assertEqual(u.rstrip(), base)
2942 self.assertIs(u.replace("x", "x").__class__, str)
2943 self.assertEqual(u.replace("x", "x"), base)
2944 self.assertIs(u.replace("xy", "xy").__class__, str)
2945 self.assertEqual(u.replace("xy", "xy"), base)
2946 self.assertIs(u.center(len(u)).__class__, str)
2947 self.assertEqual(u.center(len(u)), base)
2948 self.assertIs(u.ljust(len(u)).__class__, str)
2949 self.assertEqual(u.ljust(len(u)), base)
2950 self.assertIs(u.rjust(len(u)).__class__, str)
2951 self.assertEqual(u.rjust(len(u)), base)
2952 self.assertIs(u.lower().__class__, str)
2953 self.assertEqual(u.lower(), base)
2954 self.assertIs(u.upper().__class__, str)
2955 self.assertEqual(u.upper(), base)
2956 self.assertIs(u.capitalize().__class__, str)
2957 self.assertEqual(u.capitalize(), base)
2958 self.assertIs(u.title().__class__, str)
2959 self.assertEqual(u.title(), base)
2960 self.assertIs((u + "").__class__, str)
2961 self.assertEqual(u + "", base)
2962 self.assertIs(("" + u).__class__, str)
2963 self.assertEqual("" + u, base)
2964 self.assertIs((u * 0).__class__, str)
2965 self.assertEqual(u * 0, "")
2966 self.assertIs((u * 1).__class__, str)
2967 self.assertEqual(u * 1, base)
2968 self.assertIs((u * 2).__class__, str)
2969 self.assertEqual(u * 2, base + base)
2970 self.assertIs(u[:].__class__, str)
2971 self.assertEqual(u[:], base)
2972 self.assertIs(u[0:0].__class__, str)
2973 self.assertEqual(u[0:0], "")
2974
2975 class sublist(list):
2976 pass
2977 a = sublist(range(5))
2978 self.assertEqual(a, list(range(5)))
2979 a.append("hello")
2980 self.assertEqual(a, list(range(5)) + ["hello"])
2981 a[5] = 5
2982 self.assertEqual(a, list(range(6)))
2983 a.extend(range(6, 20))
2984 self.assertEqual(a, list(range(20)))
2985 a[-5:] = []
2986 self.assertEqual(a, list(range(15)))
2987 del a[10:15]
2988 self.assertEqual(len(a), 10)
2989 self.assertEqual(a, list(range(10)))
2990 self.assertEqual(list(a), list(range(10)))
2991 self.assertEqual(a[0], 0)
2992 self.assertEqual(a[9], 9)
2993 self.assertEqual(a[-10], 0)
2994 self.assertEqual(a[-1], 9)
2995 self.assertEqual(a[:5], list(range(5)))
2996
2997 ## class CountedInput(file):
2998 ## """Counts lines read by self.readline().
2999 ##
3000 ## self.lineno is the 0-based ordinal of the last line read, up to
3001 ## a maximum of one greater than the number of lines in the file.
3002 ##
3003 ## self.ateof is true if and only if the final "" line has been read,
3004 ## at which point self.lineno stops incrementing, and further calls
3005 ## to readline() continue to return "".
3006 ## """
3007 ##
3008 ## lineno = 0
3009 ## ateof = 0
3010 ## def readline(self):
3011 ## if self.ateof:
3012 ## return ""
3013 ## s = file.readline(self)
3014 ## # Next line works too.
3015 ## # s = super(CountedInput, self).readline()
3016 ## self.lineno += 1
3017 ## if s == "":
3018 ## self.ateof = 1
3019 ## return s
3020 ##
3021 ## f = file(name=os_helper.TESTFN, mode='w')
3022 ## lines = ['a\n', 'b\n', 'c\n']
3023 ## try:
3024 ## f.writelines(lines)
3025 ## f.close()
3026 ## f = CountedInput(os_helper.TESTFN)
3027 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
3028 ## got = f.readline()
3029 ## self.assertEqual(expected, got)
3030 ## self.assertEqual(f.lineno, i)
3031 ## self.assertEqual(f.ateof, (i > len(lines)))
3032 ## f.close()
3033 ## finally:
3034 ## try:
3035 ## f.close()
3036 ## except:
3037 ## pass
3038 ## os_helper.unlink(os_helper.TESTFN)
3039
3040 def test_keywords(self):
3041 # Testing keyword args to basic type constructors ...
3042 with self.assertRaisesRegex(TypeError, 'keyword argument'):
3043 int(x=1)
3044 with self.assertRaisesRegex(TypeError, 'keyword argument'):
3045 float(x=2)
3046 with self.assertRaisesRegex(TypeError, 'keyword argument'):
3047 bool(x=2)
3048 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
3049 self.assertEqual(str(object=500), '500')
3050 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
3051 with self.assertRaisesRegex(TypeError, 'keyword argument'):
3052 tuple(sequence=range(3))
3053 with self.assertRaisesRegex(TypeError, 'keyword argument'):
3054 list(sequence=(0, 1, 2))
3055 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
3056
3057 for constructor in (int, float, int, complex, str, str,
3058 tuple, list):
3059 try:
3060 constructor(bogus_keyword_arg=1)
3061 except TypeError:
3062 pass
3063 else:
3064 self.fail("expected TypeError from bogus keyword argument to %r"
3065 % constructor)
3066
3067 def test_str_subclass_as_dict_key(self):
3068 # Testing a str subclass used as dict key ..
3069
3070 class cistr(str):
3071 """Subclass of str that computes __eq__ case-insensitively.
3072
3073 Also computes a hash code of the string in canonical form.
3074 """
3075
3076 def __init__(self, value):
3077 self.canonical = value.lower()
3078 self.hashcode = hash(self.canonical)
3079
3080 def __eq__(self, other):
3081 if not isinstance(other, cistr):
3082 other = cistr(other)
3083 return self.canonical == other.canonical
3084
3085 def __hash__(self):
3086 return self.hashcode
3087
3088 self.assertEqual(cistr('ABC'), 'abc')
3089 self.assertEqual('aBc', cistr('ABC'))
3090 self.assertEqual(str(cistr('ABC')), 'ABC')
3091
3092 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
3093 self.assertEqual(d[cistr('one')], 1)
3094 self.assertEqual(d[cistr('tWo')], 2)
3095 self.assertEqual(d[cistr('THrEE')], 3)
3096 self.assertIn(cistr('ONe'), d)
3097 self.assertEqual(d.get(cistr('thrEE')), 3)
3098
3099 def test_classic_comparisons(self):
3100 # Testing classic comparisons...
3101 class classic:
3102 pass
3103
3104 for base in (classic, int, object):
3105 class C(base):
3106 def __init__(self, value):
3107 self.value = int(value)
3108 def __eq__(self, other):
3109 if isinstance(other, C):
3110 return self.value == other.value
3111 if isinstance(other, int) or isinstance(other, int):
3112 return self.value == other
3113 return NotImplemented
3114 def __ne__(self, other):
3115 if isinstance(other, C):
3116 return self.value != other.value
3117 if isinstance(other, int) or isinstance(other, int):
3118 return self.value != other
3119 return NotImplemented
3120 def __lt__(self, other):
3121 if isinstance(other, C):
3122 return self.value < other.value
3123 if isinstance(other, int) or isinstance(other, int):
3124 return self.value < other
3125 return NotImplemented
3126 def __le__(self, other):
3127 if isinstance(other, C):
3128 return self.value <= other.value
3129 if isinstance(other, int) or isinstance(other, int):
3130 return self.value <= other
3131 return NotImplemented
3132 def __gt__(self, other):
3133 if isinstance(other, C):
3134 return self.value > other.value
3135 if isinstance(other, int) or isinstance(other, int):
3136 return self.value > other
3137 return NotImplemented
3138 def __ge__(self, other):
3139 if isinstance(other, C):
3140 return self.value >= other.value
3141 if isinstance(other, int) or isinstance(other, int):
3142 return self.value >= other
3143 return NotImplemented
3144
3145 c1 = C(1)
3146 c2 = C(2)
3147 c3 = C(3)
3148 self.assertEqual(c1, 1)
3149 c = {1: c1, 2: c2, 3: c3}
3150 for x in 1, 2, 3:
3151 for y in 1, 2, 3:
3152 for op in "<", "<=", "==", "!=", ">", ">=":
3153 self.assertEqual(eval("c[x] %s c[y]" % op),
3154 eval("x %s y" % op),
3155 "x=%d, y=%d" % (x, y))
3156 self.assertEqual(eval("c[x] %s y" % op),
3157 eval("x %s y" % op),
3158 "x=%d, y=%d" % (x, y))
3159 self.assertEqual(eval("x %s c[y]" % op),
3160 eval("x %s y" % op),
3161 "x=%d, y=%d" % (x, y))
3162
3163 def test_rich_comparisons(self):
3164 # Testing rich comparisons...
3165 class Z(complex):
3166 pass
3167 z = Z(1)
3168 self.assertEqual(z, 1+0j)
3169 self.assertEqual(1+0j, z)
3170 class ZZ(complex):
3171 def __eq__(self, other):
3172 try:
3173 return abs(self - other) <= 1e-6
3174 except:
3175 return NotImplemented
3176 zz = ZZ(1.0000003)
3177 self.assertEqual(zz, 1+0j)
3178 self.assertEqual(1+0j, zz)
3179
3180 class classic:
3181 pass
3182 for base in (classic, int, object, list):
3183 class C(base):
3184 def __init__(self, value):
3185 self.value = int(value)
3186 def __cmp__(self_, other):
3187 self.fail("shouldn't call __cmp__")
3188 def __eq__(self, other):
3189 if isinstance(other, C):
3190 return self.value == other.value
3191 if isinstance(other, int) or isinstance(other, int):
3192 return self.value == other
3193 return NotImplemented
3194 def __ne__(self, other):
3195 if isinstance(other, C):
3196 return self.value != other.value
3197 if isinstance(other, int) or isinstance(other, int):
3198 return self.value != other
3199 return NotImplemented
3200 def __lt__(self, other):
3201 if isinstance(other, C):
3202 return self.value < other.value
3203 if isinstance(other, int) or isinstance(other, int):
3204 return self.value < other
3205 return NotImplemented
3206 def __le__(self, other):
3207 if isinstance(other, C):
3208 return self.value <= other.value
3209 if isinstance(other, int) or isinstance(other, int):
3210 return self.value <= other
3211 return NotImplemented
3212 def __gt__(self, other):
3213 if isinstance(other, C):
3214 return self.value > other.value
3215 if isinstance(other, int) or isinstance(other, int):
3216 return self.value > other
3217 return NotImplemented
3218 def __ge__(self, other):
3219 if isinstance(other, C):
3220 return self.value >= other.value
3221 if isinstance(other, int) or isinstance(other, int):
3222 return self.value >= other
3223 return NotImplemented
3224 c1 = C(1)
3225 c2 = C(2)
3226 c3 = C(3)
3227 self.assertEqual(c1, 1)
3228 c = {1: c1, 2: c2, 3: c3}
3229 for x in 1, 2, 3:
3230 for y in 1, 2, 3:
3231 for op in "<", "<=", "==", "!=", ">", ">=":
3232 self.assertEqual(eval("c[x] %s c[y]" % op),
3233 eval("x %s y" % op),
3234 "x=%d, y=%d" % (x, y))
3235 self.assertEqual(eval("c[x] %s y" % op),
3236 eval("x %s y" % op),
3237 "x=%d, y=%d" % (x, y))
3238 self.assertEqual(eval("x %s c[y]" % op),
3239 eval("x %s y" % op),
3240 "x=%d, y=%d" % (x, y))
3241
3242 def test_descrdoc(self):
3243 # Testing descriptor doc strings...
3244 from _io import FileIO
3245 def check(descr, what):
3246 self.assertEqual(descr.__doc__, what)
3247 check(FileIO.closed, "True if the file is closed") # getset descriptor
3248 check(complex.real, "the real part of a complex number") # member descriptor
3249
3250 def test_doc_descriptor(self):
3251 # Testing __doc__ descriptor...
3252 # SF bug 542984
3253 class DocDescr(object):
3254 def __get__(self, object, otype):
3255 if object:
3256 object = object.__class__.__name__ + ' instance'
3257 if otype:
3258 otype = otype.__name__
3259 return 'object=%s; type=%s' % (object, otype)
3260 class NewClass:
3261 __doc__ = DocDescr()
3262 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
3263 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3264
3265 def test_set_class(self):
3266 # Testing __class__ assignment...
3267 class C(object): pass
3268 class D(object): pass
3269 class E(object): pass
3270 class F(D, E): pass
3271 for cls in C, D, E, F:
3272 for cls2 in C, D, E, F:
3273 x = cls()
3274 x.__class__ = cls2
3275 self.assertIs(x.__class__, cls2)
3276 x.__class__ = cls
3277 self.assertIs(x.__class__, cls)
3278 def cant(x, C):
3279 try:
3280 x.__class__ = C
3281 except TypeError:
3282 pass
3283 else:
3284 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3285 try:
3286 delattr(x, "__class__")
3287 except (TypeError, AttributeError):
3288 pass
3289 else:
3290 self.fail("shouldn't allow del %r.__class__" % x)
3291 cant(C(), list)
3292 cant(list(), C)
3293 cant(C(), 1)
3294 cant(C(), object)
3295 cant(object(), list)
3296 cant(list(), object)
3297 class Int(int): __slots__ = []
3298 cant(True, int)
3299 cant(2, bool)
3300 o = object()
3301 cant(o, int)
3302 cant(o, type(None))
3303 del o
3304 class G(object):
3305 __slots__ = ["a", "b"]
3306 class H(object):
3307 __slots__ = ["b", "a"]
3308 class I(object):
3309 __slots__ = ["a", "b"]
3310 class J(object):
3311 __slots__ = ["c", "b"]
3312 class K(object):
3313 __slots__ = ["a", "b", "d"]
3314 class L(H):
3315 __slots__ = ["e"]
3316 class M(I):
3317 __slots__ = ["e"]
3318 class N(J):
3319 __slots__ = ["__weakref__"]
3320 class P(J):
3321 __slots__ = ["__dict__"]
3322 class Q(J):
3323 pass
3324 class R(J):
3325 __slots__ = ["__dict__", "__weakref__"]
3326
3327 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3328 x = cls()
3329 x.a = 1
3330 x.__class__ = cls2
3331 self.assertIs(x.__class__, cls2,
3332 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3333 self.assertEqual(x.a, 1)
3334 x.__class__ = cls
3335 self.assertIs(x.__class__, cls,
3336 "assigning %r as __class__ for %r silently failed" % (cls, x))
3337 self.assertEqual(x.a, 1)
3338 for cls in G, J, K, L, M, N, P, R, list, Int:
3339 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3340 if cls is cls2:
3341 continue
3342 cant(cls(), cls2)
3343
3344 # Issue5283: when __class__ changes in __del__, the wrong
3345 # type gets DECREF'd.
3346 class O(object):
3347 pass
3348 class A(object):
3349 def __del__(self):
3350 self.__class__ = O
3351 l = [A() for x in range(100)]
3352 del l
3353
3354 def test_set_dict(self):
3355 # Testing __dict__ assignment...
3356 class C(object): pass
3357 a = C()
3358 a.__dict__ = {'b': 1}
3359 self.assertEqual(a.b, 1)
3360 def cant(x, dict):
3361 try:
3362 x.__dict__ = dict
3363 except (AttributeError, TypeError):
3364 pass
3365 else:
3366 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3367 cant(a, None)
3368 cant(a, [])
3369 cant(a, 1)
3370 del a.__dict__ # Deleting __dict__ is allowed
3371
3372 class Base(object):
3373 pass
3374 def verify_dict_readonly(x):
3375 """
3376 x has to be an instance of a class inheriting from Base.
3377 """
3378 cant(x, {})
3379 try:
3380 del x.__dict__
3381 except (AttributeError, TypeError):
3382 pass
3383 else:
3384 self.fail("shouldn't allow del %r.__dict__" % x)
3385 dict_descr = Base.__dict__["__dict__"]
3386 try:
3387 dict_descr.__set__(x, {})
3388 except (AttributeError, TypeError):
3389 pass
3390 else:
3391 self.fail("dict_descr allowed access to %r's dict" % x)
3392
3393 # Classes don't allow __dict__ assignment and have readonly dicts
3394 class Meta1(type, Base):
3395 pass
3396 class Meta2(Base, type):
3397 pass
3398 class D(object, metaclass=Meta1):
3399 pass
3400 class E(object, metaclass=Meta2):
3401 pass
3402 for cls in C, D, E:
3403 verify_dict_readonly(cls)
3404 class_dict = cls.__dict__
3405 try:
3406 class_dict["spam"] = "eggs"
3407 except TypeError:
3408 pass
3409 else:
3410 self.fail("%r's __dict__ can be modified" % cls)
3411
3412 # Modules also disallow __dict__ assignment
3413 class Module1(types.ModuleType, Base):
3414 pass
3415 class Module2(Base, types.ModuleType):
3416 pass
3417 for ModuleType in Module1, Module2:
3418 mod = ModuleType("spam")
3419 verify_dict_readonly(mod)
3420 mod.__dict__["spam"] = "eggs"
3421
3422 # Exception's __dict__ can be replaced, but not deleted
3423 # (at least not any more than regular exception's __dict__ can
3424 # be deleted; on CPython it is not the case, whereas on PyPy they
3425 # can, just like any other new-style instance's __dict__.)
3426 def can_delete_dict(e):
3427 try:
3428 del e.__dict__
3429 except (TypeError, AttributeError):
3430 return False
3431 else:
3432 return True
3433 class Exception1(Exception, Base):
3434 pass
3435 class Exception2(Base, Exception):
3436 pass
3437 for ExceptionType in Exception, Exception1, Exception2:
3438 e = ExceptionType()
3439 e.__dict__ = {"a": 1}
3440 self.assertEqual(e.a, 1)
3441 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
3442
3443 def test_binary_operator_override(self):
3444 # Testing overrides of binary operations...
3445 class I(int):
3446 def __repr__(self):
3447 return "I(%r)" % int(self)
3448 def __add__(self, other):
3449 return I(int(self) + int(other))
3450 __radd__ = __add__
3451 def __pow__(self, other, mod=None):
3452 if mod is None:
3453 return I(pow(int(self), int(other)))
3454 else:
3455 return I(pow(int(self), int(other), int(mod)))
3456 def __rpow__(self, other, mod=None):
3457 if mod is None:
3458 return I(pow(int(other), int(self), mod))
3459 else:
3460 return I(pow(int(other), int(self), int(mod)))
3461
3462 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3463 self.assertEqual(repr(I(1) + 2), "I(3)")
3464 self.assertEqual(repr(1 + I(2)), "I(3)")
3465 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3466 self.assertEqual(repr(2 ** I(3)), "I(8)")
3467 self.assertEqual(repr(I(2) ** 3), "I(8)")
3468 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3469 class S(str):
3470 def __eq__(self, other):
3471 return self.lower() == other.lower()
3472
3473 def test_subclass_propagation(self):
3474 # Testing propagation of slot functions to subclasses...
3475 class A(object):
3476 pass
3477 class B(A):
3478 pass
3479 class C(A):
3480 pass
3481 class D(B, C):
3482 pass
3483 d = D()
3484 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3485 A.__hash__ = lambda self: 42
3486 self.assertEqual(hash(d), 42)
3487 C.__hash__ = lambda self: 314
3488 self.assertEqual(hash(d), 314)
3489 B.__hash__ = lambda self: 144
3490 self.assertEqual(hash(d), 144)
3491 D.__hash__ = lambda self: 100
3492 self.assertEqual(hash(d), 100)
3493 D.__hash__ = None
3494 self.assertRaises(TypeError, hash, d)
3495 del D.__hash__
3496 self.assertEqual(hash(d), 144)
3497 B.__hash__ = None
3498 self.assertRaises(TypeError, hash, d)
3499 del B.__hash__
3500 self.assertEqual(hash(d), 314)
3501 C.__hash__ = None
3502 self.assertRaises(TypeError, hash, d)
3503 del C.__hash__
3504 self.assertEqual(hash(d), 42)
3505 A.__hash__ = None
3506 self.assertRaises(TypeError, hash, d)
3507 del A.__hash__
3508 self.assertEqual(hash(d), orig_hash)
3509 d.foo = 42
3510 d.bar = 42
3511 self.assertEqual(d.foo, 42)
3512 self.assertEqual(d.bar, 42)
3513 def __getattribute__(self, name):
3514 if name == "foo":
3515 return 24
3516 return object.__getattribute__(self, name)
3517 A.__getattribute__ = __getattribute__
3518 self.assertEqual(d.foo, 24)
3519 self.assertEqual(d.bar, 42)
3520 def __getattr__(self, name):
3521 if name in ("spam", "foo", "bar"):
3522 return "hello"
3523 raise AttributeError(name)
3524 B.__getattr__ = __getattr__
3525 self.assertEqual(d.spam, "hello")
3526 self.assertEqual(d.foo, 24)
3527 self.assertEqual(d.bar, 42)
3528 del A.__getattribute__
3529 self.assertEqual(d.foo, 42)
3530 del d.foo
3531 self.assertEqual(d.foo, "hello")
3532 self.assertEqual(d.bar, 42)
3533 del B.__getattr__
3534 try:
3535 d.foo
3536 except AttributeError:
3537 pass
3538 else:
3539 self.fail("d.foo should be undefined now")
3540
3541 # Test a nasty bug in recurse_down_subclasses()
3542 class A(object):
3543 pass
3544 class B(A):
3545 pass
3546 del B
3547 support.gc_collect()
3548 A.__setitem__ = lambda *a: None # crash
3549
3550 def test_buffer_inheritance(self):
3551 # Testing that buffer interface is inherited ...
3552
3553 import binascii
3554 # SF bug [#470040] ParseTuple t# vs subclasses.
3555
3556 class MyBytes(bytes):
3557 pass
3558 base = b'abc'
3559 m = MyBytes(base)
3560 # b2a_hex uses the buffer interface to get its argument's value, via
3561 # PyArg_ParseTuple 't#' code.
3562 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3563
3564 class MyInt(int):
3565 pass
3566 m = MyInt(42)
3567 try:
3568 binascii.b2a_hex(m)
3569 self.fail('subclass of int should not have a buffer interface')
3570 except TypeError:
3571 pass
3572
3573 def test_str_of_str_subclass(self):
3574 # Testing __str__ defined in subclass of str ...
3575 import binascii
3576
3577 class octetstring(str):
3578 def __str__(self):
3579 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
3580 def __repr__(self):
3581 return self + " repr"
3582
3583 o = octetstring('A')
3584 self.assertEqual(type(o), octetstring)
3585 self.assertEqual(type(str(o)), str)
3586 self.assertEqual(type(repr(o)), str)
3587 self.assertEqual(ord(o), 0x41)
3588 self.assertEqual(str(o), '41')
3589 self.assertEqual(repr(o), 'A repr')
3590 self.assertEqual(o.__str__(), '41')
3591 self.assertEqual(o.__repr__(), 'A repr')
3592
3593 def test_repr_with_module_str_subclass(self):
3594 # gh-98783
3595 class StrSub(str):
3596 pass
3597 class Some:
3598 pass
3599 Some.__module__ = StrSub('example')
3600 self.assertIsInstance(repr(Some), str) # should not crash
3601 self.assertIsInstance(repr(Some()), str) # should not crash
3602
3603 def test_keyword_arguments(self):
3604 # Testing keyword arguments to __init__, __call__...
3605 def f(a): return a
3606 self.assertEqual(f.__call__(a=42), 42)
3607 ba = bytearray()
3608 bytearray.__init__(ba, 'abc\xbd\u20ac',
3609 encoding='latin1', errors='replace')
3610 self.assertEqual(ba, b'abc\xbd?')
3611
3612 def test_recursive_call(self):
3613 # Testing recursive __call__() by setting to instance of class...
3614 class A(object):
3615 pass
3616
3617 A.__call__ = A()
3618 with self.assertRaises(RecursionError):
3619 A()()
3620
3621 def test_delete_hook(self):
3622 # Testing __del__ hook...
3623 log = []
3624 class C(object):
3625 def __del__(self):
3626 log.append(1)
3627 c = C()
3628 self.assertEqual(log, [])
3629 del c
3630 support.gc_collect()
3631 self.assertEqual(log, [1])
3632
3633 class D(object): pass
3634 d = D()
3635 try: del d[0]
3636 except TypeError: pass
3637 else: self.fail("invalid del() didn't raise TypeError")
3638
3639 def test_hash_inheritance(self):
3640 # Testing hash of mutable subclasses...
3641
3642 class mydict(dict):
3643 pass
3644 d = mydict()
3645 try:
3646 hash(d)
3647 except TypeError:
3648 pass
3649 else:
3650 self.fail("hash() of dict subclass should fail")
3651
3652 class mylist(list):
3653 pass
3654 d = mylist()
3655 try:
3656 hash(d)
3657 except TypeError:
3658 pass
3659 else:
3660 self.fail("hash() of list subclass should fail")
3661
3662 def test_str_operations(self):
3663 try: 'a' + 5
3664 except TypeError: pass
3665 else: self.fail("'' + 5 doesn't raise TypeError")
3666
3667 try: ''.split('')
3668 except ValueError: pass
3669 else: self.fail("''.split('') doesn't raise ValueError")
3670
3671 try: ''.join([0])
3672 except TypeError: pass
3673 else: self.fail("''.join([0]) doesn't raise TypeError")
3674
3675 try: ''.rindex('5')
3676 except ValueError: pass
3677 else: self.fail("''.rindex('5') doesn't raise ValueError")
3678
3679 try: '%(n)s' % None
3680 except TypeError: pass
3681 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3682
3683 try: '%(n' % {}
3684 except ValueError: pass
3685 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3686
3687 try: '%*s' % ('abc')
3688 except TypeError: pass
3689 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3690
3691 try: '%*.*s' % ('abc', 5)
3692 except TypeError: pass
3693 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3694
3695 try: '%s' % (1, 2)
3696 except TypeError: pass
3697 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3698
3699 try: '%' % None
3700 except ValueError: pass
3701 else: self.fail("'%' % None doesn't raise ValueError")
3702
3703 self.assertEqual('534253'.isdigit(), 1)
3704 self.assertEqual('534253x'.isdigit(), 0)
3705 self.assertEqual('%c' % 5, '\x05')
3706 self.assertEqual('%c' % '5', '5')
3707
3708 def test_deepcopy_recursive(self):
3709 # Testing deepcopy of recursive objects...
3710 class Node:
3711 pass
3712 a = Node()
3713 b = Node()
3714 a.b = b
3715 b.a = a
3716 z = deepcopy(a) # This blew up before
3717
3718 def test_uninitialized_modules(self):
3719 # Testing uninitialized module objects...
3720 from types import ModuleType as M
3721 m = M.__new__(M)
3722 str(m)
3723 self.assertNotHasAttr(m, "__name__")
3724 self.assertNotHasAttr(m, "__file__")
3725 self.assertNotHasAttr(m, "foo")
3726 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
3727 m.foo = 1
3728 self.assertEqual(m.__dict__, {"foo": 1})
3729
3730 def test_funny_new(self):
3731 # Testing __new__ returning something unexpected...
3732 class C(object):
3733 def __new__(cls, arg):
3734 if isinstance(arg, str): return [1, 2, 3]
3735 elif isinstance(arg, int): return object.__new__(D)
3736 else: return object.__new__(cls)
3737 class D(C):
3738 def __init__(self, arg):
3739 self.foo = arg
3740 self.assertEqual(C("1"), [1, 2, 3])
3741 self.assertEqual(D("1"), [1, 2, 3])
3742 d = D(None)
3743 self.assertEqual(d.foo, None)
3744 d = C(1)
3745 self.assertIsInstance(d, D)
3746 self.assertEqual(d.foo, 1)
3747 d = D(1)
3748 self.assertIsInstance(d, D)
3749 self.assertEqual(d.foo, 1)
3750
3751 class C(object):
3752 @staticmethod
3753 def __new__(*args):
3754 return args
3755 self.assertEqual(C(1, 2), (C, 1, 2))
3756 class D(C):
3757 pass
3758 self.assertEqual(D(1, 2), (D, 1, 2))
3759
3760 class C(object):
3761 @classmethod
3762 def __new__(*args):
3763 return args
3764 self.assertEqual(C(1, 2), (C, C, 1, 2))
3765 class D(C):
3766 pass
3767 self.assertEqual(D(1, 2), (D, D, 1, 2))
3768
3769 def test_imul_bug(self):
3770 # Testing for __imul__ problems...
3771 # SF bug 544647
3772 class C(object):
3773 def __imul__(self, other):
3774 return (self, other)
3775 x = C()
3776 y = x
3777 y *= 1.0
3778 self.assertEqual(y, (x, 1.0))
3779 y = x
3780 y *= 2
3781 self.assertEqual(y, (x, 2))
3782 y = x
3783 y *= 3
3784 self.assertEqual(y, (x, 3))
3785 y = x
3786 y *= 1<<100
3787 self.assertEqual(y, (x, 1<<100))
3788 y = x
3789 y *= None
3790 self.assertEqual(y, (x, None))
3791 y = x
3792 y *= "foo"
3793 self.assertEqual(y, (x, "foo"))
3794
3795 def test_copy_setstate(self):
3796 # Testing that copy.*copy() correctly uses __setstate__...
3797 import copy
3798 class C(object):
3799 def __init__(self, foo=None):
3800 self.foo = foo
3801 self.__foo = foo
3802 def setfoo(self, foo=None):
3803 self.foo = foo
3804 def getfoo(self):
3805 return self.__foo
3806 def __getstate__(self):
3807 return [self.foo]
3808 def __setstate__(self_, lst):
3809 self.assertEqual(len(lst), 1)
3810 self_.__foo = self_.foo = lst[0]
3811 a = C(42)
3812 a.setfoo(24)
3813 self.assertEqual(a.foo, 24)
3814 self.assertEqual(a.getfoo(), 42)
3815 b = copy.copy(a)
3816 self.assertEqual(b.foo, 24)
3817 self.assertEqual(b.getfoo(), 24)
3818 b = copy.deepcopy(a)
3819 self.assertEqual(b.foo, 24)
3820 self.assertEqual(b.getfoo(), 24)
3821
3822 def test_slices(self):
3823 # Testing cases with slices and overridden __getitem__ ...
3824
3825 # Strings
3826 self.assertEqual("hello"[:4], "hell")
3827 self.assertEqual("hello"[slice(4)], "hell")
3828 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3829 class S(str):
3830 def __getitem__(self, x):
3831 return str.__getitem__(self, x)
3832 self.assertEqual(S("hello")[:4], "hell")
3833 self.assertEqual(S("hello")[slice(4)], "hell")
3834 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3835 # Tuples
3836 self.assertEqual((1,2,3)[:2], (1,2))
3837 self.assertEqual((1,2,3)[slice(2)], (1,2))
3838 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3839 class T(tuple):
3840 def __getitem__(self, x):
3841 return tuple.__getitem__(self, x)
3842 self.assertEqual(T((1,2,3))[:2], (1,2))
3843 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3844 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3845 # Lists
3846 self.assertEqual([1,2,3][:2], [1,2])
3847 self.assertEqual([1,2,3][slice(2)], [1,2])
3848 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3849 class L(list):
3850 def __getitem__(self, x):
3851 return list.__getitem__(self, x)
3852 self.assertEqual(L([1,2,3])[:2], [1,2])
3853 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3854 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3855 # Now do lists and __setitem__
3856 a = L([1,2,3])
3857 a[slice(1, 3)] = [3,2]
3858 self.assertEqual(a, [1,3,2])
3859 a[slice(0, 2, 1)] = [3,1]
3860 self.assertEqual(a, [3,1,2])
3861 a.__setitem__(slice(1, 3), [2,1])
3862 self.assertEqual(a, [3,2,1])
3863 a.__setitem__(slice(0, 2, 1), [2,3])
3864 self.assertEqual(a, [2,3,1])
3865
3866 def test_subtype_resurrection(self):
3867 # Testing resurrection of new-style instance...
3868
3869 class C(object):
3870 container = []
3871
3872 def __del__(self):
3873 # resurrect the instance
3874 C.container.append(self)
3875
3876 c = C()
3877 c.attr = 42
3878
3879 # The most interesting thing here is whether this blows up, due to
3880 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3881 # bug).
3882 del c
3883
3884 support.gc_collect()
3885 self.assertEqual(len(C.container), 1)
3886
3887 # Make c mortal again, so that the test framework with -l doesn't report
3888 # it as a leak.
3889 del C.__del__
3890
3891 def test_slots_trash(self):
3892 # Testing slot trash...
3893 # Deallocating deeply nested slotted trash caused stack overflows
3894 class trash(object):
3895 __slots__ = ['x']
3896 def __init__(self, x):
3897 self.x = x
3898 o = None
3899 for i in range(50000):
3900 o = trash(o)
3901 del o
3902
3903 def test_slots_multiple_inheritance(self):
3904 # SF bug 575229, multiple inheritance w/ slots dumps core
3905 class A(object):
3906 __slots__=()
3907 class B(object):
3908 pass
3909 class C(A,B) :
3910 __slots__=()
3911 if support.check_impl_detail():
3912 self.assertEqual(C.__basicsize__, B.__basicsize__)
3913 self.assertHasAttr(C, '__dict__')
3914 self.assertHasAttr(C, '__weakref__')
3915 C().x = 2
3916
3917 def test_rmul(self):
3918 # Testing correct invocation of __rmul__...
3919 # SF patch 592646
3920 class C(object):
3921 def __mul__(self, other):
3922 return "mul"
3923 def __rmul__(self, other):
3924 return "rmul"
3925 a = C()
3926 self.assertEqual(a*2, "mul")
3927 self.assertEqual(a*2.2, "mul")
3928 self.assertEqual(2*a, "rmul")
3929 self.assertEqual(2.2*a, "rmul")
3930
3931 def test_ipow(self):
3932 # Testing correct invocation of __ipow__...
3933 # [SF bug 620179]
3934 class C(object):
3935 def __ipow__(self, other):
3936 pass
3937 a = C()
3938 a **= 2
3939
3940 def test_ipow_returns_not_implemented(self):
3941 class A:
3942 def __ipow__(self, other):
3943 return NotImplemented
3944
3945 class B(A):
3946 def __rpow__(self, other):
3947 return 1
3948
3949 class C(A):
3950 def __pow__(self, other):
3951 return 2
3952 a = A()
3953 b = B()
3954 c = C()
3955
3956 a **= b
3957 self.assertEqual(a, 1)
3958
3959 c **= b
3960 self.assertEqual(c, 2)
3961
3962 def test_no_ipow(self):
3963 class B:
3964 def __rpow__(self, other):
3965 return 1
3966
3967 a = object()
3968 b = B()
3969 a **= b
3970 self.assertEqual(a, 1)
3971
3972 def test_ipow_exception_text(self):
3973 x = None
3974 with self.assertRaises(TypeError) as cm:
3975 x **= 2
3976 self.assertIn('unsupported operand type(s) for **=', str(cm.exception))
3977
3978 with self.assertRaises(TypeError) as cm:
3979 y = x ** 2
3980 self.assertIn('unsupported operand type(s) for **', str(cm.exception))
3981
3982 def test_mutable_bases(self):
3983 # Testing mutable bases...
3984
3985 # stuff that should work:
3986 class C(object):
3987 pass
3988 class C2(object):
3989 def __getattribute__(self, attr):
3990 if attr == 'a':
3991 return 2
3992 else:
3993 return super(C2, self).__getattribute__(attr)
3994 def meth(self):
3995 return 1
3996 class D(C):
3997 pass
3998 class E(D):
3999 pass
4000 d = D()
4001 e = E()
4002 D.__bases__ = (C,)
4003 D.__bases__ = (C2,)
4004 self.assertEqual(d.meth(), 1)
4005 self.assertEqual(e.meth(), 1)
4006 self.assertEqual(d.a, 2)
4007 self.assertEqual(e.a, 2)
4008 self.assertEqual(C2.__subclasses__(), [D])
4009
4010 try:
4011 del D.__bases__
4012 except (TypeError, AttributeError):
4013 pass
4014 else:
4015 self.fail("shouldn't be able to delete .__bases__")
4016
4017 try:
4018 D.__bases__ = ()
4019 except TypeError as msg:
4020 if str(msg) == "a new-style class can't have only classic bases":
4021 self.fail("wrong error message for .__bases__ = ()")
4022 else:
4023 self.fail("shouldn't be able to set .__bases__ to ()")
4024
4025 try:
4026 D.__bases__ = (D,)
4027 except TypeError:
4028 pass
4029 else:
4030 # actually, we'll have crashed by here...
4031 self.fail("shouldn't be able to create inheritance cycles")
4032
4033 try:
4034 D.__bases__ = (C, C)
4035 except TypeError:
4036 pass
4037 else:
4038 self.fail("didn't detect repeated base classes")
4039
4040 try:
4041 D.__bases__ = (E,)
4042 except TypeError:
4043 pass
4044 else:
4045 self.fail("shouldn't be able to create inheritance cycles")
4046
4047 def test_builtin_bases(self):
4048 # Make sure all the builtin types can have their base queried without
4049 # segfaulting. See issue #5787.
4050 builtin_types = [tp for tp in builtins.__dict__.values()
4051 if isinstance(tp, type)]
4052 for tp in builtin_types:
4053 object.__getattribute__(tp, "__bases__")
4054 if tp is not object:
4055 if tp is ExceptionGroup:
4056 num_bases = 2
4057 else:
4058 num_bases = 1
4059 self.assertEqual(len(tp.__bases__), num_bases, tp)
4060
4061 class L(list):
4062 pass
4063
4064 class C(object):
4065 pass
4066
4067 class D(C):
4068 pass
4069
4070 try:
4071 L.__bases__ = (dict,)
4072 except TypeError:
4073 pass
4074 else:
4075 self.fail("shouldn't turn list subclass into dict subclass")
4076
4077 try:
4078 list.__bases__ = (dict,)
4079 except TypeError:
4080 pass
4081 else:
4082 self.fail("shouldn't be able to assign to list.__bases__")
4083
4084 try:
4085 D.__bases__ = (C, list)
4086 except TypeError:
4087 pass
4088 else:
4089 self.fail("best_base calculation found wanting")
4090
4091 def test_unsubclassable_types(self):
4092 with self.assertRaises(TypeError):
4093 class X(type(None)):
4094 pass
4095 with self.assertRaises(TypeError):
4096 class X(object, type(None)):
4097 pass
4098 with self.assertRaises(TypeError):
4099 class X(type(None), object):
4100 pass
4101 class O(object):
4102 pass
4103 with self.assertRaises(TypeError):
4104 class X(O, type(None)):
4105 pass
4106 with self.assertRaises(TypeError):
4107 class X(type(None), O):
4108 pass
4109
4110 class X(object):
4111 pass
4112 with self.assertRaises(TypeError):
4113 X.__bases__ = type(None),
4114 with self.assertRaises(TypeError):
4115 X.__bases__ = object, type(None)
4116 with self.assertRaises(TypeError):
4117 X.__bases__ = type(None), object
4118 with self.assertRaises(TypeError):
4119 X.__bases__ = O, type(None)
4120 with self.assertRaises(TypeError):
4121 X.__bases__ = type(None), O
4122
4123 def test_mutable_bases_with_failing_mro(self):
4124 # Testing mutable bases with failing mro...
4125 class WorkOnce(type):
4126 def __new__(self, name, bases, ns):
4127 self.flag = 0
4128 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
4129 def mro(self):
4130 if self.flag > 0:
4131 raise RuntimeError("bozo")
4132 else:
4133 self.flag += 1
4134 return type.mro(self)
4135
4136 class WorkAlways(type):
4137 def mro(self):
4138 # this is here to make sure that .mro()s aren't called
4139 # with an exception set (which was possible at one point).
4140 # An error message will be printed in a debug build.
4141 # What's a good way to test for this?
4142 return type.mro(self)
4143
4144 class C(object):
4145 pass
4146
4147 class C2(object):
4148 pass
4149
4150 class D(C):
4151 pass
4152
4153 class E(D):
4154 pass
4155
4156 class F(D, metaclass=WorkOnce):
4157 pass
4158
4159 class G(D, metaclass=WorkAlways):
4160 pass
4161
4162 # Immediate subclasses have their mro's adjusted in alphabetical
4163 # order, so E's will get adjusted before adjusting F's fails. We
4164 # check here that E's gets restored.
4165
4166 E_mro_before = E.__mro__
4167 D_mro_before = D.__mro__
4168
4169 try:
4170 D.__bases__ = (C2,)
4171 except RuntimeError:
4172 self.assertEqual(E.__mro__, E_mro_before)
4173 self.assertEqual(D.__mro__, D_mro_before)
4174 else:
4175 self.fail("exception not propagated")
4176
4177 def test_mutable_bases_catch_mro_conflict(self):
4178 # Testing mutable bases catch mro conflict...
4179 class A(object):
4180 pass
4181
4182 class B(object):
4183 pass
4184
4185 class C(A, B):
4186 pass
4187
4188 class D(A, B):
4189 pass
4190
4191 class E(C, D):
4192 pass
4193
4194 try:
4195 C.__bases__ = (B, A)
4196 except TypeError:
4197 pass
4198 else:
4199 self.fail("didn't catch MRO conflict")
4200
4201 def test_mutable_names(self):
4202 # Testing mutable names...
4203 class C(object):
4204 pass
4205
4206 # C.__module__ could be 'test_descr' or '__main__'
4207 mod = C.__module__
4208
4209 C.__name__ = 'D'
4210 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4211
4212 C.__name__ = 'D.E'
4213 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4214
4215 def test_evil_type_name(self):
4216 # A badly placed Py_DECREF in type_set_name led to arbitrary code
4217 # execution while the type structure was not in a sane state, and a
4218 # possible segmentation fault as a result. See bug #16447.
4219 class Nasty(str):
4220 def __del__(self):
4221 C.__name__ = "other"
4222
4223 class C:
4224 pass
4225
4226 C.__name__ = Nasty("abc")
4227 C.__name__ = "normal"
4228
4229 def test_subclass_right_op(self):
4230 # Testing correct dispatch of subclass overloading __r<op>__...
4231
4232 # This code tests various cases where right-dispatch of a subclass
4233 # should be preferred over left-dispatch of a base class.
4234
4235 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4236
4237 class B(int):
4238 def __floordiv__(self, other):
4239 return "B.__floordiv__"
4240 def __rfloordiv__(self, other):
4241 return "B.__rfloordiv__"
4242
4243 self.assertEqual(B(1) // 1, "B.__floordiv__")
4244 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4245
4246 # Case 2: subclass of object; this is just the baseline for case 3
4247
4248 class C(object):
4249 def __floordiv__(self, other):
4250 return "C.__floordiv__"
4251 def __rfloordiv__(self, other):
4252 return "C.__rfloordiv__"
4253
4254 self.assertEqual(C() // 1, "C.__floordiv__")
4255 self.assertEqual(1 // C(), "C.__rfloordiv__")
4256
4257 # Case 3: subclass of new-style class; here it gets interesting
4258
4259 class D(C):
4260 def __floordiv__(self, other):
4261 return "D.__floordiv__"
4262 def __rfloordiv__(self, other):
4263 return "D.__rfloordiv__"
4264
4265 self.assertEqual(D() // C(), "D.__floordiv__")
4266 self.assertEqual(C() // D(), "D.__rfloordiv__")
4267
4268 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4269
4270 class E(C):
4271 pass
4272
4273 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4274
4275 self.assertEqual(E() // 1, "C.__floordiv__")
4276 self.assertEqual(1 // E(), "C.__rfloordiv__")
4277 self.assertEqual(E() // C(), "C.__floordiv__")
4278 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4279
4280 @support.impl_detail("testing an internal kind of method object")
4281 def test_meth_class_get(self):
4282 # Testing __get__ method of METH_CLASS C methods...
4283 # Full coverage of descrobject.c::classmethod_get()
4284
4285 # Baseline
4286 arg = [1, 2, 3]
4287 res = {1: None, 2: None, 3: None}
4288 self.assertEqual(dict.fromkeys(arg), res)
4289 self.assertEqual({}.fromkeys(arg), res)
4290
4291 # Now get the descriptor
4292 descr = dict.__dict__["fromkeys"]
4293
4294 # More baseline using the descriptor directly
4295 self.assertEqual(descr.__get__(None, dict)(arg), res)
4296 self.assertEqual(descr.__get__({})(arg), res)
4297
4298 # Now check various error cases
4299 try:
4300 descr.__get__(None, None)
4301 except TypeError:
4302 pass
4303 else:
4304 self.fail("shouldn't have allowed descr.__get__(None, None)")
4305 try:
4306 descr.__get__(42)
4307 except TypeError:
4308 pass
4309 else:
4310 self.fail("shouldn't have allowed descr.__get__(42)")
4311 try:
4312 descr.__get__(None, 42)
4313 except TypeError:
4314 pass
4315 else:
4316 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4317 try:
4318 descr.__get__(None, int)
4319 except TypeError:
4320 pass
4321 else:
4322 self.fail("shouldn't have allowed descr.__get__(None, int)")
4323
4324 def test_isinst_isclass(self):
4325 # Testing proxy isinstance() and isclass()...
4326 class Proxy(object):
4327 def __init__(self, obj):
4328 self.__obj = obj
4329 def __getattribute__(self, name):
4330 if name.startswith("_Proxy__"):
4331 return object.__getattribute__(self, name)
4332 else:
4333 return getattr(self.__obj, name)
4334 # Test with a classic class
4335 class C:
4336 pass
4337 a = C()
4338 pa = Proxy(a)
4339 self.assertIsInstance(a, C) # Baseline
4340 self.assertIsInstance(pa, C) # Test
4341 # Test with a classic subclass
4342 class D(C):
4343 pass
4344 a = D()
4345 pa = Proxy(a)
4346 self.assertIsInstance(a, C) # Baseline
4347 self.assertIsInstance(pa, C) # Test
4348 # Test with a new-style class
4349 class C(object):
4350 pass
4351 a = C()
4352 pa = Proxy(a)
4353 self.assertIsInstance(a, C) # Baseline
4354 self.assertIsInstance(pa, C) # Test
4355 # Test with a new-style subclass
4356 class D(C):
4357 pass
4358 a = D()
4359 pa = Proxy(a)
4360 self.assertIsInstance(a, C) # Baseline
4361 self.assertIsInstance(pa, C) # Test
4362
4363 def test_proxy_super(self):
4364 # Testing super() for a proxy object...
4365 class Proxy(object):
4366 def __init__(self, obj):
4367 self.__obj = obj
4368 def __getattribute__(self, name):
4369 if name.startswith("_Proxy__"):
4370 return object.__getattribute__(self, name)
4371 else:
4372 return getattr(self.__obj, name)
4373
4374 class B(object):
4375 def f(self):
4376 return "B.f"
4377
4378 class C(B):
4379 def f(self):
4380 return super(C, self).f() + "->C.f"
4381
4382 obj = C()
4383 p = Proxy(obj)
4384 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4385
4386 def test_carloverre(self):
4387 # Testing prohibition of Carlo Verre's hack...
4388 try:
4389 object.__setattr__(str, "foo", 42)
4390 except TypeError:
4391 pass
4392 else:
4393 self.fail("Carlo Verre __setattr__ succeeded!")
4394 try:
4395 object.__delattr__(str, "lower")
4396 except TypeError:
4397 pass
4398 else:
4399 self.fail("Carlo Verre __delattr__ succeeded!")
4400
4401 def test_carloverre_multi_inherit_valid(self):
4402 class A(type):
4403 def __setattr__(cls, key, value):
4404 type.__setattr__(cls, key, value)
4405
4406 class B:
4407 pass
4408
4409 class C(B, A):
4410 pass
4411
4412 obj = C('D', (object,), {})
4413 try:
4414 obj.test = True
4415 except TypeError:
4416 self.fail("setattr through direct base types should be legal")
4417
4418 def test_carloverre_multi_inherit_invalid(self):
4419 class A(type):
4420 def __setattr__(cls, key, value):
4421 object.__setattr__(cls, key, value) # this should fail!
4422
4423 class B:
4424 pass
4425
4426 class C(B, A):
4427 pass
4428
4429 obj = C('D', (object,), {})
4430 try:
4431 obj.test = True
4432 except TypeError:
4433 pass
4434 else:
4435 self.fail("setattr through indirect base types should be rejected")
4436
4437 def test_weakref_segfault(self):
4438 # Testing weakref segfault...
4439 # SF 742911
4440 import weakref
4441
4442 class Provoker:
4443 def __init__(self, referrent):
4444 self.ref = weakref.ref(referrent)
4445
4446 def __del__(self):
4447 x = self.ref()
4448
4449 class Oops(object):
4450 pass
4451
4452 o = Oops()
4453 o.whatever = Provoker(o)
4454 del o
4455
4456 @support.requires_resource('cpu')
4457 def test_wrapper_segfault(self):
4458 # SF 927248: deeply nested wrappers could cause stack overflow
4459 f = lambda:None
4460 for i in range(1000000):
4461 f = f.__call__
4462 f = None
4463
4464 def test_file_fault(self):
4465 # Testing sys.stdout is changed in getattr...
4466 class StdoutGuard:
4467 def __getattr__(self, attr):
4468 sys.stdout = sys.__stdout__
4469 raise RuntimeError(f"Premature access to sys.stdout.{attr}")
4470
4471 with redirect_stdout(StdoutGuard()):
4472 with self.assertRaises(RuntimeError):
4473 print("Oops!")
4474
4475 def test_vicious_descriptor_nonsense(self):
4476 # Testing vicious_descriptor_nonsense...
4477
4478 # A potential segfault spotted by Thomas Wouters in mail to
4479 # python-dev 2003-04-17, turned into an example & fixed by Michael
4480 # Hudson just less than four months later...
4481
4482 class Evil(object):
4483 def __hash__(self):
4484 return hash('attr')
4485 def __eq__(self, other):
4486 try:
4487 del C.attr
4488 except AttributeError:
4489 # possible race condition
4490 pass
4491 return 0
4492
4493 class Descr(object):
4494 def __get__(self, ob, type=None):
4495 return 1
4496
4497 class C(object):
4498 attr = Descr()
4499
4500 c = C()
4501 c.__dict__[Evil()] = 0
4502
4503 self.assertEqual(c.attr, 1)
4504 # this makes a crash more likely:
4505 support.gc_collect()
4506 self.assertNotHasAttr(c, 'attr')
4507
4508 def test_init(self):
4509 # SF 1155938
4510 class Foo(object):
4511 def __init__(self):
4512 return 10
4513 try:
4514 Foo()
4515 except TypeError:
4516 pass
4517 else:
4518 self.fail("did not test __init__() for None return")
4519
4520 def assertNotOrderable(self, a, b):
4521 with self.assertRaises(TypeError):
4522 a < b
4523 with self.assertRaises(TypeError):
4524 a > b
4525 with self.assertRaises(TypeError):
4526 a <= b
4527 with self.assertRaises(TypeError):
4528 a >= b
4529
4530 def test_method_wrapper(self):
4531 # Testing method-wrapper objects...
4532 # <type 'method-wrapper'> did not support any reflection before 2.5
4533 l = []
4534 self.assertTrue(l.__add__ == l.__add__)
4535 self.assertFalse(l.__add__ != l.__add__)
4536 self.assertFalse(l.__add__ == [].__add__)
4537 self.assertTrue(l.__add__ != [].__add__)
4538 self.assertFalse(l.__add__ == l.__mul__)
4539 self.assertTrue(l.__add__ != l.__mul__)
4540 self.assertNotOrderable(l.__add__, l.__add__)
4541 self.assertEqual(l.__add__.__name__, '__add__')
4542 self.assertIs(l.__add__.__self__, l)
4543 self.assertIs(l.__add__.__objclass__, list)
4544 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4545 # hash([].__add__) should not be based on hash([])
4546 hash(l.__add__)
4547
4548 def test_builtin_function_or_method(self):
4549 # Not really belonging to test_descr, but introspection and
4550 # comparison on <type 'builtin_function_or_method'> seems not
4551 # to be tested elsewhere
4552 l = []
4553 self.assertTrue(l.append == l.append)
4554 self.assertFalse(l.append != l.append)
4555 self.assertFalse(l.append == [].append)
4556 self.assertTrue(l.append != [].append)
4557 self.assertFalse(l.append == l.pop)
4558 self.assertTrue(l.append != l.pop)
4559 self.assertNotOrderable(l.append, l.append)
4560 self.assertEqual(l.append.__name__, 'append')
4561 self.assertIs(l.append.__self__, l)
4562 # self.assertIs(l.append.__objclass__, list) --- could be added?
4563 self.assertEqual(l.append.__doc__, list.append.__doc__)
4564 # hash([].append) should not be based on hash([])
4565 hash(l.append)
4566
4567 def test_special_unbound_method_types(self):
4568 # Testing objects of <type 'wrapper_descriptor'>...
4569 self.assertTrue(list.__add__ == list.__add__)
4570 self.assertFalse(list.__add__ != list.__add__)
4571 self.assertFalse(list.__add__ == list.__mul__)
4572 self.assertTrue(list.__add__ != list.__mul__)
4573 self.assertNotOrderable(list.__add__, list.__add__)
4574 self.assertEqual(list.__add__.__name__, '__add__')
4575 self.assertIs(list.__add__.__objclass__, list)
4576
4577 # Testing objects of <type 'method_descriptor'>...
4578 self.assertTrue(list.append == list.append)
4579 self.assertFalse(list.append != list.append)
4580 self.assertFalse(list.append == list.pop)
4581 self.assertTrue(list.append != list.pop)
4582 self.assertNotOrderable(list.append, list.append)
4583 self.assertEqual(list.append.__name__, 'append')
4584 self.assertIs(list.append.__objclass__, list)
4585
4586 def test_not_implemented(self):
4587 # Testing NotImplemented...
4588 # all binary methods should be able to return a NotImplemented
4589
4590 def specialmethod(self, other):
4591 return NotImplemented
4592
4593 def check(expr, x, y):
4594 with (
4595 self.subTest(expr=expr, x=x, y=y),
4596 self.assertRaises(TypeError),
4597 ):
4598 exec(expr, {'x': x, 'y': y})
4599
4600 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4601 # TypeErrors
4602 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4603 # ValueErrors instead of TypeErrors
4604 for name, expr, iexpr in [
4605 ('__add__', 'x + y', 'x += y'),
4606 ('__sub__', 'x - y', 'x -= y'),
4607 ('__mul__', 'x * y', 'x *= y'),
4608 ('__matmul__', 'x @ y', 'x @= y'),
4609 ('__truediv__', 'x / y', 'x /= y'),
4610 ('__floordiv__', 'x // y', 'x //= y'),
4611 ('__mod__', 'x % y', 'x %= y'),
4612 ('__divmod__', 'divmod(x, y)', None),
4613 ('__pow__', 'x ** y', 'x **= y'),
4614 ('__lshift__', 'x << y', 'x <<= y'),
4615 ('__rshift__', 'x >> y', 'x >>= y'),
4616 ('__and__', 'x & y', 'x &= y'),
4617 ('__or__', 'x | y', 'x |= y'),
4618 ('__xor__', 'x ^ y', 'x ^= y')]:
4619 # Defines 'left' magic method:
4620 A = type('A', (), {name: specialmethod})
4621 a = A()
4622 check(expr, a, a)
4623 check(expr, a, N1)
4624 check(expr, a, N2)
4625 # Defines 'right' magic method:
4626 rname = '__r' + name[2:]
4627 B = type('B', (), {rname: specialmethod})
4628 b = B()
4629 check(expr, b, b)
4630 check(expr, a, b)
4631 check(expr, b, a)
4632 check(expr, b, N1)
4633 check(expr, b, N2)
4634 check(expr, N1, b)
4635 check(expr, N2, b)
4636 if iexpr:
4637 check(iexpr, a, a)
4638 check(iexpr, a, N1)
4639 check(iexpr, a, N2)
4640 iname = '__i' + name[2:]
4641 C = type('C', (), {iname: specialmethod})
4642 c = C()
4643 check(iexpr, c, a)
4644 check(iexpr, c, N1)
4645 check(iexpr, c, N2)
4646
4647 def test_assign_slice(self):
4648 # ceval.c's assign_slice used to check for
4649 # tp->tp_as_sequence->sq_slice instead of
4650 # tp->tp_as_sequence->sq_ass_slice
4651
4652 class C(object):
4653 def __setitem__(self, idx, value):
4654 self.value = value
4655
4656 c = C()
4657 c[1:2] = 3
4658 self.assertEqual(c.value, 3)
4659
4660 def test_set_and_no_get(self):
4661 # See
4662 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4663 class Descr(object):
4664
4665 def __init__(self, name):
4666 self.name = name
4667
4668 def __set__(self, obj, value):
4669 obj.__dict__[self.name] = value
4670 descr = Descr("a")
4671
4672 class X(object):
4673 a = descr
4674
4675 x = X()
4676 self.assertIs(x.a, descr)
4677 x.a = 42
4678 self.assertEqual(x.a, 42)
4679
4680 # Also check type_getattro for correctness.
4681 class Meta(type):
4682 pass
4683 class X(metaclass=Meta):
4684 pass
4685 X.a = 42
4686 Meta.a = Descr("a")
4687 self.assertEqual(X.a, 42)
4688
4689 def test_getattr_hooks(self):
4690 # issue 4230
4691
4692 class Descriptor(object):
4693 counter = 0
4694 def __get__(self, obj, objtype=None):
4695 def getter(name):
4696 self.counter += 1
4697 raise AttributeError(name)
4698 return getter
4699
4700 descr = Descriptor()
4701 class A(object):
4702 __getattribute__ = descr
4703 class B(object):
4704 __getattr__ = descr
4705 class C(object):
4706 __getattribute__ = descr
4707 __getattr__ = descr
4708
4709 self.assertRaises(AttributeError, getattr, A(), "attr")
4710 self.assertEqual(descr.counter, 1)
4711 self.assertRaises(AttributeError, getattr, B(), "attr")
4712 self.assertEqual(descr.counter, 2)
4713 self.assertRaises(AttributeError, getattr, C(), "attr")
4714 self.assertEqual(descr.counter, 4)
4715
4716 class EvilGetattribute(object):
4717 # This used to segfault
4718 def __getattr__(self, name):
4719 raise AttributeError(name)
4720 def __getattribute__(self, name):
4721 del EvilGetattribute.__getattr__
4722 for i in range(5):
4723 gc.collect()
4724 raise AttributeError(name)
4725
4726 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4727
4728 def test_type___getattribute__(self):
4729 self.assertRaises(TypeError, type.__getattribute__, list, type)
4730
4731 def test_abstractmethods(self):
4732 # type pretends not to have __abstractmethods__.
4733 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4734 class meta(type):
4735 pass
4736 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
4737 class X(object):
4738 pass
4739 with self.assertRaises(AttributeError):
4740 del X.__abstractmethods__
4741
4742 def test_gh55664(self):
4743 # gh-55664: issue a warning when the
4744 # __dict__ of a class contains non-string keys
4745 with self.assertWarnsRegex(RuntimeWarning, 'MyClass'):
4746 MyClass = type('MyClass', (), {1: 2})
4747
4748 class meta(type):
4749 def __new__(mcls, name, bases, ns):
4750 ns[1] = 2
4751 return super().__new__(mcls, name, bases, ns)
4752
4753 with self.assertWarnsRegex(RuntimeWarning, 'MyClass'):
4754 MyClass = meta('MyClass', (), {})
4755
4756 def test_proxy_call(self):
4757 class FakeStr:
4758 __class__ = str
4759
4760 fake_str = FakeStr()
4761 # isinstance() reads __class__
4762 self.assertIsInstance(fake_str, str)
4763
4764 # call a method descriptor
4765 with self.assertRaises(TypeError):
4766 str.split(fake_str)
4767
4768 # call a slot wrapper descriptor
4769 with self.assertRaises(TypeError):
4770 str.__add__(fake_str, "abc")
4771
4772 def test_specialized_method_calls_check_types(self):
4773 # https://github.com/python/cpython/issues/92063
4774 class Thing:
4775 pass
4776 thing = Thing()
4777 for i in range(20):
4778 with self.assertRaises(TypeError):
4779 # CALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS
4780 list.sort(thing)
4781 for i in range(20):
4782 with self.assertRaises(TypeError):
4783 # CALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS
4784 str.split(thing)
4785 for i in range(20):
4786 with self.assertRaises(TypeError):
4787 # CALL_METHOD_DESCRIPTOR_NOARGS
4788 str.upper(thing)
4789 for i in range(20):
4790 with self.assertRaises(TypeError):
4791 # CALL_METHOD_DESCRIPTOR_FAST
4792 str.strip(thing)
4793 from collections import deque
4794 for i in range(20):
4795 with self.assertRaises(TypeError):
4796 # CALL_METHOD_DESCRIPTOR_O
4797 deque.append(thing, thing)
4798
4799 def test_repr_as_str(self):
4800 # Issue #11603: crash or infinite loop when rebinding __str__ as
4801 # __repr__.
4802 class Foo:
4803 pass
4804 Foo.__repr__ = Foo.__str__
4805 foo = Foo()
4806 self.assertRaises(RecursionError, str, foo)
4807 self.assertRaises(RecursionError, repr, foo)
4808
4809 def test_mixing_slot_wrappers(self):
4810 class X(dict):
4811 __setattr__ = dict.__setitem__
4812 __neg__ = dict.copy
4813 x = X()
4814 x.y = 42
4815 self.assertEqual(x["y"], 42)
4816 self.assertEqual(x, -x)
4817
4818 def test_wrong_class_slot_wrapper(self):
4819 # Check bpo-37619: a wrapper descriptor taken from the wrong class
4820 # should raise an exception instead of silently being ignored
4821 class A(int):
4822 __eq__ = str.__eq__
4823 __add__ = str.__add__
4824 a = A()
4825 with self.assertRaises(TypeError):
4826 a == a
4827 with self.assertRaises(TypeError):
4828 a + a
4829
4830 def test_slot_shadows_class_variable(self):
4831 with self.assertRaises(ValueError) as cm:
4832 class X:
4833 __slots__ = ["foo"]
4834 foo = None
4835 m = str(cm.exception)
4836 self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
4837
4838 def test_set_doc(self):
4839 class X:
4840 "elephant"
4841 X.__doc__ = "banana"
4842 self.assertEqual(X.__doc__, "banana")
4843
4844 with self.assertRaises(TypeError) as cm:
4845 type(list).__dict__["__doc__"].__set__(list, "blah")
4846 self.assertIn("cannot set '__doc__' attribute of immutable type 'list'", str(cm.exception))
4847
4848 with self.assertRaises(TypeError) as cm:
4849 type(X).__dict__["__doc__"].__delete__(X)
4850 self.assertIn("cannot delete '__doc__' attribute of immutable type 'X'", str(cm.exception))
4851 self.assertEqual(X.__doc__, "banana")
4852
4853 def test_qualname(self):
4854 descriptors = [str.lower, complex.real, float.real, int.__add__]
4855 types = ['method', 'member', 'getset', 'wrapper']
4856
4857 # make sure we have an example of each type of descriptor
4858 for d, n in zip(descriptors, types):
4859 self.assertEqual(type(d).__name__, n + '_descriptor')
4860
4861 for d in descriptors:
4862 qualname = d.__objclass__.__qualname__ + '.' + d.__name__
4863 self.assertEqual(d.__qualname__, qualname)
4864
4865 self.assertEqual(str.lower.__qualname__, 'str.lower')
4866 self.assertEqual(complex.real.__qualname__, 'complex.real')
4867 self.assertEqual(float.real.__qualname__, 'float.real')
4868 self.assertEqual(int.__add__.__qualname__, 'int.__add__')
4869
4870 class X:
4871 pass
4872 with self.assertRaises(TypeError):
4873 del X.__qualname__
4874
4875 self.assertRaises(TypeError, type.__dict__['__qualname__'].__set__,
4876 str, 'Oink')
4877
4878 global Y
4879 class Y:
4880 class Inside:
4881 pass
4882 self.assertEqual(Y.__qualname__, 'Y')
4883 self.assertEqual(Y.Inside.__qualname__, 'Y.Inside')
4884
4885 def test_qualname_dict(self):
4886 ns = {'__qualname__': 'some.name'}
4887 tp = type('Foo', (), ns)
4888 self.assertEqual(tp.__qualname__, 'some.name')
4889 self.assertNotIn('__qualname__', tp.__dict__)
4890 self.assertEqual(ns, {'__qualname__': 'some.name'})
4891
4892 ns = {'__qualname__': 1}
4893 self.assertRaises(TypeError, type, 'Foo', (), ns)
4894
4895 def test_cycle_through_dict(self):
4896 # See bug #1469629
4897 class X(dict):
4898 def __init__(self):
4899 dict.__init__(self)
4900 self.__dict__ = self
4901 x = X()
4902 x.attr = 42
4903 wr = weakref.ref(x)
4904 del x
4905 support.gc_collect()
4906 self.assertIsNone(wr())
4907 for o in gc.get_objects():
4908 self.assertIsNot(type(o), X)
4909
4910 def test_object_new_and_init_with_parameters(self):
4911 # See issue #1683368
4912 class OverrideNeither:
4913 pass
4914 self.assertRaises(TypeError, OverrideNeither, 1)
4915 self.assertRaises(TypeError, OverrideNeither, kw=1)
4916 class OverrideNew:
4917 def __new__(cls, foo, kw=0, *args, **kwds):
4918 return object.__new__(cls, *args, **kwds)
4919 class OverrideInit:
4920 def __init__(self, foo, kw=0, *args, **kwargs):
4921 return object.__init__(self, *args, **kwargs)
4922 class OverrideBoth(OverrideNew, OverrideInit):
4923 pass
4924 for case in OverrideNew, OverrideInit, OverrideBoth:
4925 case(1)
4926 case(1, kw=2)
4927 self.assertRaises(TypeError, case, 1, 2, 3)
4928 self.assertRaises(TypeError, case, 1, 2, foo=3)
4929
4930 def test_subclassing_does_not_duplicate_dict_descriptors(self):
4931 class Base:
4932 pass
4933 class Sub(Base):
4934 pass
4935 self.assertIn("__dict__", Base.__dict__)
4936 self.assertNotIn("__dict__", Sub.__dict__)
4937
4938 def test_bound_method_repr(self):
4939 class Foo:
4940 def method(self):
4941 pass
4942 self.assertRegex(repr(Foo().method),
4943 r"<bound method .*Foo\.method of <.*Foo object at .*>>")
4944
4945
4946 class Base:
4947 def method(self):
4948 pass
4949 class Derived1(Base):
4950 pass
4951 class Derived2(Base):
4952 def method(self):
4953 pass
4954 base = Base()
4955 derived1 = Derived1()
4956 derived2 = Derived2()
4957 super_d2 = super(Derived2, derived2)
4958 self.assertRegex(repr(base.method),
4959 r"<bound method .*Base\.method of <.*Base object at .*>>")
4960 self.assertRegex(repr(derived1.method),
4961 r"<bound method .*Base\.method of <.*Derived1 object at .*>>")
4962 self.assertRegex(repr(derived2.method),
4963 r"<bound method .*Derived2\.method of <.*Derived2 object at .*>>")
4964 self.assertRegex(repr(super_d2.method),
4965 r"<bound method .*Base\.method of <.*Derived2 object at .*>>")
4966
4967 class Foo:
4968 @classmethod
4969 def method(cls):
4970 pass
4971 foo = Foo()
4972 self.assertRegex(repr(foo.method), # access via instance
4973 r"<bound method .*Foo\.method of <class '.*Foo'>>")
4974 self.assertRegex(repr(Foo.method), # access via the class
4975 r"<bound method .*Foo\.method of <class '.*Foo'>>")
4976
4977
4978 class MyCallable:
4979 def __call__(self, arg):
4980 pass
4981 func = MyCallable() # func has no __name__ or __qualname__ attributes
4982 instance = object()
4983 method = types.MethodType(func, instance)
4984 self.assertRegex(repr(method),
4985 r"<bound method \? of <object object at .*>>")
4986 func.__name__ = "name"
4987 self.assertRegex(repr(method),
4988 r"<bound method name of <object object at .*>>")
4989 func.__qualname__ = "qualname"
4990 self.assertRegex(repr(method),
4991 r"<bound method qualname of <object object at .*>>")
4992
4993 @unittest.skipIf(_testcapi is None, 'need the _testcapi module')
4994 def test_bpo25750(self):
4995 # bpo-25750: calling a descriptor (implemented as built-in
4996 # function with METH_FASTCALL) should not crash CPython if the
4997 # descriptor deletes itself from the class.
4998 class Descr:
4999 __get__ = _testcapi.bad_get
5000
5001 class X:
5002 descr = Descr()
5003 def __new__(cls):
5004 cls.descr = None
5005 # Create this large list to corrupt some unused memory
5006 cls.lst = [2**i for i in range(10000)]
5007 X.descr
5008
5009 @support.suppress_immortalization()
5010 def test_remove_subclass(self):
5011 # bpo-46417: when the last subclass of a type is deleted,
5012 # remove_subclass() clears the internal dictionary of subclasses:
5013 # set PyTypeObject.tp_subclasses to NULL. remove_subclass() is called
5014 # when a type is deallocated.
5015 class Parent:
5016 pass
5017 self.assertEqual(Parent.__subclasses__(), [])
5018
5019 class Child(Parent):
5020 pass
5021 self.assertEqual(Parent.__subclasses__(), [Child])
5022
5023 del Child
5024 gc.collect()
5025 self.assertEqual(Parent.__subclasses__(), [])
5026
5027 def test_instance_method_get_behavior(self):
5028 # test case for gh-113157
5029
5030 class A:
5031 def meth(self):
5032 return self
5033
5034 class B:
5035 pass
5036
5037 a = A()
5038 b = B()
5039 b.meth = a.meth.__get__(b, B)
5040 self.assertEqual(b.meth(), a)
5041
5042 def test_attr_raise_through_property(self):
5043 # test case for gh-103272
5044 class A:
5045 def __getattr__(self, name):
5046 raise ValueError("FOO")
5047
5048 @property
5049 def foo(self):
5050 return self.__getattr__("asdf")
5051
5052 with self.assertRaisesRegex(ValueError, "FOO"):
5053 A().foo
5054
5055 # test case for gh-103551
5056 class B:
5057 @property
5058 def __getattr__(self, name):
5059 raise ValueError("FOO")
5060
5061 @property
5062 def foo(self):
5063 raise NotImplementedError("BAR")
5064
5065 with self.assertRaisesRegex(NotImplementedError, "BAR"):
5066 B().foo
5067
5068
5069 class DictProxyTests(unittest.TestCase):
5070 def setUp(self):
5071 class C(object):
5072 def meth(self):
5073 pass
5074 self.C = C
5075
5076 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
5077 'trace function introduces __local__')
5078 def test_iter_keys(self):
5079 # Testing dict-proxy keys...
5080 it = self.C.__dict__.keys()
5081 self.assertNotIsInstance(it, list)
5082 keys = list(it)
5083 keys.sort()
5084 self.assertEqual(keys, ['__dict__', '__doc__', '__firstlineno__',
5085 '__module__',
5086 '__static_attributes__', '__weakref__',
5087 'meth'])
5088
5089 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
5090 'trace function introduces __local__')
5091 def test_iter_values(self):
5092 # Testing dict-proxy values...
5093 it = self.C.__dict__.values()
5094 self.assertNotIsInstance(it, list)
5095 values = list(it)
5096 self.assertEqual(len(values), 7)
5097
5098 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
5099 'trace function introduces __local__')
5100 def test_iter_items(self):
5101 # Testing dict-proxy iteritems...
5102 it = self.C.__dict__.items()
5103 self.assertNotIsInstance(it, list)
5104 keys = [item[0] for item in it]
5105 keys.sort()
5106 self.assertEqual(keys, ['__dict__', '__doc__', '__firstlineno__',
5107 '__module__',
5108 '__static_attributes__', '__weakref__',
5109 'meth'])
5110
5111 def test_dict_type_with_metaclass(self):
5112 # Testing type of __dict__ when metaclass set...
5113 class B(object):
5114 pass
5115 class M(type):
5116 pass
5117 class C(metaclass=M):
5118 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
5119 pass
5120 self.assertEqual(type(C.__dict__), type(B.__dict__))
5121
5122 def test_repr(self):
5123 # Testing mappingproxy.__repr__.
5124 # We can't blindly compare with the repr of another dict as ordering
5125 # of keys and values is arbitrary and may differ.
5126 r = repr(self.C.__dict__)
5127 self.assertTrue(r.startswith('mappingproxy('), r)
5128 self.assertTrue(r.endswith(')'), r)
5129 for k, v in self.C.__dict__.items():
5130 self.assertIn('{!r}: {!r}'.format(k, v), r)
5131
5132
5133 class AAAPTypesLongInitTest(unittest.TestCase):
5134 # This is in its own TestCase so that it can be run before any other tests.
5135 # (Hence the 'AAA' in the test class name: to make it the first
5136 # item in a list sorted by name, like
5137 # unittest.TestLoader.getTestCaseNames() does.)
5138 def test_pytype_long_ready(self):
5139 # Testing SF bug 551412 ...
5140
5141 # This dumps core when SF bug 551412 isn't fixed --
5142 # but only when test_descr.py is run separately.
5143 # (That can't be helped -- as soon as PyType_Ready()
5144 # is called for PyLong_Type, the bug is gone.)
5145 class UserLong(object):
5146 def __pow__(self, *args):
5147 pass
5148 try:
5149 pow(0, UserLong(), 0)
5150 except:
5151 pass
5152
5153 # Another segfault only when run early
5154 # (before PyType_Ready(tuple) is called)
5155 type.mro(tuple)
5156
5157
5158 class MiscTests(unittest.TestCase):
5159 def test_type_lookup_mro_reference(self):
5160 # Issue #14199: _PyType_Lookup() has to keep a strong reference to
5161 # the type MRO because it may be modified during the lookup, if
5162 # __bases__ is set during the lookup for example.
5163 class MyKey(object):
5164 def __hash__(self):
5165 return hash('mykey')
5166
5167 def __eq__(self, other):
5168 X.__bases__ = (Base2,)
5169
5170 class Base(object):
5171 mykey = 'from Base'
5172 mykey2 = 'from Base'
5173
5174 class Base2(object):
5175 mykey = 'from Base2'
5176 mykey2 = 'from Base2'
5177
5178 with self.assertWarnsRegex(RuntimeWarning, 'X'):
5179 X = type('X', (Base,), {MyKey(): 5})
5180
5181 # Note that the access below uses getattr() rather than normally
5182 # accessing the attribute. That is done to avoid the bytecode
5183 # specializer activating on repeated runs of the test.
5184
5185 # mykey is read from Base
5186 self.assertEqual(getattr(X, 'mykey'), 'from Base')
5187 # mykey2 is read from Base2 because MyKey.__eq__ has set __bases__
5188 self.assertEqual(getattr(X, 'mykey2'), 'from Base2')
5189
5190
5191 class PicklingTests(unittest.TestCase):
5192
5193 def _check_reduce(self, proto, obj, args=(), kwargs={}, state=None,
5194 listitems=None, dictitems=None):
5195 if proto >= 2:
5196 reduce_value = obj.__reduce_ex__(proto)
5197 if kwargs:
5198 self.assertEqual(reduce_value[0], copyreg.__newobj_ex__)
5199 self.assertEqual(reduce_value[1], (type(obj), args, kwargs))
5200 else:
5201 self.assertEqual(reduce_value[0], copyreg.__newobj__)
5202 self.assertEqual(reduce_value[1], (type(obj),) + args)
5203 self.assertEqual(reduce_value[2], state)
5204 if listitems is not None:
5205 self.assertListEqual(list(reduce_value[3]), listitems)
5206 else:
5207 self.assertIsNone(reduce_value[3])
5208 if dictitems is not None:
5209 self.assertDictEqual(dict(reduce_value[4]), dictitems)
5210 else:
5211 self.assertIsNone(reduce_value[4])
5212 else:
5213 base_type = type(obj).__base__
5214 reduce_value = (copyreg._reconstructor,
5215 (type(obj),
5216 base_type,
5217 None if base_type is object else base_type(obj)))
5218 if state is not None:
5219 reduce_value += (state,)
5220 self.assertEqual(obj.__reduce_ex__(proto), reduce_value)
5221 self.assertEqual(obj.__reduce__(), reduce_value)
5222
5223 def test_reduce(self):
5224 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
5225 args = (-101, "spam")
5226 kwargs = {'bacon': -201, 'fish': -301}
5227 state = {'cheese': -401}
5228
5229 class C1:
5230 def __getnewargs__(self):
5231 return args
5232 obj = C1()
5233 for proto in protocols:
5234 self._check_reduce(proto, obj, args)
5235
5236 for name, value in state.items():
5237 setattr(obj, name, value)
5238 for proto in protocols:
5239 self._check_reduce(proto, obj, args, state=state)
5240
5241 class C2:
5242 def __getnewargs__(self):
5243 return "bad args"
5244 obj = C2()
5245 for proto in protocols:
5246 if proto >= 2:
5247 with self.assertRaises(TypeError):
5248 obj.__reduce_ex__(proto)
5249
5250 class C3:
5251 def __getnewargs_ex__(self):
5252 return (args, kwargs)
5253 obj = C3()
5254 for proto in protocols:
5255 if proto >= 2:
5256 self._check_reduce(proto, obj, args, kwargs)
5257
5258 class C4:
5259 def __getnewargs_ex__(self):
5260 return (args, "bad dict")
5261 class C5:
5262 def __getnewargs_ex__(self):
5263 return ("bad tuple", kwargs)
5264 class C6:
5265 def __getnewargs_ex__(self):
5266 return ()
5267 class C7:
5268 def __getnewargs_ex__(self):
5269 return "bad args"
5270 for proto in protocols:
5271 for cls in C4, C5, C6, C7:
5272 obj = cls()
5273 if proto >= 2:
5274 with self.assertRaises((TypeError, ValueError)):
5275 obj.__reduce_ex__(proto)
5276
5277 class C9:
5278 def __getnewargs_ex__(self):
5279 return (args, {})
5280 obj = C9()
5281 for proto in protocols:
5282 self._check_reduce(proto, obj, args)
5283
5284 class C10:
5285 def __getnewargs_ex__(self):
5286 raise IndexError
5287 obj = C10()
5288 for proto in protocols:
5289 if proto >= 2:
5290 with self.assertRaises(IndexError):
5291 obj.__reduce_ex__(proto)
5292
5293 class C11:
5294 def __getstate__(self):
5295 return state
5296 obj = C11()
5297 for proto in protocols:
5298 self._check_reduce(proto, obj, state=state)
5299
5300 class C12:
5301 def __getstate__(self):
5302 return "not dict"
5303 obj = C12()
5304 for proto in protocols:
5305 self._check_reduce(proto, obj, state="not dict")
5306
5307 class C13:
5308 def __getstate__(self):
5309 raise IndexError
5310 obj = C13()
5311 for proto in protocols:
5312 with self.assertRaises(IndexError):
5313 obj.__reduce_ex__(proto)
5314 if proto < 2:
5315 with self.assertRaises(IndexError):
5316 obj.__reduce__()
5317
5318 class C14:
5319 __slots__ = tuple(state)
5320 def __init__(self):
5321 for name, value in state.items():
5322 setattr(self, name, value)
5323
5324 obj = C14()
5325 for proto in protocols:
5326 if proto >= 2:
5327 self._check_reduce(proto, obj, state=(None, state))
5328 else:
5329 with self.assertRaises(TypeError):
5330 obj.__reduce_ex__(proto)
5331 with self.assertRaises(TypeError):
5332 obj.__reduce__()
5333
5334 class C15(dict):
5335 pass
5336 obj = C15({"quebec": -601})
5337 for proto in protocols:
5338 self._check_reduce(proto, obj, dictitems=dict(obj))
5339
5340 class C16(list):
5341 pass
5342 obj = C16(["yukon"])
5343 for proto in protocols:
5344 self._check_reduce(proto, obj, listitems=list(obj))
5345
5346 def test_special_method_lookup(self):
5347 protocols = range(pickle.HIGHEST_PROTOCOL + 1)
5348 class Picky:
5349 def __getstate__(self):
5350 return {}
5351
5352 def __getattr__(self, attr):
5353 if attr in ("__getnewargs__", "__getnewargs_ex__"):
5354 raise AssertionError(attr)
5355 return None
5356 for protocol in protocols:
5357 state = {} if protocol >= 2 else None
5358 self._check_reduce(protocol, Picky(), state=state)
5359
5360 def _assert_is_copy(self, obj, objcopy, msg=None):
5361 """Utility method to verify if two objects are copies of each others.
5362 """
5363 if msg is None:
5364 msg = "{!r} is not a copy of {!r}".format(obj, objcopy)
5365 if type(obj).__repr__ is object.__repr__:
5366 # We have this limitation for now because we use the object's repr
5367 # to help us verify that the two objects are copies. This allows
5368 # us to delegate the non-generic verification logic to the objects
5369 # themselves.
5370 raise ValueError("object passed to _assert_is_copy must " +
5371 "override the __repr__ method.")
5372 self.assertIsNot(obj, objcopy, msg=msg)
5373 self.assertIs(type(obj), type(objcopy), msg=msg)
5374 if hasattr(obj, '__dict__'):
5375 self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg)
5376 self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg)
5377 if hasattr(obj, '__slots__'):
5378 self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg)
5379 for slot in obj.__slots__:
5380 self.assertEqual(
5381 hasattr(obj, slot), hasattr(objcopy, slot), msg=msg)
5382 self.assertEqual(getattr(obj, slot, None),
5383 getattr(objcopy, slot, None), msg=msg)
5384 self.assertEqual(repr(obj), repr(objcopy), msg=msg)
5385
5386 @staticmethod
5387 def _generate_pickle_copiers():
5388 """Utility method to generate the many possible pickle configurations.
5389 """
5390 class PickleCopier:
5391 "This class copies object using pickle."
5392 def __init__(self, proto, dumps, loads):
5393 self.proto = proto
5394 self.dumps = dumps
5395 self.loads = loads
5396 def copy(self, obj):
5397 return self.loads(self.dumps(obj, self.proto))
5398 def __repr__(self):
5399 # We try to be as descriptive as possible here since this is
5400 # the string which we will allow us to tell the pickle
5401 # configuration we are using during debugging.
5402 return ("PickleCopier(proto={}, dumps={}.{}, loads={}.{})"
5403 .format(self.proto,
5404 self.dumps.__module__, self.dumps.__qualname__,
5405 self.loads.__module__, self.loads.__qualname__))
5406 return (PickleCopier(*args) for args in
5407 itertools.product(range(pickle.HIGHEST_PROTOCOL + 1),
5408 {pickle.dumps, pickle._dumps},
5409 {pickle.loads, pickle._loads}))
5410
5411 def test_pickle_slots(self):
5412 # Tests pickling of classes with __slots__.
5413
5414 # Pickling of classes with __slots__ but without __getstate__ should
5415 # fail (if using protocol 0 or 1)
5416 global C
5417 class C:
5418 __slots__ = ['a']
5419 with self.assertRaises(TypeError):
5420 pickle.dumps(C(), 0)
5421
5422 global D
5423 class D(C):
5424 pass
5425 with self.assertRaises(TypeError):
5426 pickle.dumps(D(), 0)
5427
5428 class C:
5429 "A class with __getstate__ and __setstate__ implemented."
5430 __slots__ = ['a']
5431 def __getstate__(self):
5432 state = getattr(self, '__dict__', {}).copy()
5433 for cls in type(self).__mro__:
5434 for slot in cls.__dict__.get('__slots__', ()):
5435 try:
5436 state[slot] = getattr(self, slot)
5437 except AttributeError:
5438 pass
5439 return state
5440 def __setstate__(self, state):
5441 for k, v in state.items():
5442 setattr(self, k, v)
5443 def __repr__(self):
5444 return "%s()<%r>" % (type(self).__name__, self.__getstate__())
5445
5446 class D(C):
5447 "A subclass of a class with slots."
5448 pass
5449
5450 global E
5451 class E(C):
5452 "A subclass with an extra slot."
5453 __slots__ = ['b']
5454
5455 # Now it should work
5456 for pickle_copier in self._generate_pickle_copiers():
5457 with self.subTest(pickle_copier=pickle_copier):
5458 x = C()
5459 y = pickle_copier.copy(x)
5460 self._assert_is_copy(x, y)
5461
5462 x.a = 42
5463 y = pickle_copier.copy(x)
5464 self._assert_is_copy(x, y)
5465
5466 x = D()
5467 x.a = 42
5468 x.b = 100
5469 y = pickle_copier.copy(x)
5470 self._assert_is_copy(x, y)
5471
5472 x = E()
5473 x.a = 42
5474 x.b = "foo"
5475 y = pickle_copier.copy(x)
5476 self._assert_is_copy(x, y)
5477
5478 def test_reduce_copying(self):
5479 # Tests pickling and copying new-style classes and objects.
5480 global C1
5481 class C1:
5482 "The state of this class is copyable via its instance dict."
5483 ARGS = (1, 2)
5484 NEED_DICT_COPYING = True
5485 def __init__(self, a, b):
5486 super().__init__()
5487 self.a = a
5488 self.b = b
5489 def __repr__(self):
5490 return "C1(%r, %r)" % (self.a, self.b)
5491
5492 global C2
5493 class C2(list):
5494 "A list subclass copyable via __getnewargs__."
5495 ARGS = (1, 2)
5496 NEED_DICT_COPYING = False
5497 def __new__(cls, a, b):
5498 self = super().__new__(cls)
5499 self.a = a
5500 self.b = b
5501 return self
5502 def __init__(self, *args):
5503 super().__init__()
5504 # This helps testing that __init__ is not called during the
5505 # unpickling process, which would cause extra appends.
5506 self.append("cheese")
5507 @classmethod
5508 def __getnewargs__(cls):
5509 return cls.ARGS
5510 def __repr__(self):
5511 return "C2(%r, %r)<%r>" % (self.a, self.b, list(self))
5512
5513 global C3
5514 class C3(list):
5515 "A list subclass copyable via __getstate__."
5516 ARGS = (1, 2)
5517 NEED_DICT_COPYING = False
5518 def __init__(self, a, b):
5519 self.a = a
5520 self.b = b
5521 # This helps testing that __init__ is not called during the
5522 # unpickling process, which would cause extra appends.
5523 self.append("cheese")
5524 @classmethod
5525 def __getstate__(cls):
5526 return cls.ARGS
5527 def __setstate__(self, state):
5528 a, b = state
5529 self.a = a
5530 self.b = b
5531 def __repr__(self):
5532 return "C3(%r, %r)<%r>" % (self.a, self.b, list(self))
5533
5534 global C4
5535 class C4(int):
5536 "An int subclass copyable via __getnewargs__."
5537 ARGS = ("hello", "world", 1)
5538 NEED_DICT_COPYING = False
5539 def __new__(cls, a, b, value):
5540 self = super().__new__(cls, value)
5541 self.a = a
5542 self.b = b
5543 return self
5544 @classmethod
5545 def __getnewargs__(cls):
5546 return cls.ARGS
5547 def __repr__(self):
5548 return "C4(%r, %r)<%r>" % (self.a, self.b, int(self))
5549
5550 global C5
5551 class C5(int):
5552 "An int subclass copyable via __getnewargs_ex__."
5553 ARGS = (1, 2)
5554 KWARGS = {'value': 3}
5555 NEED_DICT_COPYING = False
5556 def __new__(cls, a, b, *, value=0):
5557 self = super().__new__(cls, value)
5558 self.a = a
5559 self.b = b
5560 return self
5561 @classmethod
5562 def __getnewargs_ex__(cls):
5563 return (cls.ARGS, cls.KWARGS)
5564 def __repr__(self):
5565 return "C5(%r, %r)<%r>" % (self.a, self.b, int(self))
5566
5567 test_classes = (C1, C2, C3, C4, C5)
5568 # Testing copying through pickle
5569 pickle_copiers = self._generate_pickle_copiers()
5570 for cls, pickle_copier in itertools.product(test_classes, pickle_copiers):
5571 with self.subTest(cls=cls, pickle_copier=pickle_copier):
5572 kwargs = getattr(cls, 'KWARGS', {})
5573 obj = cls(*cls.ARGS, **kwargs)
5574 proto = pickle_copier.proto
5575 objcopy = pickle_copier.copy(obj)
5576 self._assert_is_copy(obj, objcopy)
5577 # For test classes that supports this, make sure we didn't go
5578 # around the reduce protocol by simply copying the attribute
5579 # dictionary. We clear attributes using the previous copy to
5580 # not mutate the original argument.
5581 if proto >= 2 and not cls.NEED_DICT_COPYING:
5582 objcopy.__dict__.clear()
5583 objcopy2 = pickle_copier.copy(objcopy)
5584 self._assert_is_copy(obj, objcopy2)
5585
5586 # Testing copying through copy.deepcopy()
5587 for cls in test_classes:
5588 with self.subTest(cls=cls):
5589 kwargs = getattr(cls, 'KWARGS', {})
5590 obj = cls(*cls.ARGS, **kwargs)
5591 objcopy = deepcopy(obj)
5592 self._assert_is_copy(obj, objcopy)
5593 # For test classes that supports this, make sure we didn't go
5594 # around the reduce protocol by simply copying the attribute
5595 # dictionary. We clear attributes using the previous copy to
5596 # not mutate the original argument.
5597 if not cls.NEED_DICT_COPYING:
5598 objcopy.__dict__.clear()
5599 objcopy2 = deepcopy(objcopy)
5600 self._assert_is_copy(obj, objcopy2)
5601
5602 def test_issue24097(self):
5603 # Slot name is freed inside __getattr__ and is later used.
5604 class S(str): # Not interned
5605 pass
5606 class A:
5607 __slotnames__ = [S('spam')]
5608 def __getattr__(self, attr):
5609 if attr == 'spam':
5610 A.__slotnames__[:] = [S('spam')]
5611 return 42
5612 else:
5613 raise AttributeError
5614
5615 import copyreg
5616 expected = (copyreg.__newobj__, (A,), (None, {'spam': 42}), None, None)
5617 self.assertEqual(A().__reduce_ex__(2), expected) # Shouldn't crash
5618
5619 def test_object_reduce(self):
5620 # Issue #29914
5621 # __reduce__() takes no arguments
5622 object().__reduce__()
5623 with self.assertRaises(TypeError):
5624 object().__reduce__(0)
5625 # __reduce_ex__() takes one integer argument
5626 object().__reduce_ex__(0)
5627 with self.assertRaises(TypeError):
5628 object().__reduce_ex__()
5629 with self.assertRaises(TypeError):
5630 object().__reduce_ex__(None)
5631
5632
5633 class SharedKeyTests(unittest.TestCase):
5634
5635 @support.cpython_only
5636 def test_subclasses(self):
5637 # Verify that subclasses can share keys (per PEP 412)
5638 class A:
5639 pass
5640 class B(A):
5641 pass
5642
5643 #Shrink keys by repeatedly creating instances
5644 [(A(), B()) for _ in range(30)]
5645
5646 a, b = A(), B()
5647 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5648 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({"a":1}))
5649 # Initial hash table can contain only one or two elements.
5650 # Set 6 attributes to cause internal resizing.
5651 a.x, a.y, a.z, a.w, a.v, a.u = range(6)
5652 self.assertNotEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b)))
5653 a2 = A()
5654 self.assertGreater(sys.getsizeof(vars(a)), sys.getsizeof(vars(a2)))
5655 self.assertLess(sys.getsizeof(vars(a2)), sys.getsizeof({"a":1}))
5656 self.assertLess(sys.getsizeof(vars(b)), sys.getsizeof({"a":1}))
5657
5658
5659 class DebugHelperMeta(type):
5660 """
5661 Sets default __doc__ and simplifies repr() output.
5662 """
5663 def __new__(mcls, name, bases, attrs):
5664 if attrs.get('__doc__') is None:
5665 attrs['__doc__'] = name # helps when debugging with gdb
5666 return type.__new__(mcls, name, bases, attrs)
5667 def __repr__(cls):
5668 return repr(cls.__name__)
5669
5670
5671 class MroTest(unittest.TestCase):
5672 """
5673 Regressions for some bugs revealed through
5674 mcsl.mro() customization (typeobject.c: mro_internal()) and
5675 cls.__bases__ assignment (typeobject.c: type_set_bases()).
5676 """
5677
5678 def setUp(self):
5679 self.step = 0
5680 self.ready = False
5681
5682 def step_until(self, limit):
5683 ret = (self.step < limit)
5684 if ret:
5685 self.step += 1
5686 return ret
5687
5688 def test_incomplete_set_bases_on_self(self):
5689 """
5690 type_set_bases must be aware that type->tp_mro can be NULL.
5691 """
5692 class M(DebugHelperMeta):
5693 def mro(cls):
5694 if self.step_until(1):
5695 assert cls.__mro__ is None
5696 cls.__bases__ += ()
5697
5698 return type.mro(cls)
5699
5700 class A(metaclass=M):
5701 pass
5702
5703 def test_reent_set_bases_on_base(self):
5704 """
5705 Deep reentrancy must not over-decref old_mro.
5706 """
5707 class M(DebugHelperMeta):
5708 def mro(cls):
5709 if cls.__mro__ is not None and cls.__name__ == 'B':
5710 # 4-5 steps are usually enough to make it crash somewhere
5711 if self.step_until(10):
5712 A.__bases__ += ()
5713
5714 return type.mro(cls)
5715
5716 class A(metaclass=M):
5717 pass
5718 class B(A):
5719 pass
5720 B.__bases__ += ()
5721
5722 def test_reent_set_bases_on_direct_base(self):
5723 """
5724 Similar to test_reent_set_bases_on_base, but may crash differently.
5725 """
5726 class M(DebugHelperMeta):
5727 def mro(cls):
5728 base = cls.__bases__[0]
5729 if base is not object:
5730 if self.step_until(5):
5731 base.__bases__ += ()
5732
5733 return type.mro(cls)
5734
5735 class A(metaclass=M):
5736 pass
5737 class B(A):
5738 pass
5739 class C(B):
5740 pass
5741
5742 def test_reent_set_bases_tp_base_cycle(self):
5743 """
5744 type_set_bases must check for an inheritance cycle not only through
5745 MRO of the type, which may be not yet updated in case of reentrance,
5746 but also through tp_base chain, which is assigned before diving into
5747 inner calls to mro().
5748
5749 Otherwise, the following snippet can loop forever:
5750 do {
5751 // ...
5752 type = type->tp_base;
5753 } while (type != NULL);
5754
5755 Functions that rely on tp_base (like solid_base and PyType_IsSubtype)
5756 would not be happy in that case, causing a stack overflow.
5757 """
5758 class M(DebugHelperMeta):
5759 def mro(cls):
5760 if self.ready:
5761 if cls.__name__ == 'B1':
5762 B2.__bases__ = (B1,)
5763 if cls.__name__ == 'B2':
5764 B1.__bases__ = (B2,)
5765 return type.mro(cls)
5766
5767 class A(metaclass=M):
5768 pass
5769 class B1(A):
5770 pass
5771 class B2(A):
5772 pass
5773
5774 self.ready = True
5775 with self.assertRaises(TypeError):
5776 B1.__bases__ += ()
5777
5778 def test_tp_subclasses_cycle_in_update_slots(self):
5779 """
5780 type_set_bases must check for reentrancy upon finishing its job
5781 by updating tp_subclasses of old/new bases of the type.
5782 Otherwise, an implicit inheritance cycle through tp_subclasses
5783 can break functions that recurse on elements of that field
5784 (like recurse_down_subclasses and mro_hierarchy) eventually
5785 leading to a stack overflow.
5786 """
5787 class M(DebugHelperMeta):
5788 def mro(cls):
5789 if self.ready and cls.__name__ == 'C':
5790 self.ready = False
5791 C.__bases__ = (B2,)
5792 return type.mro(cls)
5793
5794 class A(metaclass=M):
5795 pass
5796 class B1(A):
5797 pass
5798 class B2(A):
5799 pass
5800 class C(A):
5801 pass
5802
5803 self.ready = True
5804 C.__bases__ = (B1,)
5805 B1.__bases__ = (C,)
5806
5807 self.assertEqual(C.__bases__, (B2,))
5808 self.assertEqual(B2.__subclasses__(), [C])
5809 self.assertEqual(B1.__subclasses__(), [])
5810
5811 self.assertEqual(B1.__bases__, (C,))
5812 self.assertEqual(C.__subclasses__(), [B1])
5813
5814 def test_tp_subclasses_cycle_error_return_path(self):
5815 """
5816 The same as test_tp_subclasses_cycle_in_update_slots, but tests
5817 a code path executed on error (goto bail).
5818 """
5819 class E(Exception):
5820 pass
5821 class M(DebugHelperMeta):
5822 def mro(cls):
5823 if self.ready and cls.__name__ == 'C':
5824 if C.__bases__ == (B2,):
5825 self.ready = False
5826 else:
5827 C.__bases__ = (B2,)
5828 raise E
5829 return type.mro(cls)
5830
5831 class A(metaclass=M):
5832 pass
5833 class B1(A):
5834 pass
5835 class B2(A):
5836 pass
5837 class C(A):
5838 pass
5839
5840 self.ready = True
5841 with self.assertRaises(E):
5842 C.__bases__ = (B1,)
5843 B1.__bases__ = (C,)
5844
5845 self.assertEqual(C.__bases__, (B2,))
5846 self.assertEqual(C.__mro__, tuple(type.mro(C)))
5847
5848 def test_incomplete_extend(self):
5849 """
5850 Extending an uninitialized type with type->tp_mro == NULL must
5851 throw a reasonable TypeError exception, instead of failing
5852 with PyErr_BadInternalCall.
5853 """
5854 class M(DebugHelperMeta):
5855 def mro(cls):
5856 if cls.__mro__ is None and cls.__name__ != 'X':
5857 with self.assertRaises(TypeError):
5858 class X(cls):
5859 pass
5860
5861 return type.mro(cls)
5862
5863 class A(metaclass=M):
5864 pass
5865
5866 def test_incomplete_super(self):
5867 """
5868 Attribute lookup on a super object must be aware that
5869 its target type can be uninitialized (type->tp_mro == NULL).
5870 """
5871 class M(DebugHelperMeta):
5872 def mro(cls):
5873 if cls.__mro__ is None:
5874 with self.assertRaises(AttributeError):
5875 super(cls, cls).xxx
5876
5877 return type.mro(cls)
5878
5879 class A(metaclass=M):
5880 pass
5881
5882 def test_disappearing_custom_mro(self):
5883 """
5884 gh-92112: A custom mro() returning a result conflicting with
5885 __bases__ and deleting itself caused a double free.
5886 """
5887 class B:
5888 pass
5889
5890 class M(DebugHelperMeta):
5891 def mro(cls):
5892 del M.mro
5893 return (B,)
5894
5895 with self.assertRaises(TypeError):
5896 class A(metaclass=M):
5897 pass
5898
5899
5900 if __name__ == "__main__":
5901 unittest.main()