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