Debian Codegraph @

lib-python/3/test/test_descr.py

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