1import builtins 2import copyreg 3import gc 4import itertools 5import math 6import pickle 7import random 8import string 9import sys 10import types 11import unittest 12import warnings 13import weakref 14 15from copy import deepcopy 16from contextlib import redirect_stdout 17from test import support 18 19try: 20 import _testcapi 21except ImportError: 22 _testcapi = None 23 24 25class 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 399class 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 986order (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'): 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__': "f docstring", 1591 '__module__': __name__, 1592 '__name__': 'f', 1593 '__qualname__': f.__qualname__} 1594 self.assertEqual(cm.__dict__, cm_dict) 1595 1596 cm.x = 42 1597 self.assertEqual(cm.x, 42) 1598 self.assertEqual(cm.__dict__, {"x" : 42, **cm_dict}) 1599 del cm.x 1600 self.assertNotHasAttr(cm, "x") 1601 1602 @support.refcount_test 1603 def test_refleaks_in_classmethod___init__(self): 1604 gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount') 1605 cm = classmethod(None) 1606 refs_before = gettotalrefcount() 1607 for i in range(100): 1608 cm.__init__(None) 1609 self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10) 1610 1611 @support.impl_detail("the module 'xxsubtype' is internal") 1612 def test_classmethods_in_c(self): 1613 # Testing C-based class methods... 1614 import xxsubtype as spam 1615 a = (1, 2, 3) 1616 d = {'abc': 123} 1617 x, a1, d1 = spam.spamlist.classmeth(*a, **d) 1618 self.assertEqual(x, spam.spamlist) 1619 self.assertEqual(a, a1) 1620 self.assertEqual(d, d1) 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 spam_cm = spam.spamlist.__dict__['classmeth'] 1626 x2, a2, d2 = spam_cm(spam.spamlist, *a, **d) 1627 self.assertEqual(x2, spam.spamlist) 1628 self.assertEqual(a2, a1) 1629 self.assertEqual(d2, d1) 1630 class SubSpam(spam.spamlist): pass 1631 x2, a2, d2 = spam_cm(SubSpam, *a, **d) 1632 self.assertEqual(x2, SubSpam) 1633 self.assertEqual(a2, a1) 1634 self.assertEqual(d2, d1) 1635 1636 with self.assertRaises(TypeError) as cm: 1637 spam_cm() 1638 self.assertEqual( 1639 str(cm.exception), 1640 "descriptor 'classmeth' of 'xxsubtype.spamlist' " 1641 "object needs an argument") 1642 1643 with self.assertRaises(TypeError) as cm: 1644 spam_cm(spam.spamlist()) 1645 self.assertEqual( 1646 str(cm.exception), 1647 "descriptor 'classmeth' for type 'xxsubtype.spamlist' " 1648 "needs a type, not a 'xxsubtype.spamlist' as arg 2") 1649 1650 with self.assertRaises(TypeError) as cm: 1651 spam_cm(list) 1652 expected_errmsg = ( 1653 "descriptor 'classmeth' requires a subtype of 'xxsubtype.spamlist' " 1654 "but received 'list'") 1655 self.assertEqual(str(cm.exception), expected_errmsg) 1656 1657 with self.assertRaises(TypeError) as cm: 1658 spam_cm.__get__(None, list) 1659 self.assertEqual(str(cm.exception), expected_errmsg) 1660 1661 def test_staticmethods(self): 1662 # Testing static methods... 1663 class C(object): 1664 def foo(*a): return a 1665 goo = staticmethod(foo) 1666 c = C() 1667 self.assertEqual(C.goo(1), (1,)) 1668 self.assertEqual(c.goo(1), (1,)) 1669 self.assertEqual(c.foo(1), (c, 1,)) 1670 class D(C): 1671 pass 1672 d = D() 1673 self.assertEqual(D.goo(1), (1,)) 1674 self.assertEqual(d.goo(1), (1,)) 1675 self.assertEqual(d.foo(1), (d, 1)) 1676 self.assertEqual(D.foo(d, 1), (d, 1)) 1677 sm = staticmethod(None) 1678 self.assertEqual(sm.__dict__, {'__doc__': None}) 1679 sm.x = 42 1680 self.assertEqual(sm.x, 42) 1681 self.assertEqual(sm.__dict__, {"x" : 42, '__doc__': None}) 1682 del sm.x 1683 self.assertNotHasAttr(sm, "x") 1684 1685 @support.refcount_test 1686 def test_refleaks_in_staticmethod___init__(self): 1687 gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount') 1688 sm = staticmethod(None) 1689 refs_before = gettotalrefcount() 1690 for i in range(100): 1691 sm.__init__(None) 1692 self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10) 1693 1694 @support.impl_detail("the module 'xxsubtype' is internal") 1695 def test_staticmethods_in_c(self): 1696 # Testing C-based static methods... 1697 import xxsubtype as spam 1698 a = (1, 2, 3) 1699 d = {"abc": 123} 1700 x, a1, d1 = spam.spamlist.staticmeth(*a, **d) 1701 self.assertEqual(x, None) 1702 self.assertEqual(a, a1) 1703 self.assertEqual(d, d1) 1704 x, a1, d2 = spam.spamlist().staticmeth(*a, **d) 1705 self.assertEqual(x, None) 1706 self.assertEqual(a, a1) 1707 self.assertEqual(d, d1) 1708 1709 def test_classic(self): 1710 # Testing classic classes... 1711 class C: 1712 def foo(*a): return a 1713 goo = classmethod(foo) 1714 c = C() 1715 self.assertEqual(C.goo(1), (C, 1)) 1716 self.assertEqual(c.goo(1), (C, 1)) 1717 self.assertEqual(c.foo(1), (c, 1)) 1718 class D(C): 1719 pass 1720 d = D() 1721 self.assertEqual(D.goo(1), (D, 1)) 1722 self.assertEqual(d.goo(1), (D, 1)) 1723 self.assertEqual(d.foo(1), (d, 1)) 1724 self.assertEqual(D.foo(d, 1), (d, 1)) 1725 class E: # *not* subclassing from C 1726 foo = C.foo 1727 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound 1728 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method ")) 1729 1730 def test_compattr(self): 1731 # Testing computed attributes... 1732 class C(object): 1733 class computed_attribute(object): 1734 def __init__(self, get, set=None, delete=None): 1735 self.__get = get 1736 self.__set = set 1737 self.__delete = delete 1738 def __get__(self, obj, type=None): 1739 return self.__get(obj) 1740 def __set__(self, obj, value): 1741 return self.__set(obj, value) 1742 def __delete__(self, obj): 1743 return self.__delete(obj) 1744 def __init__(self): 1745 self.__x = 0 1746 def __get_x(self): 1747 x = self.__x 1748 self.__x = x+1 1749 return x 1750 def __set_x(self, x): 1751 self.__x = x 1752 def __delete_x(self): 1753 del self.__x 1754 x = computed_attribute(__get_x, __set_x, __delete_x) 1755 a = C() 1756 self.assertEqual(a.x, 0) 1757 self.assertEqual(a.x, 1) 1758 a.x = 10 1759 self.assertEqual(a.x, 10) 1760 self.assertEqual(a.x, 11) 1761 del a.x 1762 self.assertNotHasAttr(a, 'x') 1763 1764 def test_newslots(self): 1765 # Testing __new__ slot override... 1766 class C(list): 1767 def __new__(cls): 1768 self = list.__new__(cls) 1769 self.foo = 1 1770 return self 1771 def __init__(self): 1772 self.foo = self.foo + 2 1773 a = C() 1774 self.assertEqual(a.foo, 3) 1775 self.assertEqual(a.__class__, C) 1776 class D(C): 1777 pass 1778 b = D() 1779 self.assertEqual(b.foo, 3) 1780 self.assertEqual(b.__class__, D) 1781 1782 @unittest.expectedFailure 1783 def test_bad_new(self): 1784 self.assertRaises(TypeError, object.__new__) 1785 self.assertRaises(TypeError, object.__new__, '') 1786 self.assertRaises(TypeError, list.__new__, object) 1787 self.assertRaises(TypeError, object.__new__, list) 1788 class C(object): 1789 __new__ = list.__new__ 1790 self.assertRaises(TypeError, C) 1791 class C(list): 1792 __new__ = object.__new__ 1793 self.assertRaises(TypeError, C) 1794 1795 def test_object_new(self): 1796 class A(object): 1797 pass 1798 object.__new__(A) 1799 self.assertRaises(TypeError, object.__new__, A, 5) 1800 object.__init__(A()) 1801 self.assertRaises(TypeError, object.__init__, A(), 5) 1802 1803 class A(object): 1804 def __init__(self, foo): 1805 self.foo = foo 1806 object.__new__(A) 1807 object.__new__(A, 5) 1808 object.__init__(A(3)) 1809 self.assertRaises(TypeError, object.__init__, A(3), 5) 1810 1811 class A(object): 1812 def __new__(cls, foo): 1813 return object.__new__(cls) 1814 object.__new__(A) 1815 self.assertRaises(TypeError, object.__new__, A, 5) 1816 object.__init__(A(3)) 1817 object.__init__(A(3), 5) 1818 1819 class A(object): 1820 def __new__(cls, foo): 1821 return object.__new__(cls) 1822 def __init__(self, foo): 1823 self.foo = foo 1824 object.__new__(A) 1825 self.assertRaises(TypeError, object.__new__, A, 5) 1826 object.__init__(A(3)) 1827 self.assertRaises(TypeError, object.__init__, A(3), 5) 1828 1829 @unittest.expectedFailure 1830 def test_restored_object_new(self): 1831 class A(object): 1832 def __new__(cls, *args, **kwargs): 1833 raise AssertionError 1834 self.assertRaises(AssertionError, A) 1835 class B(A): 1836 __new__ = object.__new__ 1837 def __init__(self, foo): 1838 self.foo = foo 1839 with warnings.catch_warnings(): 1840 warnings.simplefilter('error', DeprecationWarning) 1841 b = B(3) 1842 self.assertEqual(b.foo, 3) 1843 self.assertEqual(b.__class__, B) 1844 del B.__new__ 1845 self.assertRaises(AssertionError, B) 1846 del A.__new__ 1847 with warnings.catch_warnings(): 1848 warnings.simplefilter('error', DeprecationWarning) 1849 b = B(3) 1850 self.assertEqual(b.foo, 3) 1851 self.assertEqual(b.__class__, B) 1852 1853 def test_altmro(self): 1854 # Testing mro() and overriding it... 1855 class A(object): 1856 def f(self): return "A" 1857 class B(A): 1858 pass 1859 class C(A): 1860 def f(self): return "C" 1861 class D(B, C): 1862 pass 1863 self.assertEqual(A.mro(), [A, object]) 1864 self.assertEqual(A.__mro__, (A, object)) 1865 self.assertEqual(B.mro(), [B, A, object]) 1866 self.assertEqual(B.__mro__, (B, A, object)) 1867 self.assertEqual(C.mro(), [C, A, object]) 1868 self.assertEqual(C.__mro__, (C, A, object)) 1869 self.assertEqual(D.mro(), [D, B, C, A, object]) 1870 self.assertEqual(D.__mro__, (D, B, C, A, object)) 1871 self.assertEqual(D().f(), "C") 1872 1873 class PerverseMetaType(type): 1874 def mro(cls): 1875 L = type.mro(cls) 1876 L.reverse() 1877 return L 1878 class X(D,B,C,A, metaclass=PerverseMetaType): 1879 pass 1880 self.assertEqual(X.__mro__, (object, A, C, B, D, X)) 1881 self.assertEqual(X().f(), "A") 1882 1883 try: 1884 class _metaclass(type): 1885 def mro(self): 1886 return [self, dict, object] 1887 class X(object, metaclass=_metaclass): 1888 pass 1889 # In CPython, the class creation above already raises 1890 # TypeError, as a protection against the fact that 1891 # instances of X would segfault it. In other Python 1892 # implementations it would be ok to let the class X 1893 # be created, but instead get a clean TypeError on the 1894 # __setitem__ below. 1895 x = object.__new__(X) 1896 x[5] = 6 1897 except TypeError: 1898 pass 1899 else: 1900 self.fail("devious mro() return not caught") 1901 1902 try: 1903 class _metaclass(type): 1904 def mro(self): 1905 return [1] 1906 class X(object, metaclass=_metaclass): 1907 pass 1908 except TypeError: 1909 pass 1910 else: 1911 self.fail("non-class mro() return not caught") 1912 1913 try: 1914 class _metaclass(type): 1915 def mro(self): 1916 return 1 1917 class X(object, metaclass=_metaclass): 1918 pass 1919 except TypeError: 1920 pass 1921 else: 1922 self.fail("non-sequence mro() return not caught") 1923 1924 def test_overloading(self): 1925 # Testing operator overloading... 1926 1927 class B(object): 1928 "Intermediate class because object doesn't have a __setattr__" 1929 1930 class C(B): 1931 def __getattr__(self, name): 1932 if name == "foo": 1933 return ("getattr", name) 1934 else: 1935 raise AttributeError 1936 def __setattr__(self, name, value): 1937 if name == "foo": 1938 self.setattr = (name, value) 1939 else: 1940 return B.__setattr__(self, name, value) 1941 def __delattr__(self, name): 1942 if name == "foo": 1943 self.delattr = name 1944 else: 1945 return B.__delattr__(self, name) 1946 1947 def __getitem__(self, key): 1948 return ("getitem", key) 1949 def __setitem__(self, key, value): 1950 self.setitem = (key, value) 1951 def __delitem__(self, key): 1952 self.delitem = key 1953 1954 a = C() 1955 self.assertEqual(a.foo, ("getattr", "foo")) 1956 a.foo = 12 1957 self.assertEqual(a.setattr, ("foo", 12)) 1958 del a.foo 1959 self.assertEqual(a.delattr, "foo") 1960 1961 self.assertEqual(a[12], ("getitem", 12)) 1962 a[12] = 21 1963 self.assertEqual(a.setitem, (12, 21)) 1964 del a[12] 1965 self.assertEqual(a.delitem, 12) 1966 1967 self.assertEqual(a[0:10], ("getitem", slice(0, 10))) 1968 a[0:10] = "foo" 1969 self.assertEqual(a.setitem, (slice(0, 10), "foo")) 1970 del a[0:10] 1971 self.assertEqual(a.delitem, (slice(0, 10))) 1972 1973 def test_load_attr_extended_arg(self): 1974 # https://github.com/python/cpython/issues/91625 1975 class Numbers: 1976 def __getattr__(self, attr): 1977 return int(attr.lstrip("_")) 1978 attrs = ", ".join(f"Z._{n:03d}" for n in range(280)) 1979 code = f"def number_attrs(Z):\n return [ {attrs} ]" 1980 ns = {} 1981 exec(code, ns) 1982 number_attrs = ns["number_attrs"] 1983 # Warm up the the function for quickening (PEP 659) 1984 for _ in range(30): 1985 self.assertEqual(number_attrs(Numbers()), list(range(280))) 1986 1987 def test_methods(self): 1988 # Testing methods... 1989 class C(object): 1990 def __init__(self, x): 1991 self.x = x 1992 def foo(self): 1993 return self.x 1994 c1 = C(1) 1995 self.assertEqual(c1.foo(), 1) 1996 class D(C): 1997 boo = C.foo 1998 goo = c1.foo 1999 d2 = D(2) 2000 self.assertEqual(d2.foo(), 2) 2001 self.assertEqual(d2.boo(), 2) 2002 self.assertEqual(d2.goo(), 1) 2003 class E(object): 2004 foo = C.foo 2005 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound 2006 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method ")) 2007 2008 @support.impl_detail("testing error message from implementation") 2009 def test_methods_in_c(self): 2010 # This test checks error messages in builtin method descriptor. 2011 # It is allowed that other Python implementations use 2012 # different error messages. 2013 set_add = set.add 2014 2015 expected_errmsg = "unbound method set.add() needs an argument" 2016 2017 with self.assertRaises(TypeError) as cm: 2018 set_add() 2019 self.assertEqual(cm.exception.args[0], expected_errmsg) 2020 2021 expected_errmsg = "descriptor 'add' for 'set' objects doesn't apply to a 'int' object" 2022 2023 with self.assertRaises(TypeError) as cm: 2024 set_add(0) 2025 self.assertEqual(cm.exception.args[0], expected_errmsg) 2026 2027 with self.assertRaises(TypeError) as cm: 2028 set_add.__get__(0) 2029 self.assertEqual(cm.exception.args[0], expected_errmsg) 2030 2031 def test_special_method_lookup(self): 2032 # The lookup of special methods bypasses __getattr__ and 2033 # __getattribute__, but they still can be descriptors. 2034 2035 def run_context(manager): 2036 with manager: 2037 pass 2038 def iden(self): 2039 return self 2040 def hello(self): 2041 return b"hello" 2042 def empty_seq(self): 2043 return [] 2044 def zero(self): 2045 return 0 2046 def complex_num(self): 2047 return 1j 2048 def stop(self): 2049 raise StopIteration 2050 def return_true(self, thing=None): 2051 return True 2052 def do_isinstance(obj): 2053 return isinstance(int, obj) 2054 def do_issubclass(obj): 2055 return issubclass(int, obj) 2056 def do_dict_missing(checker): 2057 class DictSub(checker.__class__, dict): 2058 pass 2059 self.assertEqual(DictSub()["hi"], 4) 2060 def some_number(self_, key): 2061 self.assertEqual(key, "hi") 2062 return 4 2063 def swallow(*args): pass 2064 def format_impl(self, spec): 2065 return "hello" 2066 2067 # It would be nice to have every special method tested here, but I'm 2068 # only listing the ones I can remember outside of typeobject.c, since it 2069 # does it right. 2070 specials = [ 2071 ("__bytes__", bytes, hello, set(), {}), 2072 ("__reversed__", reversed, empty_seq, set(), {}), 2073 ("__length_hint__", list, zero, set(), 2074 {"__iter__" : iden, "__next__" : stop}), 2075 ("__sizeof__", sys.getsizeof, zero, set(), {}), 2076 ("__instancecheck__", do_isinstance, return_true, set(), {}), 2077 ("__missing__", do_dict_missing, some_number, 2078 set(("__class__",)), {}), 2079 ("__subclasscheck__", do_issubclass, return_true, 2080 set(("__bases__",)), {}), 2081 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}), 2082 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}), 2083 ("__complex__", complex, complex_num, set(), {}), 2084 ("__format__", format, format_impl, set(), {}), 2085 ("__floor__", math.floor, zero, set(), {}), 2086 ("__trunc__", math.trunc, zero, set(), {}), 2087 ("__ceil__", math.ceil, zero, set(), {}), 2088 ("__dir__", dir, empty_seq, set(), {}), 2089 ("__round__", round, zero, set(), {}), 2090 ] 2091 2092 class Checker(object): 2093 def __getattr__(self, attr, test=self): 2094 test.fail("__getattr__ called with {0}".format(attr)) 2095 def __getattribute__(self, attr, test=self): 2096 if attr not in ok: 2097 test.fail("__getattribute__ called with {0}".format(attr)) 2098 return object.__getattribute__(self, attr) 2099 class SpecialDescr(object): 2100 def __init__(self, impl): 2101 self.impl = impl 2102 def __get__(self, obj, owner): 2103 record.append(1) 2104 return self.impl.__get__(obj, owner) 2105 class MyException(Exception): 2106 pass 2107 class ErrDescr(object): 2108 def __get__(self, obj, owner): 2109 raise MyException 2110 2111 for name, runner, meth_impl, ok, env in specials: 2112 class X(Checker): 2113 pass 2114 for attr, obj in env.items(): 2115 setattr(X, attr, obj) 2116 setattr(X, name, meth_impl) 2117 runner(X()) 2118 2119 record = [] 2120 class X(Checker): 2121 pass 2122 for attr, obj in env.items(): 2123 setattr(X, attr, obj) 2124 setattr(X, name, SpecialDescr(meth_impl)) 2125 runner(X()) 2126 self.assertEqual(record, [1], name) 2127 2128 class X(Checker): 2129 pass 2130 for attr, obj in env.items(): 2131 setattr(X, attr, obj) 2132 setattr(X, name, ErrDescr()) 2133 self.assertRaises(MyException, runner, X()) 2134 2135 def test_specials(self): 2136 # Testing special operators... 2137 # Test operators like __hash__ for which a built-in default exists 2138 2139 # Test the default behavior for static classes 2140 class C(object): 2141 def __getitem__(self, i): 2142 if 0 <= i < 10: return i 2143 raise IndexError 2144 c1 = C() 2145 c2 = C() 2146 self.assertFalse(not c1) 2147 self.assertNotEqual(id(c1), id(c2)) 2148 hash(c1) 2149 hash(c2) 2150 self.assertEqual(c1, c1) 2151 self.assertTrue(c1 != c2) 2152 self.assertFalse(c1 != c1) 2153 self.assertFalse(c1 == c2) 2154 # Note that the module name appears in str/repr, and that varies 2155 # depending on whether this test is run standalone or from a framework. 2156 self.assertGreaterEqual(str(c1).find('C object at '), 0) 2157 self.assertEqual(str(c1), repr(c1)) 2158 self.assertNotIn(-1, c1) 2159 for i in range(10): 2160 self.assertIn(i, c1) 2161 self.assertNotIn(10, c1) 2162 # Test the default behavior for dynamic classes 2163 class D(object): 2164 def __getitem__(self, i): 2165 if 0 <= i < 10: return i 2166 raise IndexError 2167 d1 = D() 2168 d2 = D() 2169 self.assertFalse(not d1) 2170 self.assertNotEqual(id(d1), id(d2)) 2171 hash(d1) 2172 hash(d2) 2173 self.assertEqual(d1, d1) 2174 self.assertNotEqual(d1, d2) 2175 self.assertFalse(d1 != d1) 2176 self.assertFalse(d1 == d2) 2177 # Note that the module name appears in str/repr, and that varies 2178 # depending on whether this test is run standalone or from a framework. 2179 self.assertGreaterEqual(str(d1).find('D object at '), 0) 2180 self.assertEqual(str(d1), repr(d1)) 2181 self.assertNotIn(-1, d1) 2182 for i in range(10): 2183 self.assertIn(i, d1) 2184 self.assertNotIn(10, d1) 2185 # Test overridden behavior 2186 class Proxy(object): 2187 def __init__(self, x): 2188 self.x = x 2189 def __bool__(self): 2190 return not not self.x 2191 def __hash__(self): 2192 return hash(self.x) 2193 def __eq__(self, other): 2194 return self.x == other 2195 def __ne__(self, other): 2196 return self.x != other 2197 def __ge__(self, other): 2198 return self.x >= other 2199 def __gt__(self, other): 2200 return self.x > other 2201 def __le__(self, other): 2202 return self.x <= other 2203 def __lt__(self, other): 2204 return self.x < other 2205 def __str__(self): 2206 return "Proxy:%s" % self.x 2207 def __repr__(self): 2208 return "Proxy(%r)" % self.x 2209 def __contains__(self, value): 2210 return value in self.x 2211 p0 = Proxy(0) 2212 p1 = Proxy(1) 2213 p_1 = Proxy(-1) 2214 self.assertFalse(p0) 2215 self.assertFalse(not p1) 2216 self.assertEqual(hash(p0), hash(0)) 2217 self.assertEqual(p0, p0) 2218 self.assertNotEqual(p0, p1) 2219 self.assertFalse(p0 != p0) 2220 self.assertEqual(not p0, p1) 2221 self.assertTrue(p0 < p1) 2222 self.assertTrue(p0 <= p1) 2223 self.assertTrue(p1 > p0) 2224 self.assertTrue(p1 >= p0) 2225 self.assertEqual(str(p0), "Proxy:0") 2226 self.assertEqual(repr(p0), "Proxy(0)") 2227 p10 = Proxy(range(10)) 2228 self.assertNotIn(-1, p10) 2229 for i in range(10): 2230 self.assertIn(i, p10) 2231 self.assertNotIn(10, p10) 2232 2233 def test_weakrefs(self): 2234 # Testing weak references... 2235 import weakref 2236 class C(object): 2237 pass 2238 c = C() 2239 r = weakref.ref(c) 2240 self.assertEqual(r(), c) 2241 del c 2242 support.gc_collect() 2243 self.assertEqual(r(), None) 2244 del r 2245 class NoWeak(object): 2246 __slots__ = ['foo'] 2247 no = NoWeak() 2248 try: 2249 weakref.ref(no) 2250 except TypeError as msg: 2251 self.assertIn("weak reference", str(msg)) 2252 else: 2253 self.fail("weakref.ref(no) should be illegal") 2254 class Weak(object): 2255 __slots__ = ['foo', '__weakref__'] 2256 yes = Weak() 2257 r = weakref.ref(yes) 2258 self.assertEqual(r(), yes) 2259 del yes 2260 support.gc_collect() 2261 self.assertEqual(r(), None) 2262 del r 2263 2264 def test_properties(self): 2265 # Testing property... 2266 class C(object): 2267 def getx(self): 2268 return self.__x 2269 def setx(self, value): 2270 self.__x = value 2271 def delx(self): 2272 del self.__x 2273 x = property(getx, setx, delx, doc="I'm the x property.") 2274 a = C() 2275 self.assertNotHasAttr(a, "x") 2276 a.x = 42 2277 self.assertEqual(a._C__x, 42) 2278 self.assertEqual(a.x, 42) 2279 del a.x 2280 self.assertNotHasAttr(a, "x") 2281 self.assertNotHasAttr(a, "_C__x") 2282 C.x.__set__(a, 100) 2283 self.assertEqual(C.x.__get__(a), 100) 2284 C.x.__delete__(a) 2285 self.assertNotHasAttr(a, "x") 2286 2287 raw = C.__dict__['x'] 2288 self.assertIsInstance(raw, property) 2289 2290 attrs = dir(raw) 2291 self.assertIn("__doc__", attrs) 2292 self.assertIn("fget", attrs) 2293 self.assertIn("fset", attrs) 2294 self.assertIn("fdel", attrs) 2295 2296 self.assertEqual(raw.__doc__, "I'm the x property.") 2297 self.assertIs(raw.fget, C.__dict__['getx']) 2298 self.assertIs(raw.fset, C.__dict__['setx']) 2299 self.assertIs(raw.fdel, C.__dict__['delx']) 2300 2301 for attr in "fget", "fset", "fdel": 2302 try: 2303 setattr(raw, attr, 42) 2304 except AttributeError as msg: 2305 if str(msg).find('readonly') < 0: 2306 self.fail("when setting readonly attr %r on a property, " 2307 "got unexpected AttributeError msg %r" % (attr, str(msg))) 2308 else: 2309 self.fail("expected AttributeError from trying to set readonly %r " 2310 "attr on a property" % attr) 2311 2312 raw.__doc__ = 42 2313 self.assertEqual(raw.__doc__, 42) 2314 2315 class D(object): 2316 __getitem__ = property(lambda s: 1/0) 2317 2318 d = D() 2319 try: 2320 for i in d: 2321 str(i) 2322 except ZeroDivisionError: 2323 pass 2324 else: 2325 self.fail("expected ZeroDivisionError from bad property") 2326 2327 @unittest.skipIf(sys.flags.optimize >= 2, 2328 "Docstrings are omitted with -O2 and above") 2329 def test_properties_doc_attrib(self): 2330 class E(object): 2331 def getter(self): 2332 "getter method" 2333 return 0 2334 def setter(self_, value): 2335 "setter method" 2336 pass 2337 prop = property(getter) 2338 self.assertEqual(prop.__doc__, "getter method") 2339 prop2 = property(fset=setter) 2340 self.assertEqual(prop2.__doc__, None) 2341 2342 @support.cpython_only 2343 def test_testcapi_no_segfault(self): 2344 # this segfaulted in 2.5b2 2345 try: 2346 import _testcapi 2347 except ImportError: 2348 pass 2349 else: 2350 class X(object): 2351 p = property(_testcapi.test_with_docstring) 2352 2353 def test_properties_plus(self): 2354 class C(object): 2355 foo = property(doc="hello") 2356 @foo.getter 2357 def foo(self): 2358 return self._foo 2359 @foo.setter 2360 def foo(self, value): 2361 self._foo = abs(value) 2362 @foo.deleter 2363 def foo(self): 2364 del self._foo 2365 c = C() 2366 self.assertEqual(C.foo.__doc__, "hello") 2367 self.assertNotHasAttr(c, "foo") 2368 c.foo = -42 2369 self.assertHasAttr(c, '_foo') 2370 self.assertEqual(c._foo, 42) 2371 self.assertEqual(c.foo, 42) 2372 del c.foo 2373 self.assertNotHasAttr(c, '_foo') 2374 self.assertNotHasAttr(c, "foo") 2375 2376 class D(C): 2377 @C.foo.deleter 2378 def foo(self): 2379 try: 2380 del self._foo 2381 except AttributeError: 2382 pass 2383 d = D() 2384 d.foo = 24 2385 self.assertEqual(d.foo, 24) 2386 del d.foo 2387 del d.foo 2388 2389 class E(object): 2390 @property 2391 def foo(self): 2392 return self._foo 2393 @foo.setter 2394 def foo(self, value): 2395 raise RuntimeError 2396 @foo.setter 2397 def foo(self, value): 2398 self._foo = abs(value) 2399 @foo.deleter 2400 def foo(self, value=None): 2401 del self._foo 2402 2403 e = E() 2404 e.foo = -42 2405 self.assertEqual(e.foo, 42) 2406 del e.foo 2407 2408 class F(E): 2409 @E.foo.deleter 2410 def foo(self): 2411 del self._foo 2412 @foo.setter 2413 def foo(self, value): 2414 self._foo = max(0, value) 2415 f = F() 2416 f.foo = -10 2417 self.assertEqual(f.foo, 0) 2418 del f.foo 2419 2420 def test_dict_constructors(self): 2421 # Testing dict constructor ... 2422 d = dict() 2423 self.assertEqual(d, {}) 2424 d = dict({}) 2425 self.assertEqual(d, {}) 2426 d = dict({1: 2, 'a': 'b'}) 2427 self.assertEqual(d, {1: 2, 'a': 'b'}) 2428 self.assertEqual(d, dict(list(d.items()))) 2429 self.assertEqual(d, dict(iter(d.items()))) 2430 d = dict({'one':1, 'two':2}) 2431 self.assertEqual(d, dict(one=1, two=2)) 2432 self.assertEqual(d, dict(**d)) 2433 self.assertEqual(d, dict({"one": 1}, two=2)) 2434 self.assertEqual(d, dict([("two", 2)], one=1)) 2435 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d)) 2436 self.assertEqual(d, dict(**d)) 2437 2438 for badarg in 0, 0, 0j, "0", [0], (0,): 2439 try: 2440 dict(badarg) 2441 except TypeError: 2442 pass 2443 except ValueError: 2444 if badarg == "0": 2445 # It's a sequence, and its elements are also sequences (gotta 2446 # love strings <wink>), but they aren't of length 2, so this 2447 # one seemed better as a ValueError than a TypeError. 2448 pass 2449 else: 2450 self.fail("no TypeError from dict(%r)" % badarg) 2451 else: 2452 self.fail("no TypeError from dict(%r)" % badarg) 2453 2454 with self.assertRaises(TypeError): 2455 dict({}, {}) 2456 2457 class Mapping: 2458 # Lacks a .keys() method; will be added later. 2459 dict = {1:2, 3:4, 'a':1j} 2460 2461 try: 2462 dict(Mapping()) 2463 except TypeError: 2464 pass 2465 else: 2466 self.fail("no TypeError from dict(incomplete mapping)") 2467 2468 Mapping.keys = lambda self: list(self.dict.keys()) 2469 Mapping.__getitem__ = lambda self, i: self.dict[i] 2470 d = dict(Mapping()) 2471 self.assertEqual(d, Mapping.dict) 2472 2473 # Init from sequence of iterable objects, each producing a 2-sequence. 2474 class AddressBookEntry: 2475 def __init__(self, first, last): 2476 self.first = first 2477 self.last = last 2478 def __iter__(self): 2479 return iter([self.first, self.last]) 2480 2481 d = dict([AddressBookEntry('Tim', 'Warsaw'), 2482 AddressBookEntry('Barry', 'Peters'), 2483 AddressBookEntry('Tim', 'Peters'), 2484 AddressBookEntry('Barry', 'Warsaw')]) 2485 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'}) 2486 2487 d = dict(zip(range(4), range(1, 5))) 2488 self.assertEqual(d, dict([(i, i+1) for i in range(4)])) 2489 2490 # Bad sequence lengths. 2491 for bad in [('tooshort',)], [('too', 'long', 'by 1')]: 2492 try: 2493 dict(bad) 2494 except ValueError: 2495 pass 2496 else: 2497 self.fail("no ValueError from dict(%r)" % bad) 2498 2499 def test_dir(self): 2500 # Testing dir() ... 2501 junk = 12 2502 self.assertEqual(dir(), ['junk', 'self']) 2503 del junk 2504 2505 # Just make sure these don't blow up! 2506 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir: 2507 dir(arg) 2508 2509 # Test dir on new-style classes. Since these have object as a 2510 # base class, a lot more gets sucked in. 2511 def interesting(strings): 2512 return [s for s in strings if not s.startswith('_')] 2513 2514 class C(object): 2515 Cdata = 1 2516 def Cmethod(self): pass 2517 2518 cstuff = ['Cdata', 'Cmethod'] 2519 self.assertEqual(interesting(dir(C)), cstuff) 2520 2521 c = C() 2522 self.assertEqual(interesting(dir(c)), cstuff) 2523 ## self.assertIn('__self__', dir(C.Cmethod)) 2524 2525 c.cdata = 2 2526 c.cmethod = lambda self: 0 2527 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod']) 2528 ## self.assertIn('__self__', dir(c.Cmethod)) 2529 2530 class A(C): 2531 Adata = 1 2532 def Amethod(self): pass 2533 2534 astuff = ['Adata', 'Amethod'] + cstuff 2535 self.assertEqual(interesting(dir(A)), astuff) 2536 ## self.assertIn('__self__', dir(A.Amethod)) 2537 a = A() 2538 self.assertEqual(interesting(dir(a)), astuff) 2539 a.adata = 42 2540 a.amethod = lambda self: 3 2541 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod']) 2542 ## self.assertIn('__self__', dir(a.Amethod)) 2543 2544 # Try a module subclass. 2545 class M(type(sys)): 2546 pass 2547 minstance = M("m") 2548 minstance.b = 2 2549 minstance.a = 1 2550 default_attributes = ['__name__', '__doc__', '__package__', 2551 '__loader__', '__spec__'] 2552 names = [x for x in dir(minstance) if x not in default_attributes] 2553 self.assertEqual(names, ['a', 'b']) 2554 2555 class M2(M): 2556 def getdict(self): 2557 return "Not a dict!" 2558 __dict__ = property(getdict) 2559 2560 m2instance = M2("m2") 2561 m2instance.b = 2 2562 m2instance.a = 1 2563 self.assertEqual(m2instance.__dict__, "Not a dict!") 2564 with self.assertRaises(TypeError): 2565 dir(m2instance) 2566 2567 # Two essentially featureless objects, (Ellipsis just inherits stuff 2568 # from object. 2569 self.assertEqual(dir(object()), dir(Ellipsis)) 2570 2571 # Nasty test case for proxied objects 2572 class Wrapper(object): 2573 def __init__(self, obj): 2574 self.__obj = obj 2575 def __repr__(self): 2576 return "Wrapper(%s)" % repr(self.__obj) 2577 def __getitem__(self, key): 2578 return Wrapper(self.__obj[key]) 2579 def __len__(self): 2580 return len(self.__obj) 2581 def __getattr__(self, name): 2582 return Wrapper(getattr(self.__obj, name)) 2583 2584 class C(object): 2585 def __getclass(self): 2586 return Wrapper(type(self)) 2587 __class__ = property(__getclass) 2588 2589 dir(C()) # This used to segfault 2590 2591 def test_supers(self): 2592 # Testing super... 2593 2594 class A(object): 2595 def meth(self, a): 2596 return "A(%r)" % a 2597 2598 self.assertEqual(A().meth(1), "A(1)") 2599 2600 class B(A): 2601 def __init__(self): 2602 self.__super = super(B, self) 2603 def meth(self, a): 2604 return "B(%r)" % a + self.__super.meth(a) 2605 2606 self.assertEqual(B().meth(2), "B(2)A(2)") 2607 2608 class C(A): 2609 def meth(self, a): 2610 return "C(%r)" % a + self.__super.meth(a) 2611 C._C__super = super(C) 2612 2613 self.assertEqual(C().meth(3), "C(3)A(3)") 2614 2615 class D(C, B): 2616 def meth(self, a): 2617 return "D(%r)" % a + super(D, self).meth(a) 2618 2619 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)") 2620 2621 # Test for subclassing super 2622 2623 class mysuper(super): 2624 def __init__(self, *args): 2625 return super(mysuper, self).__init__(*args) 2626 2627 class E(D): 2628 def meth(self, a): 2629 return "E(%r)" % a + mysuper(E, self).meth(a) 2630 2631 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)") 2632 2633 class F(E): 2634 def meth(self, a): 2635 s = self.__super # == mysuper(F, self) 2636 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a) 2637 F._F__super = mysuper(F) 2638 2639 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)") 2640 2641 # Make sure certain errors are raised 2642 2643 try: 2644 super(D, 42) 2645 except TypeError: 2646 pass 2647 else: 2648 self.fail("shouldn't allow super(D, 42)") 2649 2650 try: 2651 super(D, C()) 2652 except TypeError: 2653 pass 2654 else: 2655 self.fail("shouldn't allow super(D, C())") 2656 2657 try: 2658 super(D).__get__(12) 2659 except TypeError: 2660 pass 2661 else: 2662 self.fail("shouldn't allow super(D).__get__(12)") 2663 2664 try: 2665 super(D).__get__(C()) 2666 except TypeError: 2667 pass 2668 else: 2669 self.fail("shouldn't allow super(D).__get__(C())") 2670 2671 # Make sure data descriptors can be overridden and accessed via super 2672 # (new feature in Python 2.3) 2673 2674 class DDbase(object): 2675 def getx(self): return 42 2676 x = property(getx) 2677 2678 class DDsub(DDbase): 2679 def getx(self): return "hello" 2680 x = property(getx) 2681 2682 dd = DDsub() 2683 self.assertEqual(dd.x, "hello") 2684 self.assertEqual(super(DDsub, dd).x, 42) 2685 2686 # Ensure that super() lookup of descriptor from classmethod 2687 # works (SF ID# 743627) 2688 2689 class Base(object): 2690 aProp = property(lambda self: "foo") 2691 2692 class Sub(Base): 2693 @classmethod 2694 def test(klass): 2695 return super(Sub,klass).aProp 2696 2697 self.assertEqual(Sub.test(), Base.aProp) 2698 2699 # Verify that super() doesn't allow keyword args 2700 with self.assertRaises(TypeError): 2701 super(Base, kw=1) 2702 2703 def test_basic_inheritance(self): 2704 # Testing inheritance from basic types... 2705 2706 class hexint(int): 2707 def __repr__(self): 2708 return hex(self) 2709 def __add__(self, other): 2710 return hexint(int.__add__(self, other)) 2711 # (Note that overriding __radd__ doesn't work, 2712 # because the int type gets first dibs.) 2713 self.assertEqual(repr(hexint(7) + 9), "0x10") 2714 self.assertEqual(repr(hexint(1000) + 7), "0x3ef") 2715 a = hexint(12345) 2716 self.assertEqual(a, 12345) 2717 self.assertEqual(int(a), 12345) 2718 self.assertIs(int(a).__class__, int) 2719 self.assertEqual(hash(a), hash(12345)) 2720 self.assertIs((+a).__class__, int) 2721 self.assertIs((a >> 0).__class__, int) 2722 self.assertIs((a << 0).__class__, int) 2723 self.assertIs((hexint(0) << 12).__class__, int) 2724 self.assertIs((hexint(0) >> 12).__class__, int) 2725 2726 class octlong(int): 2727 __slots__ = [] 2728 def __str__(self): 2729 return oct(self) 2730 def __add__(self, other): 2731 return self.__class__(super(octlong, self).__add__(other)) 2732 __radd__ = __add__ 2733 self.assertEqual(str(octlong(3) + 5), "0o10") 2734 # (Note that overriding __radd__ here only seems to work 2735 # because the example uses a short int left argument.) 2736 self.assertEqual(str(5 + octlong(3000)), "0o5675") 2737 a = octlong(12345) 2738 self.assertEqual(a, 12345) 2739 self.assertEqual(int(a), 12345) 2740 self.assertEqual(hash(a), hash(12345)) 2741 self.assertIs(int(a).__class__, int) 2742 self.assertIs((+a).__class__, int) 2743 self.assertIs((-a).__class__, int) 2744 self.assertIs((-octlong(0)).__class__, int) 2745 self.assertIs((a >> 0).__class__, int) 2746 self.assertIs((a << 0).__class__, int) 2747 self.assertIs((a - 0).__class__, int) 2748 self.assertIs((a * 1).__class__, int) 2749 self.assertIs((a ** 1).__class__, int) 2750 self.assertIs((a // 1).__class__, int) 2751 self.assertIs((1 * a).__class__, int) 2752 self.assertIs((a | 0).__class__, int) 2753 self.assertIs((a ^ 0).__class__, int) 2754 self.assertIs((a & -1).__class__, int) 2755 self.assertIs((octlong(0) << 12).__class__, int) 2756 self.assertIs((octlong(0) >> 12).__class__, int) 2757 self.assertIs(abs(octlong(0)).__class__, int) 2758 2759 # Because octlong overrides __add__, we can't check the absence of +0 2760 # optimizations using octlong. 2761 class longclone(int): 2762 pass 2763 a = longclone(1) 2764 self.assertIs((a + 0).__class__, int) 2765 self.assertIs((0 + a).__class__, int) 2766 2767 # Check that negative clones don't segfault 2768 a = longclone(-1) 2769 self.assertEqual(a.__dict__, {}) 2770 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit 2771 2772 class precfloat(float): 2773 __slots__ = ['prec'] 2774 def __init__(self, value=0.0, prec=12): 2775 self.prec = int(prec) 2776 def __repr__(self): 2777 return "%.*g" % (self.prec, self) 2778 self.assertEqual(repr(precfloat(1.1)), "1.1") 2779 a = precfloat(12345) 2780 self.assertEqual(a, 12345.0) 2781 self.assertEqual(float(a), 12345.0) 2782 self.assertIs(float(a).__class__, float) 2783 self.assertEqual(hash(a), hash(12345.0)) 2784 self.assertIs((+a).__class__, float) 2785 2786 class madcomplex(complex): 2787 def __repr__(self): 2788 return "%.17gj%+.17g" % (self.imag, self.real) 2789 a = madcomplex(-3, 4) 2790 self.assertEqual(repr(a), "4j-3") 2791 base = complex(-3, 4) 2792 self.assertEqual(base.__class__, complex) 2793 self.assertEqual(a, base) 2794 self.assertEqual(complex(a), base) 2795 self.assertEqual(complex(a).__class__, complex) 2796 a = madcomplex(a) # just trying another form of the constructor 2797 self.assertEqual(repr(a), "4j-3") 2798 self.assertEqual(a, base) 2799 self.assertEqual(complex(a), base) 2800 self.assertEqual(complex(a).__class__, complex) 2801 self.assertEqual(hash(a), hash(base)) 2802 self.assertEqual((+a).__class__, complex) 2803 self.assertEqual((a + 0).__class__, complex) 2804 self.assertEqual(a + 0, base) 2805 self.assertEqual((a - 0).__class__, complex) 2806 self.assertEqual(a - 0, base) 2807 self.assertEqual((a * 1).__class__, complex) 2808 self.assertEqual(a * 1, base) 2809 self.assertEqual((a / 1).__class__, complex) 2810 self.assertEqual(a / 1, base) 2811 2812 class madtuple(tuple): 2813 _rev = None 2814 def rev(self): 2815 if self._rev is not None: 2816 return self._rev 2817 L = list(self) 2818 L.reverse() 2819 self._rev = self.__class__(L) 2820 return self._rev 2821 a = madtuple((1,2,3,4,5,6,7,8,9,0)) 2822 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0)) 2823 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1))) 2824 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0))) 2825 for i in range(512): 2826 t = madtuple(range(i)) 2827 u = t.rev() 2828 v = u.rev() 2829 self.assertEqual(v, t) 2830 a = madtuple((1,2,3,4,5)) 2831 self.assertEqual(tuple(a), (1,2,3,4,5)) 2832 self.assertIs(tuple(a).__class__, tuple) 2833 self.assertEqual(hash(a), hash((1,2,3,4,5))) 2834 self.assertIs(a[:].__class__, tuple) 2835 self.assertIs((a * 1).__class__, tuple) 2836 self.assertIs((a * 0).__class__, tuple) 2837 self.assertIs((a + ()).__class__, tuple) 2838 a = madtuple(()) 2839 self.assertEqual(tuple(a), ()) 2840 self.assertIs(tuple(a).__class__, tuple) 2841 self.assertIs((a + a).__class__, tuple) 2842 self.assertIs((a * 0).__class__, tuple) 2843 self.assertIs((a * 1).__class__, tuple) 2844 self.assertIs((a * 2).__class__, tuple) 2845 self.assertIs(a[:].__class__, tuple) 2846 2847 class madstring(str): 2848 _rev = None 2849 def rev(self): 2850 if self._rev is not None: 2851 return self._rev 2852 L = list(self) 2853 L.reverse() 2854 self._rev = self.__class__("".join(L)) 2855 return self._rev 2856 s = madstring("abcdefghijklmnopqrstuvwxyz") 2857 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz") 2858 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba")) 2859 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz")) 2860 for i in range(256): 2861 s = madstring("".join(map(chr, range(i)))) 2862 t = s.rev() 2863 u = t.rev() 2864 self.assertEqual(u, s) 2865 s = madstring("12345") 2866 self.assertEqual(str(s), "12345") 2867 self.assertIs(str(s).__class__, str) 2868 2869 base = "\x00" * 5 2870 s = madstring(base) 2871 self.assertEqual(s, base) 2872 self.assertEqual(str(s), base) 2873 self.assertIs(str(s).__class__, str) 2874 self.assertEqual(hash(s), hash(base)) 2875 self.assertEqual({s: 1}[base], 1) 2876 self.assertEqual({base: 1}[s], 1) 2877 self.assertIs((s + "").__class__, str) 2878 self.assertEqual(s + "", base) 2879 self.assertIs(("" + s).__class__, str) 2880 self.assertEqual("" + s, base) 2881 self.assertIs((s * 0).__class__, str) 2882 self.assertEqual(s * 0, "") 2883 self.assertIs((s * 1).__class__, str) 2884 self.assertEqual(s * 1, base) 2885 self.assertIs((s * 2).__class__, str) 2886 self.assertEqual(s * 2, base + base) 2887 self.assertIs(s[:].__class__, str) 2888 self.assertEqual(s[:], base) 2889 self.assertIs(s[0:0].__class__, str) 2890 self.assertEqual(s[0:0], "") 2891 self.assertIs(s.strip().__class__, str) 2892 self.assertEqual(s.strip(), base) 2893 self.assertIs(s.lstrip().__class__, str) 2894 self.assertEqual(s.lstrip(), base) 2895 self.assertIs(s.rstrip().__class__, str) 2896 self.assertEqual(s.rstrip(), base) 2897 identitytab = {} 2898 self.assertIs(s.translate(identitytab).__class__, str) 2899 self.assertEqual(s.translate(identitytab), base) 2900 self.assertIs(s.replace("x", "x").__class__, str) 2901 self.assertEqual(s.replace("x", "x"), base) 2902 self.assertIs(s.ljust(len(s)).__class__, str) 2903 self.assertEqual(s.ljust(len(s)), base) 2904 self.assertIs(s.rjust(len(s)).__class__, str) 2905 self.assertEqual(s.rjust(len(s)), base) 2906 self.assertIs(s.center(len(s)).__class__, str) 2907 self.assertEqual(s.center(len(s)), base) 2908 self.assertIs(s.lower().__class__, str) 2909 self.assertEqual(s.lower(), base) 2910 2911 class madunicode(str): 2912 _rev = None 2913 def rev(self): 2914 if self._rev is not None: 2915 return self._rev 2916 L = list(self) 2917 L.reverse() 2918 self._rev = self.__class__("".join(L)) 2919 return self._rev 2920 u = madunicode("ABCDEF") 2921 self.assertEqual(u, "ABCDEF") 2922 self.assertEqual(u.rev(), madunicode("FEDCBA")) 2923 self.assertEqual(u.rev().rev(), madunicode("ABCDEF")) 2924 base = "12345" 2925 u = madunicode(base) 2926 self.assertEqual(str(u), base) 2927 self.assertIs(str(u).__class__, str) 2928 self.assertEqual(hash(u), hash(base)) 2929 self.assertEqual({u: 1}[base], 1) 2930 self.assertEqual({base: 1}[u], 1) 2931 self.assertIs(u.strip().__class__, str) 2932 self.assertEqual(u.strip(), base) 2933 self.assertIs(u.lstrip().__class__, str) 2934 self.assertEqual(u.lstrip(), base) 2935 self.assertIs(u.rstrip().__class__, str) 2936 self.assertEqual(u.rstrip(), base) 2937 self.assertIs(u.replace("x", "x").__class__, str) 2938 self.assertEqual(u.replace("x", "x"), base) 2939 self.assertIs(u.replace("xy", "xy").__class__, str) 2940 self.assertEqual(u.replace("xy", "xy"), base) 2941 self.assertIs(u.center(len(u)).__class__, str) 2942 self.assertEqual(u.center(len(u)), base) 2943 self.assertIs(u.ljust(len(u)).__class__, str) 2944 self.assertEqual(u.ljust(len(u)), base) 2945 self.assertIs(u.rjust(len(u)).__class__, str) 2946 self.assertEqual(u.rjust(len(u)), base) 2947 self.assertIs(u.lower().__class__, str) 2948 self.assertEqual(u.lower(), base) 2949 self.assertIs(u.upper().__class__, str) 2950 self.assertEqual(u.upper(), base) 2951 self.assertIs(u.capitalize().__class__, str) 2952 self.assertEqual(u.capitalize(), base) 2953 self.assertIs(u.title().__class__, str) 2954 self.assertEqual(u.title(), base) 2955 self.assertIs((u + "").__class__, str) 2956 self.assertEqual(u + "", base) 2957 self.assertIs(("" + u).__class__, str) 2958 self.assertEqual("" + u, base) 2959 self.assertIs((u * 0).__class__, str) 2960 self.assertEqual(u * 0, "") 2961 self.assertIs((u * 1).__class__, str) 2962 self.assertEqual(u * 1, base) 2963 self.assertIs((u * 2).__class__, str) 2964 self.assertEqual(u * 2, base + base) 2965 self.assertIs(u[:].__class__, str) 2966 self.assertEqual(u[:], base) 2967 self.assertIs(u[0:0].__class__, str) 2968 self.assertEqual(u[0:0], "") 2969 2970 class sublist(list): 2971 pass 2972 a = sublist(range(5)) 2973 self.assertEqual(a, list(range(5))) 2974 a.append("hello") 2975 self.assertEqual(a, list(range(5)) + ["hello"]) 2976 a[5] = 5 2977 self.assertEqual(a, list(range(6))) 2978 a.extend(range(6, 20)) 2979 self.assertEqual(a, list(range(20))) 2980 a[-5:] = [] 2981 self.assertEqual(a, list(range(15))) 2982 del a[10:15] 2983 self.assertEqual(len(a), 10) 2984 self.assertEqual(a, list(range(10))) 2985 self.assertEqual(list(a), list(range(10))) 2986 self.assertEqual(a[0], 0) 2987 self.assertEqual(a[9], 9) 2988 self.assertEqual(a[-10], 0) 2989 self.assertEqual(a[-1], 9) 2990 self.assertEqual(a[:5], list(range(5))) 2991 2992 ## class CountedInput(file): 2993 ## """Counts lines read by self.readline(). 2994 ## 2995 ## self.lineno is the 0-based ordinal of the last line read, up to 2996 ## a maximum of one greater than the number of lines in the file. 2997 ## 2998 ## self.ateof is true if and only if the final "" line has been read, 2999 ## at which point self.lineno stops incrementing, and further calls 3000 ## to readline() continue to return "". 3001 ## """ 3002 ## 3003 ## lineno = 0 3004 ## ateof = 0 3005 ## def readline(self): 3006 ## if self.ateof: 3007 ## return "" 3008 ## s = file.readline(self) 3009 ## # Next line works too. 3010 ## # s = super(CountedInput, self).readline() 3011 ## self.lineno += 1 3012 ## if s == "": 3013 ## self.ateof = 1 3014 ## return s 3015 ## 3016 ## f = file(name=os_helper.TESTFN, mode='w') 3017 ## lines = ['a\n', 'b\n', 'c\n'] 3018 ## try: 3019 ## f.writelines(lines) 3020 ## f.close() 3021 ## f = CountedInput(os_helper.TESTFN) 3022 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]): 3023 ## got = f.readline() 3024 ## self.assertEqual(expected, got) 3025 ## self.assertEqual(f.lineno, i) 3026 ## self.assertEqual(f.ateof, (i > len(lines))) 3027 ## f.close() 3028 ## finally: 3029 ## try: 3030 ## f.close() 3031 ## except: 3032 ## pass 3033 ## os_helper.unlink(os_helper.TESTFN) 3034 3035 def test_keywords(self): 3036 # Testing keyword args to basic type constructors ... 3037 with self.assertRaisesRegex(TypeError, 'keyword argument'): 3038 int(x=1) 3039 with self.assertRaisesRegex(TypeError, 'keyword argument'): 3040 float(x=2) 3041 with self.assertRaisesRegex(TypeError, 'keyword argument'): 3042 bool(x=2) 3043 self.assertEqual(complex(imag=42, real=666), complex(666, 42)) 3044 self.assertEqual(str(object=500), '500') 3045 self.assertEqual(str(object=b'abc', errors='strict'), 'abc') 3046 with self.assertRaisesRegex(TypeError, 'keyword argument'): 3047 tuple(sequence=range(3)) 3048 with self.assertRaisesRegex(TypeError, 'keyword argument'): 3049 list(sequence=(0, 1, 2)) 3050 # note: as of Python 2.3, dict() no longer has an "items" keyword arg 3051 3052 for constructor in (int, float, int, complex, str, str, 3053 tuple, list): 3054 try: 3055 constructor(bogus_keyword_arg=1) 3056 except TypeError: 3057 pass 3058 else: 3059 self.fail("expected TypeError from bogus keyword argument to %r" 3060 % constructor) 3061 3062 def test_str_subclass_as_dict_key(self): 3063 # Testing a str subclass used as dict key .. 3064 3065 class cistr(str): 3066 """Subclass of str that computes __eq__ case-insensitively. 3067 3068 Also computes a hash code of the string in canonical form. 3069 """ 3070 3071 def __init__(self, value): 3072 self.canonical = value.lower() 3073 self.hashcode = hash(self.canonical) 3074 3075 def __eq__(self, other): 3076 if not isinstance(other, cistr): 3077 other = cistr(other) 3078 return self.canonical == other.canonical 3079 3080 def __hash__(self): 3081 return self.hashcode 3082 3083 self.assertEqual(cistr('ABC'), 'abc') 3084 self.assertEqual('aBc', cistr('ABC')) 3085 self.assertEqual(str(cistr('ABC')), 'ABC') 3086 3087 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3} 3088 self.assertEqual(d[cistr('one')], 1) 3089 self.assertEqual(d[cistr('tWo')], 2) 3090 self.assertEqual(d[cistr('THrEE')], 3) 3091 self.assertIn(cistr('ONe'), d) 3092 self.assertEqual(d.get(cistr('thrEE')), 3) 3093 3094 def test_classic_comparisons(self): 3095 # Testing classic comparisons... 3096 class classic: 3097 pass 3098 3099 for base in (classic, int, object): 3100 class C(base): 3101 def __init__(self, value): 3102 self.value = int(value) 3103 def __eq__(self, other): 3104 if isinstance(other, C): 3105 return self.value == other.value 3106 if isinstance(other, int) or isinstance(other, int): 3107 return self.value == other 3108 return NotImplemented 3109 def __ne__(self, other): 3110 if isinstance(other, C): 3111 return self.value != other.value 3112 if isinstance(other, int) or isinstance(other, int): 3113 return self.value != other 3114 return NotImplemented 3115 def __lt__(self, other): 3116 if isinstance(other, C): 3117 return self.value < other.value 3118 if isinstance(other, int) or isinstance(other, int): 3119 return self.value < other 3120 return NotImplemented 3121 def __le__(self, other): 3122 if isinstance(other, C): 3123 return self.value <= other.value 3124 if isinstance(other, int) or isinstance(other, int): 3125 return self.value <= other 3126 return NotImplemented 3127 def __gt__(self, other): 3128 if isinstance(other, C): 3129 return self.value > other.value 3130 if isinstance(other, int) or isinstance(other, int): 3131 return self.value > other 3132 return NotImplemented 3133 def __ge__(self, other): 3134 if isinstance(other, C): 3135 return self.value >= other.value 3136 if isinstance(other, int) or isinstance(other, int): 3137 return self.value >= other 3138 return NotImplemented 3139 3140 c1 = C(1) 3141 c2 = C(2) 3142 c3 = C(3) 3143 self.assertEqual(c1, 1) 3144 c = {1: c1, 2: c2, 3: c3} 3145 for x in 1, 2, 3: 3146 for y in 1, 2, 3: 3147 for op in "<", "<=", "==", "!=", ">", ">=": 3148 self.assertEqual(eval("c[x] %s c[y]" % op), 3149 eval("x %s y" % op), 3150 "x=%d, y=%d" % (x, y)) 3151 self.assertEqual(eval("c[x] %s y" % op), 3152 eval("x %s y" % op), 3153 "x=%d, y=%d" % (x, y)) 3154 self.assertEqual(eval("x %s c[y]" % op), 3155 eval("x %s y" % op), 3156 "x=%d, y=%d" % (x, y)) 3157 3158 def test_rich_comparisons(self): 3159 # Testing rich comparisons... 3160 class Z(complex): 3161 pass 3162 z = Z(1) 3163 self.assertEqual(z, 1+0j) 3164 self.assertEqual(1+0j, z) 3165 class ZZ(complex): 3166 def __eq__(self, other): 3167 try: 3168 return abs(self - other) <= 1e-6 3169 except: 3170 return NotImplemented 3171 zz = ZZ(1.0000003) 3172 self.assertEqual(zz, 1+0j) 3173 self.assertEqual(1+0j, zz) 3174 3175 class classic: 3176 pass 3177 for base in (classic, int, object, list): 3178 class C(base): 3179 def __init__(self, value): 3180 self.value = int(value) 3181 def __cmp__(self_, other): 3182 self.fail("shouldn't call __cmp__") 3183 def __eq__(self, other): 3184 if isinstance(other, C): 3185 return self.value == other.value 3186 if isinstance(other, int) or isinstance(other, int): 3187 return self.value == other 3188 return NotImplemented 3189 def __ne__(self, other): 3190 if isinstance(other, C): 3191 return self.value != other.value 3192 if isinstance(other, int) or isinstance(other, int): 3193 return self.value != other 3194 return NotImplemented 3195 def __lt__(self, other): 3196 if isinstance(other, C): 3197 return self.value < other.value 3198 if isinstance(other, int) or isinstance(other, int): 3199 return self.value < other 3200 return NotImplemented 3201 def __le__(self, other): 3202 if isinstance(other, C): 3203 return self.value <= other.value 3204 if isinstance(other, int) or isinstance(other, int): 3205 return self.value <= other 3206 return NotImplemented 3207 def __gt__(self, other): 3208 if isinstance(other, C): 3209 return self.value > other.value 3210 if isinstance(other, int) or isinstance(other, int): 3211 return self.value > other 3212 return NotImplemented 3213 def __ge__(self, other): 3214 if isinstance(other, C): 3215 return self.value >= other.value 3216 if isinstance(other, int) or isinstance(other, int): 3217 return self.value >= other 3218 return NotImplemented 3219 c1 = C(1) 3220 c2 = C(2) 3221 c3 = C(3) 3222 self.assertEqual(c1, 1) 3223 c = {1: c1, 2: c2, 3: c3} 3224 for x in 1, 2, 3: 3225 for y in 1, 2, 3: 3226 for op in "<", "<=", "==", "!=", ">", ">=": 3227 self.assertEqual(eval("c[x] %s c[y]" % op), 3228 eval("x %s y" % op), 3229 "x=%d, y=%d" % (x, y)) 3230 self.assertEqual(eval("c[x] %s y" % op), 3231 eval("x %s y" % op), 3232 "x=%d, y=%d" % (x, y)) 3233 self.assertEqual(eval("x %s c[y]" % op), 3234 eval("x %s y" % op), 3235 "x=%d, y=%d" % (x, y)) 3236 3237 def test_descrdoc(self): 3238 # Testing descriptor doc strings... 3239 from _io import FileIO 3240 def check(descr, what): 3241 self.assertEqual(descr.__doc__, what) 3242 check(FileIO.closed, "True if the file is closed") # getset descriptor 3243 check(complex.real, "the real part of a complex number") # member descriptor 3244 3245 def test_doc_descriptor(self): 3246 # Testing __doc__ descriptor... 3247 # SF bug 542984 3248 class DocDescr(object): 3249 def __get__(self, object, otype): 3250 if object: 3251 object = object.__class__.__name__ + ' instance' 3252 if otype: 3253 otype = otype.__name__ 3254 return 'object=%s; type=%s' % (object, otype) 3255 class OldClass: 3256 __doc__ = DocDescr() 3257 class NewClass(object): 3258 __doc__ = DocDescr() 3259 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass') 3260 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass') 3261 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass') 3262 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass') 3263 3264 def test_set_class(self): 3265 # Testing __class__ assignment... 3266 class C(object): pass 3267 class D(object): pass 3268 class E(object): pass 3269 class F(D, E): pass 3270 for cls in C, D, E, F: 3271 for cls2 in C, D, E, F: 3272 x = cls() 3273 x.__class__ = cls2 3274 self.assertIs(x.__class__, cls2) 3275 x.__class__ = cls 3276 self.assertIs(x.__class__, cls) 3277 def cant(x, C): 3278 try: 3279 x.__class__ = C 3280 except TypeError: 3281 pass 3282 else: 3283 self.fail("shouldn't allow %r.__class__ = %r" % (x, C)) 3284 try: 3285 delattr(x, "__class__") 3286 except (TypeError, AttributeError): 3287 pass 3288 else: 3289 self.fail("shouldn't allow del %r.__class__" % x) 3290 cant(C(), list) 3291 cant(list(), C) 3292 cant(C(), 1) 3293 cant(C(), object) 3294 cant(object(), list) 3295 cant(list(), object) 3296 class Int(int): __slots__ = [] 3297 cant(True, int) 3298 cant(2, bool) 3299 o = object() 3300 cant(o, type(1)) 3301 cant(o, type(None)) 3302 del o 3303 class G(object): 3304 __slots__ = ["a", "b"] 3305 class H(object): 3306 __slots__ = ["b", "a"] 3307 class I(object): 3308 __slots__ = ["a", "b"] 3309 class J(object): 3310 __slots__ = ["c", "b"] 3311 class K(object): 3312 __slots__ = ["a", "b", "d"] 3313 class L(H): 3314 __slots__ = ["e"] 3315 class M(I): 3316 __slots__ = ["e"] 3317 class N(J): 3318 __slots__ = ["__weakref__"] 3319 class P(J): 3320 __slots__ = ["__dict__"] 3321 class Q(J): 3322 pass 3323 class R(J): 3324 __slots__ = ["__dict__", "__weakref__"] 3325 3326 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)): 3327 x = cls() 3328 x.a = 1 3329 x.__class__ = cls2 3330 self.assertIs(x.__class__, cls2, 3331 "assigning %r as __class__ for %r silently failed" % (cls2, x)) 3332 self.assertEqual(x.a, 1) 3333 x.__class__ = cls 3334 self.assertIs(x.__class__, cls, 3335 "assigning %r as __class__ for %r silently failed" % (cls, x)) 3336 self.assertEqual(x.a, 1) 3337 for cls in G, J, K, L, M, N, P, R, list, Int: 3338 for cls2 in G, J, K, L, M, N, P, R, list, Int: 3339 if cls is cls2: 3340 continue 3341 cant(cls(), cls2) 3342 3343 # Issue5283: when __class__ changes in __del__, the wrong 3344 # type gets DECREF'd. 3345 class O(object): 3346 pass 3347 class A(object): 3348 def __del__(self): 3349 self.__class__ = O 3350 l = [A() for x in range(100)] 3351 del l 3352 3353 def test_set_dict(self): 3354 # Testing __dict__ assignment... 3355 class C(object): pass 3356 a = C() 3357 a.__dict__ = {'b': 1} 3358 self.assertEqual(a.b, 1) 3359 def cant(x, dict): 3360 try: 3361 x.__dict__ = dict 3362 except (AttributeError, TypeError): 3363 pass 3364 else: 3365 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict)) 3366 cant(a, None) 3367 cant(a, []) 3368 cant(a, 1) 3369 del a.__dict__ # Deleting __dict__ is allowed 3370 3371 class Base(object): 3372 pass 3373 def verify_dict_readonly(x): 3374 """ 3375 x has to be an instance of a class inheriting from Base. 3376 """ 3377 cant(x, {}) 3378 try: 3379 del x.__dict__ 3380 except (AttributeError, TypeError): 3381 pass 3382 else: 3383 self.fail("shouldn't allow del %r.__dict__" % x) 3384 dict_descr = Base.__dict__["__dict__"] 3385 try: 3386 dict_descr.__set__(x, {}) 3387 except (AttributeError, TypeError): 3388 pass 3389 else: 3390 self.fail("dict_descr allowed access to %r's dict" % x) 3391 3392 # Classes don't allow __dict__ assignment and have readonly dicts 3393 class Meta1(type, Base): 3394 pass 3395 class Meta2(Base, type): 3396 pass 3397 class D(object, metaclass=Meta1): 3398 pass 3399 class E(object, metaclass=Meta2): 3400 pass 3401 for cls in C, D, E: 3402 verify_dict_readonly(cls) 3403 class_dict = cls.__dict__ 3404 try: 3405 class_dict["spam"] = "eggs" 3406 except TypeError: 3407 pass 3408 else: 3409 self.fail("%r's __dict__ can be modified" % cls) 3410 3411 # Modules also disallow __dict__ assignment 3412 class Module1(types.ModuleType, Base): 3413 pass 3414 class Module2(Base, types.ModuleType): 3415 pass 3416 for ModuleType in Module1, Module2: 3417 mod = ModuleType("spam") 3418 verify_dict_readonly(mod) 3419 mod.__dict__["spam"] = "eggs" 3420 3421 # Exception's __dict__ can be replaced, but not deleted 3422 # (at least not any more than regular exception's __dict__ can 3423 # be deleted; on CPython it is not the case, whereas on PyPy they 3424 # can, just like any other new-style instance's __dict__.) 3425 def can_delete_dict(e): 3426 try: 3427 del e.__dict__ 3428 except (TypeError, AttributeError): 3429 return False 3430 else: 3431 return True 3432 class Exception1(Exception, Base): 3433 pass 3434 class Exception2(Base, Exception): 3435 pass 3436 for ExceptionType in Exception, Exception1, Exception2: 3437 e = ExceptionType() 3438 e.__dict__ = {"a": 1} 3439 self.assertEqual(e.a, 1) 3440 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError())) 3441 3442 def test_binary_operator_override(self): 3443 # Testing overrides of binary operations... 3444 class I(int): 3445 def __repr__(self): 3446 return "I(%r)" % int(self) 3447 def __add__(self, other): 3448 return I(int(self) + int(other)) 3449 __radd__ = __add__ 3450 def __pow__(self, other, mod=None): 3451 if mod is None: 3452 return I(pow(int(self), int(other))) 3453 else: 3454 return I(pow(int(self), int(other), int(mod))) 3455 def __rpow__(self, other, mod=None): 3456 if mod is None: 3457 return I(pow(int(other), int(self), mod)) 3458 else: 3459 return I(pow(int(other), int(self), int(mod))) 3460 3461 self.assertEqual(repr(I(1) + I(2)), "I(3)") 3462 self.assertEqual(repr(I(1) + 2), "I(3)") 3463 self.assertEqual(repr(1 + I(2)), "I(3)") 3464 self.assertEqual(repr(I(2) ** I(3)), "I(8)") 3465 self.assertEqual(repr(2 ** I(3)), "I(8)") 3466 self.assertEqual(repr(I(2) ** 3), "I(8)") 3467 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)") 3468 class S(str): 3469 def __eq__(self, other): 3470 return self.lower() == other.lower() 3471 3472 def test_subclass_propagation(self): 3473 # Testing propagation of slot functions to subclasses... 3474 class A(object): 3475 pass 3476 class B(A): 3477 pass 3478 class C(A): 3479 pass 3480 class D(B, C): 3481 pass 3482 d = D() 3483 orig_hash = hash(d) # related to id(d) in platform-dependent ways 3484 A.__hash__ = lambda self: 42 3485 self.assertEqual(hash(d), 42) 3486 C.__hash__ = lambda self: 314 3487 self.assertEqual(hash(d), 314) 3488 B.__hash__ = lambda self: 144 3489 self.assertEqual(hash(d), 144) 3490 D.__hash__ = lambda self: 100 3491 self.assertEqual(hash(d), 100) 3492 D.__hash__ = None 3493 self.assertRaises(TypeError, hash, d) 3494 del D.__hash__ 3495 self.assertEqual(hash(d), 144) 3496 B.__hash__ = None 3497 self.assertRaises(TypeError, hash, d) 3498 del B.__hash__ 3499 self.assertEqual(hash(d), 314) 3500 C.__hash__ = None 3501 self.assertRaises(TypeError, hash, d) 3502 del C.__hash__ 3503 self.assertEqual(hash(d), 42) 3504 A.__hash__ = None 3505 self.assertRaises(TypeError, hash, d) 3506 del A.__hash__ 3507 self.assertEqual(hash(d), orig_hash) 3508 d.foo = 42 3509 d.bar = 42 3510 self.assertEqual(d.foo, 42) 3511 self.assertEqual(d.bar, 42) 3512 def __getattribute__(self, name): 3513 if name == "foo": 3514 return 24 3515 return object.__getattribute__(self, name) 3516 A.__getattribute__ = __getattribute__ 3517 self.assertEqual(d.foo, 24) 3518 self.assertEqual(d.bar, 42) 3519 def __getattr__(self, name): 3520 if name in ("spam", "foo", "bar"): 3521 return "hello" 3522 raise AttributeError(name) 3523 B.__getattr__ = __getattr__ 3524 self.assertEqual(d.spam, "hello") 3525 self.assertEqual(d.foo, 24) 3526 self.assertEqual(d.bar, 42) 3527 del A.__getattribute__ 3528 self.assertEqual(d.foo, 42) 3529 del d.foo 3530 self.assertEqual(d.foo, "hello") 3531 self.assertEqual(d.bar, 42) 3532 del B.__getattr__ 3533 try: 3534 d.foo 3535 except AttributeError: 3536 pass 3537 else: 3538 self.fail("d.foo should be undefined now") 3539 3540 # Test a nasty bug in recurse_down_subclasses() 3541 class A(object): 3542 pass 3543 class B(A): 3544 pass 3545 del B 3546 support.gc_collect() 3547 A.__setitem__ = lambda *a: None # crash 3548 3549 def test_buffer_inheritance(self): 3550 # Testing that buffer interface is inherited ... 3551 3552 import binascii 3553 # SF bug [#470040] ParseTuple t# vs subclasses. 3554 3555 class MyBytes(bytes): 3556 pass 3557 base = b'abc' 3558 m = MyBytes(base) 3559 # b2a_hex uses the buffer interface to get its argument's value, via 3560 # PyArg_ParseTuple 't#' code. 3561 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base)) 3562 3563 class MyInt(int): 3564 pass 3565 m = MyInt(42) 3566 try: 3567 binascii.b2a_hex(m) 3568 self.fail('subclass of int should not have a buffer interface') 3569 except TypeError: 3570 pass 3571 3572 def test_str_of_str_subclass(self): 3573 # Testing __str__ defined in subclass of str ... 3574 import binascii 3575 import io 3576 3577 class octetstring(str): 3578 def __str__(self): 3579 return binascii.b2a_hex(self.encode('ascii')).decode("ascii") 3580 def __repr__(self): 3581 return self + " repr" 3582 3583 o = octetstring('A') 3584 self.assertEqual(type(o), octetstring) 3585 self.assertEqual(type(str(o)), str) 3586 self.assertEqual(type(repr(o)), str) 3587 self.assertEqual(ord(o), 0x41) 3588 self.assertEqual(str(o), '41') 3589 self.assertEqual(repr(o), 'A repr') 3590 self.assertEqual(o.__str__(), '41') 3591 self.assertEqual(o.__repr__(), 'A repr') 3592 3593 def test_repr_with_module_str_subclass(self): 3594 # gh-98783 3595 class StrSub(str): 3596 pass 3597 class Some: 3598 pass 3599 Some.__module__ = StrSub('example') 3600 self.assertIsInstance(repr(Some), str) # should not crash 3601 self.assertIsInstance(repr(Some()), str) # should not crash 3602 3603 def test_keyword_arguments(self): 3604 # Testing keyword arguments to __init__, __call__... 3605 def f(a): return a 3606 self.assertEqual(f.__call__(a=42), 42) 3607 ba = bytearray() 3608 bytearray.__init__(ba, 'abc\xbd\u20ac', 3609 encoding='latin1', errors='replace') 3610 self.assertEqual(ba, b'abc\xbd?') 3611 3612 def test_recursive_call(self): 3613 # Testing recursive __call__() by setting to instance of class... 3614 class A(object): 3615 pass 3616 3617 A.__call__ = A() 3618 with self.assertRaises(RecursionError): 3619 A()() 3620 3621 def test_delete_hook(self): 3622 # Testing __del__ hook... 3623 log = [] 3624 class C(object): 3625 def __del__(self): 3626 log.append(1) 3627 c = C() 3628 self.assertEqual(log, []) 3629 del c 3630 support.gc_collect() 3631 self.assertEqual(log, [1]) 3632 3633 class D(object): pass 3634 d = D() 3635 try: del d[0] 3636 except TypeError: pass 3637 else: self.fail("invalid del() didn't raise TypeError") 3638 3639 def test_hash_inheritance(self): 3640 # Testing hash of mutable subclasses... 3641 3642 class mydict(dict): 3643 pass 3644 d = mydict() 3645 try: 3646 hash(d) 3647 except TypeError: 3648 pass 3649 else: 3650 self.fail("hash() of dict subclass should fail") 3651 3652 class mylist(list): 3653 pass 3654 d = mylist() 3655 try: 3656 hash(d) 3657 except TypeError: 3658 pass 3659 else: 3660 self.fail("hash() of list subclass should fail") 3661 3662 def test_str_operations(self): 3663 try: 'a' + 5 3664 except TypeError: pass 3665 else: self.fail("'' + 5 doesn't raise TypeError") 3666 3667 try: ''.split('') 3668 except ValueError: pass 3669 else: self.fail("''.split('') doesn't raise ValueError") 3670 3671 try: ''.join([0]) 3672 except TypeError: pass 3673 else: self.fail("''.join([0]) doesn't raise TypeError") 3674 3675 try: ''.rindex('5') 3676 except ValueError: pass 3677 else: self.fail("''.rindex('5') doesn't raise ValueError") 3678 3679 try: '%(n)s' % None 3680 except TypeError: pass 3681 else: self.fail("'%(n)s' % None doesn't raise TypeError") 3682 3683 try: '%(n' % {} 3684 except ValueError: pass 3685 else: self.fail("'%(n' % {} '' doesn't raise ValueError") 3686 3687 try: '%*s' % ('abc') 3688 except TypeError: pass 3689 else: self.fail("'%*s' % ('abc') doesn't raise TypeError") 3690 3691 try: '%*.*s' % ('abc', 5) 3692 except TypeError: pass 3693 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError") 3694 3695 try: '%s' % (1, 2) 3696 except TypeError: pass 3697 else: self.fail("'%s' % (1, 2) doesn't raise TypeError") 3698 3699 try: '%' % None 3700 except ValueError: pass 3701 else: self.fail("'%' % None doesn't raise ValueError") 3702 3703 self.assertEqual('534253'.isdigit(), 1) 3704 self.assertEqual('534253x'.isdigit(), 0) 3705 self.assertEqual('%c' % 5, '\x05') 3706 self.assertEqual('%c' % '5', '5') 3707 3708 def test_deepcopy_recursive(self): 3709 # Testing deepcopy of recursive objects... 3710 class Node: 3711 pass 3712 a = Node() 3713 b = Node() 3714 a.b = b 3715 b.a = a 3716 z = deepcopy(a) # This blew up before 3717 3718 def test_uninitialized_modules(self): 3719 # Testing uninitialized module objects... 3720 from types import ModuleType as M 3721 m = M.__new__(M) 3722 str(m) 3723 self.assertNotHasAttr(m, "__name__") 3724 self.assertNotHasAttr(m, "__file__") 3725 self.assertNotHasAttr(m, "foo") 3726 self.assertFalse(m.__dict__) # None or {} are both reasonable answers 3727 m.foo = 1 3728 self.assertEqual(m.__dict__, {"foo": 1}) 3729 3730 def test_funny_new(self): 3731 # Testing __new__ returning something unexpected... 3732 class C(object): 3733 def __new__(cls, arg): 3734 if isinstance(arg, str): return [1, 2, 3] 3735 elif isinstance(arg, int): return object.__new__(D) 3736 else: return object.__new__(cls) 3737 class D(C): 3738 def __init__(self, arg): 3739 self.foo = arg 3740 self.assertEqual(C("1"), [1, 2, 3]) 3741 self.assertEqual(D("1"), [1, 2, 3]) 3742 d = D(None) 3743 self.assertEqual(d.foo, None) 3744 d = C(1) 3745 self.assertIsInstance(d, D) 3746 self.assertEqual(d.foo, 1) 3747 d = D(1) 3748 self.assertIsInstance(d, D) 3749 self.assertEqual(d.foo, 1) 3750 3751 class C(object): 3752 @staticmethod 3753 def __new__(*args): 3754 return args 3755 self.assertEqual(C(1, 2), (C, 1, 2)) 3756 class D(C): 3757 pass 3758 self.assertEqual(D(1, 2), (D, 1, 2)) 3759 3760 class C(object): 3761 @classmethod 3762 def __new__(*args): 3763 return args 3764 self.assertEqual(C(1, 2), (C, C, 1, 2)) 3765 class D(C): 3766 pass 3767 self.assertEqual(D(1, 2), (D, D, 1, 2)) 3768 3769 def test_imul_bug(self): 3770 # Testing for __imul__ problems... 3771 # SF bug 544647 3772 class C(object): 3773 def __imul__(self, other): 3774 return (self, other) 3775 x = C() 3776 y = x 3777 y *= 1.0 3778 self.assertEqual(y, (x, 1.0)) 3779 y = x 3780 y *= 2 3781 self.assertEqual(y, (x, 2)) 3782 y = x 3783 y *= 3 3784 self.assertEqual(y, (x, 3)) 3785 y = x 3786 y *= 1<<100 3787 self.assertEqual(y, (x, 1<<100)) 3788 y = x 3789 y *= None 3790 self.assertEqual(y, (x, None)) 3791 y = x 3792 y *= "foo" 3793 self.assertEqual(y, (x, "foo")) 3794 3795 def test_copy_setstate(self): 3796 # Testing that copy.*copy() correctly uses __setstate__... 3797 import copy 3798 class C(object): 3799 def __init__(self, foo=None): 3800 self.foo = foo 3801 self.__foo = foo 3802 def setfoo(self, foo=None): 3803 self.foo = foo 3804 def getfoo(self): 3805 return self.__foo 3806 def __getstate__(self): 3807 return [self.foo] 3808 def __setstate__(self_, lst): 3809 self.assertEqual(len(lst), 1) 3810 self_.__foo = self_.foo = lst[0] 3811 a = C(42) 3812 a.setfoo(24) 3813 self.assertEqual(a.foo, 24) 3814 self.assertEqual(a.getfoo(), 42) 3815 b = copy.copy(a) 3816 self.assertEqual(b.foo, 24) 3817 self.assertEqual(b.getfoo(), 24) 3818 b = copy.deepcopy(a) 3819 self.assertEqual(b.foo, 24) 3820 self.assertEqual(b.getfoo(), 24) 3821 3822 def test_slices(self): 3823 # Testing cases with slices and overridden __getitem__ ... 3824 3825 # Strings 3826 self.assertEqual("hello"[:4], "hell") 3827 self.assertEqual("hello"[slice(4)], "hell") 3828 self.assertEqual(str.__getitem__("hello", slice(4)), "hell") 3829 class S(str): 3830 def __getitem__(self, x): 3831 return str.__getitem__(self, x) 3832 self.assertEqual(S("hello")[:4], "hell") 3833 self.assertEqual(S("hello")[slice(4)], "hell") 3834 self.assertEqual(S("hello").__getitem__(slice(4)), "hell") 3835 # Tuples 3836 self.assertEqual((1,2,3)[:2], (1,2)) 3837 self.assertEqual((1,2,3)[slice(2)], (1,2)) 3838 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2)) 3839 class T(tuple): 3840 def __getitem__(self, x): 3841 return tuple.__getitem__(self, x) 3842 self.assertEqual(T((1,2,3))[:2], (1,2)) 3843 self.assertEqual(T((1,2,3))[slice(2)], (1,2)) 3844 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2)) 3845 # Lists 3846 self.assertEqual([1,2,3][:2], [1,2]) 3847 self.assertEqual([1,2,3][slice(2)], [1,2]) 3848 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2]) 3849 class L(list): 3850 def __getitem__(self, x): 3851 return list.__getitem__(self, x) 3852 self.assertEqual(L([1,2,3])[:2], [1,2]) 3853 self.assertEqual(L([1,2,3])[slice(2)], [1,2]) 3854 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2]) 3855 # Now do lists and __setitem__ 3856 a = L([1,2,3]) 3857 a[slice(1, 3)] = [3,2] 3858 self.assertEqual(a, [1,3,2]) 3859 a[slice(0, 2, 1)] = [3,1] 3860 self.assertEqual(a, [3,1,2]) 3861 a.__setitem__(slice(1, 3), [2,1]) 3862 self.assertEqual(a, [3,2,1]) 3863 a.__setitem__(slice(0, 2, 1), [2,3]) 3864 self.assertEqual(a, [2,3,1]) 3865 3866 def test_subtype_resurrection(self): 3867 # Testing resurrection of new-style instance... 3868 3869 class C(object): 3870 container = [] 3871 3872 def __del__(self): 3873 # resurrect the instance 3874 C.container.append(self) 3875 3876 c = C() 3877 c.attr = 42 3878 3879 # The most interesting thing here is whether this blows up, due to 3880 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 3881 # bug). 3882 del c 3883 3884 support.gc_collect() 3885 self.assertEqual(len(C.container), 1) 3886 3887 # Make c mortal again, so that the test framework with -l doesn't report 3888 # it as a leak. 3889 del C.__del__ 3890 3891 def test_slots_trash(self): 3892 # Testing slot trash... 3893 # Deallocating deeply nested slotted trash caused stack overflows 3894 class trash(object): 3895 __slots__ = ['x'] 3896 def __init__(self, x): 3897 self.x = x 3898 o = None 3899 for i in range(50000): 3900 o = trash(o) 3901 del o 3902 3903 def test_slots_multiple_inheritance(self): 3904 # SF bug 575229, multiple inheritance w/ slots dumps core 3905 class A(object): 3906 __slots__=() 3907 class B(object): 3908 pass 3909 class C(A,B) : 3910 __slots__=() 3911 if support.check_impl_detail(): 3912 self.assertEqual(C.__basicsize__, B.__basicsize__) 3913 self.assertHasAttr(C, '__dict__') 3914 self.assertHasAttr(C, '__weakref__') 3915 C().x = 2 3916 3917 def test_rmul(self): 3918 # Testing correct invocation of __rmul__... 3919 # SF patch 592646 3920 class C(object): 3921 def __mul__(self, other): 3922 return "mul" 3923 def __rmul__(self, other): 3924 return "rmul" 3925 a = C() 3926 self.assertEqual(a*2, "mul") 3927 self.assertEqual(a*2.2, "mul") 3928 self.assertEqual(2*a, "rmul") 3929 self.assertEqual(2.2*a, "rmul") 3930 3931 def test_ipow(self): 3932 # Testing correct invocation of __ipow__... 3933 # [SF bug 620179] 3934 class C(object): 3935 def __ipow__(self, other): 3936 pass 3937 a = C() 3938 a **= 2 3939 3940 def test_ipow_returns_not_implemented(self): 3941 class A: 3942 def __ipow__(self, other): 3943 return NotImplemented 3944 3945 class B(A): 3946 def __rpow__(self, other): 3947 return 1 3948 3949 class C(A): 3950 def __pow__(self, other): 3951 return 2 3952 a = A() 3953 b = B() 3954 c = C() 3955 3956 a **= b 3957 self.assertEqual(a, 1) 3958 3959 c **= b 3960 self.assertEqual(c, 2) 3961 3962 def test_no_ipow(self): 3963 class B: 3964 def __rpow__(self, other): 3965 return 1 3966 3967 a = object() 3968 b = B() 3969 a **= b 3970 self.assertEqual(a, 1) 3971 3972 def test_ipow_exception_text(self): 3973 x = None 3974 with self.assertRaises(TypeError) as cm: 3975 x **= 2 3976 self.assertIn('unsupported operand type(s) for **=', str(cm.exception)) 3977 3978 with self.assertRaises(TypeError) as cm: 3979 y = x ** 2 3980 self.assertIn('unsupported operand type(s) for **', str(cm.exception)) 3981 3982 def test_mutable_bases(self): 3983 # Testing mutable bases... 3984 3985 # stuff that should work: 3986 class C(object): 3987 pass 3988 class C2(object): 3989 def __getattribute__(self, attr): 3990 if attr == 'a': 3991 return 2 3992 else: 3993 return super(C2, self).__getattribute__(attr) 3994 def meth(self): 3995 return 1 3996 class D(C): 3997 pass 3998 class E(D): 3999 pass 4000 d = D() 4001 e = E() 4002 D.__bases__ = (C,) 4003 D.__bases__ = (C2,) 4004 self.assertEqual(d.meth(), 1) 4005 self.assertEqual(e.meth(), 1) 4006 self.assertEqual(d.a, 2) 4007 self.assertEqual(e.a, 2) 4008 self.assertEqual(C2.__subclasses__(), [D]) 4009 4010 try: 4011 del D.__bases__ 4012 except (TypeError, AttributeError): 4013 pass 4014 else: 4015 self.fail("shouldn't be able to delete .__bases__") 4016 4017 try: 4018 D.__bases__ = () 4019 except TypeError as msg: 4020 if str(msg) == "a new-style class can't have only classic bases": 4021 self.fail("wrong error message for .__bases__ = ()") 4022 else: 4023 self.fail("shouldn't be able to set .__bases__ to ()") 4024 4025 try: 4026 D.__bases__ = (D,) 4027 except TypeError: 4028 pass 4029 else: 4030 # actually, we'll have crashed by here... 4031 self.fail("shouldn't be able to create inheritance cycles") 4032 4033 try: 4034 D.__bases__ = (C, C) 4035 except TypeError: 4036 pass 4037 else: 4038 self.fail("didn't detect repeated base classes") 4039 4040 try: 4041 D.__bases__ = (E,) 4042 except TypeError: 4043 pass 4044 else: 4045 self.fail("shouldn't be able to create inheritance cycles") 4046 4047 def test_builtin_bases(self): 4048 # Make sure all the builtin types can have their base queried without 4049 # segfaulting. See issue #5787. 4050 builtin_types = [tp for tp in builtins.__dict__.values() 4051 if isinstance(tp, type)] 4052 for tp in builtin_types: 4053 object.__getattribute__(tp, "__bases__") 4054 if tp is not object: 4055 if tp is ExceptionGroup: 4056 num_bases = 2 4057 else: 4058 num_bases = 1 4059 self.assertEqual(len(tp.__bases__), num_bases, tp) 4060 4061 class L(list): 4062 pass 4063 4064 class C(object): 4065 pass 4066 4067 class D(C): 4068 pass 4069 4070 try: 4071 L.__bases__ = (dict,) 4072 except TypeError: 4073 pass 4074 else: 4075 self.fail("shouldn't turn list subclass into dict subclass") 4076 4077 try: 4078 list.__bases__ = (dict,) 4079 except TypeError: 4080 pass 4081 else: 4082 self.fail("shouldn't be able to assign to list.__bases__") 4083 4084 try: 4085 D.__bases__ = (C, list) 4086 except TypeError: 4087 pass 4088 else: 4089 self.fail("best_base calculation found wanting") 4090 4091 def test_unsubclassable_types(self): 4092 with self.assertRaises(TypeError): 4093 class X(type(None)): 4094 pass 4095 with self.assertRaises(TypeError): 4096 class X(object, type(None)): 4097 pass 4098 with self.assertRaises(TypeError): 4099 class X(type(None), object): 4100 pass 4101 class O(object): 4102 pass 4103 with self.assertRaises(TypeError): 4104 class X(O, type(None)): 4105 pass 4106 with self.assertRaises(TypeError): 4107 class X(type(None), O): 4108 pass 4109 4110 class X(object): 4111 pass 4112 with self.assertRaises(TypeError): 4113 X.__bases__ = type(None), 4114 with self.assertRaises(TypeError): 4115 X.__bases__ = object, type(None) 4116 with self.assertRaises(TypeError): 4117 X.__bases__ = type(None), object 4118 with self.assertRaises(TypeError): 4119 X.__bases__ = O, type(None) 4120 with self.assertRaises(TypeError): 4121 X.__bases__ = type(None), O 4122 4123 def test_mutable_bases_with_failing_mro(self): 4124 # Testing mutable bases with failing mro... 4125 class WorkOnce(type): 4126 def __new__(self, name, bases, ns): 4127 self.flag = 0 4128 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns) 4129 def mro(self): 4130 if self.flag > 0: 4131 raise RuntimeError("bozo") 4132 else: 4133 self.flag += 1 4134 return type.mro(self) 4135 4136 class WorkAlways(type): 4137 def mro(self): 4138 # this is here to make sure that .mro()s aren't called 4139 # with an exception set (which was possible at one point). 4140 # An error message will be printed in a debug build. 4141 # What's a good way to test for this? 4142 return type.mro(self) 4143 4144 class C(object): 4145 pass 4146 4147 class C2(object): 4148 pass 4149 4150 class D(C): 4151 pass 4152 4153 class E(D): 4154 pass 4155 4156 class F(D, metaclass=WorkOnce): 4157 pass 4158 4159 class G(D, metaclass=WorkAlways): 4160 pass 4161 4162 # Immediate subclasses have their mro's adjusted in alphabetical 4163 # order, so E's will get adjusted before adjusting F's fails. We 4164 # check here that E's gets restored. 4165 4166 E_mro_before = E.__mro__ 4167 D_mro_before = D.__mro__ 4168 4169 try: 4170 D.__bases__ = (C2,) 4171 except RuntimeError: 4172 self.assertEqual(E.__mro__, E_mro_before) 4173 self.assertEqual(D.__mro__, D_mro_before) 4174 else: 4175 self.fail("exception not propagated") 4176 4177 def test_mutable_bases_catch_mro_conflict(self): 4178 # Testing mutable bases catch mro conflict... 4179 class A(object): 4180 pass 4181 4182 class B(object): 4183 pass 4184 4185 class C(A, B): 4186 pass 4187 4188 class D(A, B): 4189 pass 4190 4191 class E(C, D): 4192 pass 4193 4194 try: 4195 C.__bases__ = (B, A) 4196 except TypeError: 4197 pass 4198 else: 4199 self.fail("didn't catch MRO conflict") 4200 4201 def test_mutable_names(self): 4202 # Testing mutable names... 4203 class C(object): 4204 pass 4205 4206 # C.__module__ could be 'test_descr' or '__main__' 4207 mod = C.__module__ 4208 4209 C.__name__ = 'D' 4210 self.assertEqual((C.__module__, C.__name__), (mod, 'D')) 4211 4212 C.__name__ = 'D.E' 4213 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E')) 4214 4215 def test_evil_type_name(self): 4216 # A badly placed Py_DECREF in type_set_name led to arbitrary code 4217 # execution while the type structure was not in a sane state, and a 4218 # possible segmentation fault as a result. See bug #16447. 4219 class Nasty(str): 4220 def __del__(self): 4221 C.__name__ = "other" 4222 4223 class C: 4224 pass 4225 4226 C.__name__ = Nasty("abc") 4227 C.__name__ = "normal" 4228 4229 def test_subclass_right_op(self): 4230 # Testing correct dispatch of subclass overloading __r<op>__... 4231 4232 # This code tests various cases where right-dispatch of a subclass 4233 # should be preferred over left-dispatch of a base class. 4234 4235 # Case 1: subclass of int; this tests code in abstract.c::binary_op1() 4236 4237 class B(int): 4238 def __floordiv__(self, other): 4239 return "B.__floordiv__" 4240 def __rfloordiv__(self, other): 4241 return "B.__rfloordiv__" 4242 4243 self.assertEqual(B(1) // 1, "B.__floordiv__") 4244 self.assertEqual(1 // B(1), "B.__rfloordiv__") 4245 4246 # Case 2: subclass of object; this is just the baseline for case 3 4247 4248 class C(object): 4249 def __floordiv__(self, other): 4250 return "C.__floordiv__" 4251 def __rfloordiv__(self, other): 4252 return "C.__rfloordiv__" 4253 4254 self.assertEqual(C() // 1, "C.__floordiv__") 4255 self.assertEqual(1 // C(), "C.__rfloordiv__") 4256 4257 # Case 3: subclass of new-style class; here it gets interesting 4258 4259 class D(C): 4260 def __floordiv__(self, other): 4261 return "D.__floordiv__" 4262 def __rfloordiv__(self, other): 4263 return "D.__rfloordiv__" 4264 4265 self.assertEqual(D() // C(), "D.__floordiv__") 4266 self.assertEqual(C() // D(), "D.__rfloordiv__") 4267 4268 # Case 4: this didn't work right in 2.2.2 and 2.3a1 4269 4270 class E(C): 4271 pass 4272 4273 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__) 4274 4275 self.assertEqual(E() // 1, "C.__floordiv__") 4276 self.assertEqual(1 // E(), "C.__rfloordiv__") 4277 self.assertEqual(E() // C(), "C.__floordiv__") 4278 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail 4279 4280 @support.impl_detail("testing an internal kind of method object") 4281 def test_meth_class_get(self): 4282 # Testing __get__ method of METH_CLASS C methods... 4283 # Full coverage of descrobject.c::classmethod_get() 4284 4285 # Baseline 4286 arg = [1, 2, 3] 4287 res = {1: None, 2: None, 3: None} 4288 self.assertEqual(dict.fromkeys(arg), res) 4289 self.assertEqual({}.fromkeys(arg), res) 4290 4291 # Now get the descriptor 4292 descr = dict.__dict__["fromkeys"] 4293 4294 # More baseline using the descriptor directly 4295 self.assertEqual(descr.__get__(None, dict)(arg), res) 4296 self.assertEqual(descr.__get__({})(arg), res) 4297 4298 # Now check various error cases 4299 try: 4300 descr.__get__(None, None) 4301 except TypeError: 4302 pass 4303 else: 4304 self.fail("shouldn't have allowed descr.__get__(None, None)") 4305 try: 4306 descr.__get__(42) 4307 except TypeError: 4308 pass 4309 else: 4310 self.fail("shouldn't have allowed descr.__get__(42)") 4311 try: 4312 descr.__get__(None, 42) 4313 except TypeError: 4314 pass 4315 else: 4316 self.fail("shouldn't have allowed descr.__get__(None, 42)") 4317 try: 4318 descr.__get__(None, int) 4319 except TypeError: 4320 pass 4321 else: 4322 self.fail("shouldn't have allowed descr.__get__(None, int)") 4323 4324 def test_isinst_isclass(self): 4325 # Testing proxy isinstance() and isclass()... 4326 class Proxy(object): 4327 def __init__(self, obj): 4328 self.__obj = obj 4329 def __getattribute__(self, name): 4330 if name.startswith("_Proxy__"): 4331 return object.__getattribute__(self, name) 4332 else: 4333 return getattr(self.__obj, name) 4334 # Test with a classic class 4335 class C: 4336 pass 4337 a = C() 4338 pa = Proxy(a) 4339 self.assertIsInstance(a, C) # Baseline 4340 self.assertIsInstance(pa, C) # Test 4341 # Test with a classic subclass 4342 class D(C): 4343 pass 4344 a = D() 4345 pa = Proxy(a) 4346 self.assertIsInstance(a, C) # Baseline 4347 self.assertIsInstance(pa, C) # Test 4348 # Test with a new-style class 4349 class C(object): 4350 pass 4351 a = C() 4352 pa = Proxy(a) 4353 self.assertIsInstance(a, C) # Baseline 4354 self.assertIsInstance(pa, C) # Test 4355 # Test with a new-style subclass 4356 class D(C): 4357 pass 4358 a = D() 4359 pa = Proxy(a) 4360 self.assertIsInstance(a, C) # Baseline 4361 self.assertIsInstance(pa, C) # Test 4362 4363 def test_proxy_super(self): 4364 # Testing super() for a proxy object... 4365 class Proxy(object): 4366 def __init__(self, obj): 4367 self.__obj = obj 4368 def __getattribute__(self, name): 4369 if name.startswith("_Proxy__"): 4370 return object.__getattribute__(self, name) 4371 else: 4372 return getattr(self.__obj, name) 4373 4374 class B(object): 4375 def f(self): 4376 return "B.f" 4377 4378 class C(B): 4379 def f(self): 4380 return super(C, self).f() + "->C.f" 4381 4382 obj = C() 4383 p = Proxy(obj) 4384 self.assertEqual(C.__dict__["f"](p), "B.f->C.f") 4385 4386 def test_carloverre(self): 4387 # Testing prohibition of Carlo Verre's hack... 4388 try: 4389 object.__setattr__(str, "foo", 42) 4390 except TypeError: 4391 pass 4392 else: 4393 self.fail("Carlo Verre __setattr__ succeeded!") 4394 try: 4395 object.__delattr__(str, "lower") 4396 except TypeError: 4397 pass 4398 else: 4399 self.fail("Carlo Verre __delattr__ succeeded!") 4400 4401 def test_carloverre_multi_inherit_valid(self): 4402 class A(type): 4403 def __setattr__(cls, key, value): 4404 type.__setattr__(cls, key, value) 4405 4406 class B: 4407 pass 4408 4409 class C(B, A): 4410 pass 4411 4412 obj = C('D', (object,), {}) 4413 try: 4414 obj.test = True 4415 except TypeError: 4416 self.fail("setattr through direct base types should be legal") 4417 4418 def test_carloverre_multi_inherit_invalid(self): 4419 class A(type): 4420 def __setattr__(cls, key, value): 4421 object.__setattr__(cls, key, value) # this should fail! 4422 4423 class B: 4424 pass 4425 4426 class C(B, A): 4427 pass 4428 4429 obj = C('D', (object,), {}) 4430 try: 4431 obj.test = True 4432 except TypeError: 4433 pass 4434 else: 4435 self.fail("setattr through indirect base types should be rejected") 4436 4437 def test_weakref_segfault(self): 4438 # Testing weakref segfault... 4439 # SF 742911 4440 import weakref 4441 4442 class Provoker: 4443 def __init__(self, referrent): 4444 self.ref = weakref.ref(referrent) 4445 4446 def __del__(self): 4447 x = self.ref() 4448 4449 class Oops(object): 4450 pass 4451 4452 o = Oops() 4453 o.whatever = Provoker(o) 4454 del o 4455 4456 def test_wrapper_segfault(self): 4457 # SF 927248: deeply nested wrappers could cause stack overflow 4458 f = lambda:None 4459 for i in range(1000000): 4460 f = f.__call__ 4461 f = None 4462 4463 def test_file_fault(self): 4464 # Testing sys.stdout is changed in getattr... 4465 class StdoutGuard: 4466 def __getattr__(self, attr): 4467 sys.stdout = sys.__stdout__ 4468 raise RuntimeError(f"Premature access to sys.stdout.{attr}") 4469 4470 with redirect_stdout(StdoutGuard()): 4471 with self.assertRaises(RuntimeError): 4472 print("Oops!") 4473 4474 def test_vicious_descriptor_nonsense(self): 4475 # Testing vicious_descriptor_nonsense... 4476 4477 # A potential segfault spotted by Thomas Wouters in mail to 4478 # python-dev 2003-04-17, turned into an example & fixed by Michael 4479 # Hudson just less than four months later... 4480 4481 class Evil(object): 4482 def __hash__(self): 4483 return hash('attr') 4484 def __eq__(self, other): 4485 try: 4486 del C.attr 4487 except AttributeError: 4488 # possible race condition 4489 pass 4490 return 0 4491 4492 class Descr(object): 4493 def __get__(self, ob, type=None): 4494 return 1 4495 4496 class C(object): 4497 attr = Descr() 4498 4499 c = C() 4500 c.__dict__[Evil()] = 0 4501 4502 self.assertEqual(c.attr, 1) 4503 # this makes a crash more likely: 4504 support.gc_collect() 4505 self.assertNotHasAttr(c, 'attr') 4506 4507 def test_init(self): 4508 # SF 1155938 4509 class Foo(object): 4510 def __init__(self): 4511 return 10 4512 try: 4513 Foo() 4514 except TypeError: 4515 pass 4516 else: 4517 self.fail("did not test __init__() for None return") 4518 4519 def assertNotOrderable(self, a, b): 4520 with self.assertRaises(TypeError): 4521 a < b 4522 with self.assertRaises(TypeError): 4523 a > b 4524 with self.assertRaises(TypeError): 4525 a <= b 4526 with self.assertRaises(TypeError): 4527 a >= b 4528 4529 def test_method_wrapper(self): 4530 # Testing method-wrapper objects... 4531 # <type 'method-wrapper'> did not support any reflection before 2.5 4532 l = [] 4533 self.assertTrue(l.__add__ == l.__add__) 4534 self.assertFalse(l.__add__ != l.__add__) 4535 self.assertFalse(l.__add__ == [].__add__) 4536 self.assertTrue(l.__add__ != [].__add__) 4537 self.assertFalse(l.__add__ == l.__mul__) 4538 self.assertTrue(l.__add__ != l.__mul__) 4539 self.assertNotOrderable(l.__add__, l.__add__) 4540 self.assertEqual(l.__add__.__name__, '__add__') 4541 self.assertIs(l.__add__.__self__, l) 4542 self.assertIs(l.__add__.__objclass__, list) 4543 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__) 4544 # hash([].__add__) should not be based on hash([]) 4545 hash(l.__add__) 4546 4547 def test_builtin_function_or_method(self): 4548 # Not really belonging to test_descr, but introspection and 4549 # comparison on <type 'builtin_function_or_method'> seems not 4550 # to be tested elsewhere 4551 l = [] 4552 self.assertTrue(l.append == l.append) 4553 self.assertFalse(l.append != l.append) 4554 self.assertFalse(l.append == [].append) 4555 self.assertTrue(l.append != [].append) 4556 self.assertFalse(l.append == l.pop) 4557 self.assertTrue(l.append != l.pop) 4558 self.assertNotOrderable(l.append, l.append) 4559 self.assertEqual(l.append.__name__, 'append') 4560 self.assertIs(l.append.__self__, l) 4561 # self.assertIs(l.append.__objclass__, list) --- could be added? 4562 self.assertEqual(l.append.__doc__, list.append.__doc__) 4563 # hash([].append) should not be based on hash([]) 4564 hash(l.append) 4565 4566 def test_special_unbound_method_types(self): 4567 # Testing objects of <type 'wrapper_descriptor'>... 4568 self.assertTrue(list.__add__ == list.__add__) 4569 self.assertFalse(list.__add__ != list.__add__) 4570 self.assertFalse(list.__add__ == list.__mul__) 4571 self.assertTrue(list.__add__ != list.__mul__) 4572 self.assertNotOrderable(list.__add__, list.__add__) 4573 self.assertEqual(list.__add__.__name__, '__add__') 4574 self.assertIs(list.__add__.__objclass__, list) 4575 4576 # Testing objects of <type 'method_descriptor'>... 4577 self.assertTrue(list.append == list.append) 4578 self.assertFalse(list.append != list.append) 4579 self.assertFalse(list.append == list.pop) 4580 self.assertTrue(list.append != list.pop) 4581 self.assertNotOrderable(list.append, list.append) 4582 self.assertEqual(list.append.__name__, 'append') 4583 self.assertIs(list.append.__objclass__, list) 4584 4585 def test_not_implemented(self): 4586 # Testing NotImplemented... 4587 # all binary methods should be able to return a NotImplemented 4588 import operator 4589 4590 def specialmethod(self, other): 4591 return NotImplemented 4592 4593 def check(expr, x, y): 4594 try: 4595 exec(expr, {'x': x, 'y': y, 'operator': operator}) 4596 except TypeError: 4597 pass 4598 else: 4599 self.fail("no TypeError from %r" % (expr,)) 4600 4601 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of 4602 # TypeErrors 4603 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger 4604 # ValueErrors instead of TypeErrors 4605 for name, expr, iexpr in [ 4606 ('__add__', 'x + y', 'x += y'), 4607 ('__sub__', 'x - y', 'x -= y'), 4608 ('__mul__', 'x * y', 'x *= y'), 4609 ('__matmul__', 'x @ y', 'x @= y'), 4610 ('__truediv__', 'x / y', 'x /= y'), 4611 ('__floordiv__', 'x // y', 'x //= y'), 4612 ('__mod__', 'x % y', 'x %= y'), 4613 ('__divmod__', 'divmod(x, y)', None), 4614 ('__pow__', 'x ** y', 'x **= y'), 4615 ('__lshift__', 'x << y', 'x <<= y'), 4616 ('__rshift__', 'x >> y', 'x >>= y'), 4617 ('__and__', 'x & y', 'x &= y'), 4618 ('__or__', 'x | y', 'x |= y'), 4619 ('__xor__', 'x ^ y', 'x ^= y')]: 4620 rname = '__r' + name[2:] 4621 A = type('A', (), {name: specialmethod}) 4622 a = A() 4623 check(expr, a, a) 4624 check(expr, a, N1) 4625 check(expr, a, N2) 4626 if iexpr: 4627 check(iexpr, a, a) 4628 check(iexpr, a, N1) 4629 check(iexpr, a, N2) 4630 iname = '__i' + name[2:] 4631 C = type('C', (), {iname: specialmethod}) 4632 c = C() 4633 check(iexpr, c, a) 4634 check(iexpr, c, N1) 4635 check(iexpr, c, N2) 4636 4637 def test_assign_slice(self): 4638 # ceval.c's assign_slice used to check for 4639 # tp->tp_as_sequence->sq_slice instead of 4640 # tp->tp_as_sequence->sq_ass_slice 4641 4642 class C(object): 4643 def __setitem__(self, idx, value): 4644 self.value = value 4645 4646 c = C() 4647 c[1:2] = 3 4648 self.assertEqual(c.value, 3) 4649 4650 def test_set_and_no_get(self): 4651 # See 4652 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html 4653 class Descr(object): 4654 4655 def __init__(self, name): 4656 self.name = name 4657 4658 def __set__(self, obj, value): 4659 obj.__dict__[self.name] = value 4660 descr = Descr("a") 4661 4662 class X(object): 4663 a = descr 4664 4665 x = X() 4666 self.assertIs(x.a, descr) 4667 x.a = 42 4668 self.assertEqual(x.a, 42) 4669 4670 # Also check type_getattro for correctness. 4671 class Meta(type): 4672 pass 4673 class X(metaclass=Meta): 4674 pass 4675 X.a = 42 4676 Meta.a = Descr("a") 4677 self.assertEqual(X.a, 42) 4678 4679 def test_getattr_hooks(self): 4680 # issue 4230 4681 4682 class Descriptor(object): 4683 counter = 0 4684 def __get__(self, obj, objtype=None): 4685 def getter(name): 4686 self.counter += 1 4687 raise AttributeError(name) 4688 return getter 4689 4690 descr = Descriptor() 4691 class A(object): 4692 __getattribute__ = descr 4693 class B(object): 4694 __getattr__ = descr 4695 class C(object): 4696 __getattribute__ = descr 4697 __getattr__ = descr 4698 4699 self.assertRaises(AttributeError, getattr, A(), "attr") 4700 self.assertEqual(descr.counter, 1) 4701 self.assertRaises(AttributeError, getattr, B(), "attr") 4702 self.assertEqual(descr.counter, 2) 4703 self.assertRaises(AttributeError, getattr, C(), "attr") 4704 self.assertEqual(descr.counter, 4) 4705 4706 class EvilGetattribute(object): 4707 # This used to segfault 4708 def __getattr__(self, name): 4709 raise AttributeError(name) 4710 def __getattribute__(self, name): 4711 del EvilGetattribute.__getattr__ 4712 for i in range(5): 4713 gc.collect() 4714 raise AttributeError(name) 4715 4716 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr") 4717 4718 def test_type___getattribute__(self): 4719 self.assertRaises(TypeError, type.__getattribute__, list, type) 4720 4721 def test_abstractmethods(self): 4722 # type pretends not to have __abstractmethods__. 4723 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__") 4724 class meta(type): 4725 pass 4726 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__") 4727 class X(object): 4728 pass 4729 with self.assertRaises(AttributeError): 4730 del X.__abstractmethods__ 4731 4732 def test_proxy_call(self): 4733 class FakeStr: 4734 __class__ = str 4735 4736 fake_str = FakeStr() 4737 # isinstance() reads __class__ 4738 self.assertIsInstance(fake_str, str) 4739 4740 # call a method descriptor 4741 with self.assertRaises(TypeError): 4742 str.split(fake_str) 4743 4744 # call a slot wrapper descriptor 4745 with self.assertRaises(TypeError): 4746 str.__add__(fake_str, "abc") 4747 4748 def test_specialized_method_calls_check_types(self): 4749 # https://github.com/python/cpython/issues/92063 4750 class Thing: 4751 pass 4752 thing = Thing() 4753 for i in range(20): 4754 with self.assertRaises(TypeError): 4755 # PRECALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS 4756 list.sort(thing) 4757 for i in range(20): 4758 with self.assertRaises(TypeError): 4759 # PRECALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS 4760 str.split(thing) 4761 for i in range(20): 4762 with self.assertRaises(TypeError): 4763 # PRECALL_NO_KW_METHOD_DESCRIPTOR_NOARGS 4764 str.upper(thing) 4765 for i in range(20): 4766 with self.assertRaises(TypeError): 4767 # PRECALL_NO_KW_METHOD_DESCRIPTOR_FAST 4768 str.strip(thing) 4769 from collections import deque 4770 for i in range(20): 4771 with self.assertRaises(TypeError): 4772 # PRECALL_NO_KW_METHOD_DESCRIPTOR_O 4773 deque.append(thing, thing) 4774 4775 def test_repr_as_str(self): 4776 # Issue #11603: crash or infinite loop when rebinding __str__ as 4777 # __repr__. 4778 class Foo: 4779 pass 4780 Foo.__repr__ = Foo.__str__ 4781 foo = Foo() 4782 self.assertRaises(RecursionError, str, foo) 4783 self.assertRaises(RecursionError, repr, foo) 4784 4785 def test_mixing_slot_wrappers(self): 4786 class X(dict): 4787 __setattr__ = dict.__setitem__ 4788 __neg__ = dict.copy 4789 x = X() 4790 x.y = 42 4791 self.assertEqual(x["y"], 42) 4792 self.assertEqual(x, -x) 4793 4794 def test_wrong_class_slot_wrapper(self): 4795 # Check bpo-37619: a wrapper descriptor taken from the wrong class 4796 # should raise an exception instead of silently being ignored 4797 class A(int): 4798 __eq__ = str.__eq__ 4799 __add__ = str.__add__ 4800 a = A() 4801 with self.assertRaises(TypeError): 4802 a == a 4803 with self.assertRaises(TypeError): 4804 a + a 4805 4806 def test_slot_shadows_class_variable(self): 4807 with self.assertRaises(ValueError) as cm: 4808 class X: 4809 __slots__ = ["foo"] 4810 foo = None 4811 m = str(cm.exception) 4812 self.assertEqual("'foo' in __slots__ conflicts with class variable", m) 4813 4814 def test_set_doc(self): 4815 class X: 4816 "elephant" 4817 X.__doc__ = "banana" 4818 self.assertEqual(X.__doc__, "banana") 4819 4820 with self.assertRaises(TypeError) as cm: 4821 type(list).__dict__["__doc__"].__set__(list, "blah") 4822 self.assertIn("cannot set '__doc__' attribute of immutable type 'list'", str(cm.exception)) 4823 4824 with self.assertRaises(TypeError) as cm: 4825 type(X).__dict__["__doc__"].__delete__(X) 4826 self.assertIn("cannot delete '__doc__' attribute of immutable type 'X'", str(cm.exception)) 4827 self.assertEqual(X.__doc__, "banana") 4828 4829 def test_qualname(self): 4830 descriptors = [str.lower, complex.real, float.real, int.__add__] 4831 types = ['method', 'member', 'getset', 'wrapper'] 4832 4833 # make sure we have an example of each type of descriptor 4834 for d, n in zip(descriptors, types): 4835 self.assertEqual(type(d).__name__, n + '_descriptor') 4836 4837 for d in descriptors: 4838 qualname = d.__objclass__.__qualname__ + '.' + d.__name__ 4839 self.assertEqual(d.__qualname__, qualname) 4840 4841 self.assertEqual(str.lower.__qualname__, 'str.lower') 4842 self.assertEqual(complex.real.__qualname__, 'complex.real') 4843 self.assertEqual(float.real.__qualname__, 'float.real') 4844 self.assertEqual(int.__add__.__qualname__, 'int.__add__') 4845 4846 class X: 4847 pass 4848 with self.assertRaises(TypeError): 4849 del X.__qualname__ 4850 4851 self.assertRaises(TypeError, type.__dict__['__qualname__'].__set__, 4852 str, 'Oink') 4853 4854 global Y 4855 class Y: 4856 class Inside: 4857 pass 4858 self.assertEqual(Y.__qualname__, 'Y') 4859 self.assertEqual(Y.Inside.__qualname__, 'Y.Inside') 4860 4861 def test_qualname_dict(self): 4862 ns = {'__qualname__': 'some.name'} 4863 tp = type('Foo', (), ns) 4864 self.assertEqual(tp.__qualname__, 'some.name') 4865 self.assertNotIn('__qualname__', tp.__dict__) 4866 self.assertEqual(ns, {'__qualname__': 'some.name'}) 4867 4868 ns = {'__qualname__': 1} 4869 self.assertRaises(TypeError, type, 'Foo', (), ns) 4870 4871 def test_cycle_through_dict(self): 4872 # See bug #1469629 4873 class X(dict): 4874 def __init__(self): 4875 dict.__init__(self) 4876 self.__dict__ = self 4877 x = X() 4878 x.attr = 42 4879 wr = weakref.ref(x) 4880 del x 4881 support.gc_collect() 4882 self.assertIsNone(wr()) 4883 for o in gc.get_objects(): 4884 self.assertIsNot(type(o), X) 4885 4886 def test_object_new_and_init_with_parameters(self): 4887 # See issue #1683368 4888 class OverrideNeither: 4889 pass 4890 self.assertRaises(TypeError, OverrideNeither, 1) 4891 self.assertRaises(TypeError, OverrideNeither, kw=1) 4892 class OverrideNew: 4893 def __new__(cls, foo, kw=0, *args, **kwds): 4894 return object.__new__(cls, *args, **kwds) 4895 class OverrideInit: 4896 def __init__(self, foo, kw=0, *args, **kwargs): 4897 return object.__init__(self, *args, **kwargs) 4898 class OverrideBoth(OverrideNew, OverrideInit): 4899 pass 4900 for case in OverrideNew, OverrideInit, OverrideBoth: 4901 case(1) 4902 case(1, kw=2) 4903 self.assertRaises(TypeError, case, 1, 2, 3) 4904 self.assertRaises(TypeError, case, 1, 2, foo=3) 4905 4906 def test_subclassing_does_not_duplicate_dict_descriptors(self): 4907 class Base: 4908 pass 4909 class Sub(Base): 4910 pass 4911 self.assertIn("__dict__", Base.__dict__) 4912 self.assertNotIn("__dict__", Sub.__dict__) 4913 4914 def test_bound_method_repr(self): 4915 class Foo: 4916 def method(self): 4917 pass 4918 self.assertRegex(repr(Foo().method), 4919 r"<bound method .*Foo\.method of <.*Foo object at .*>>") 4920 4921 4922 class Base: 4923 def method(self): 4924 pass 4925 class Derived1(Base): 4926 pass 4927 class Derived2(Base): 4928 def method(self): 4929 pass 4930 base = Base() 4931 derived1 = Derived1() 4932 derived2 = Derived2() 4933 super_d2 = super(Derived2, derived2) 4934 self.assertRegex(repr(base.method), 4935 r"<bound method .*Base\.method of <.*Base object at .*>>") 4936 self.assertRegex(repr(derived1.method), 4937 r"<bound method .*Base\.method of <.*Derived1 object at .*>>") 4938 self.assertRegex(repr(derived2.method), 4939 r"<bound method .*Derived2\.method of <.*Derived2 object at .*>>") 4940 self.assertRegex(repr(super_d2.method), 4941 r"<bound method .*Base\.method of <.*Derived2 object at .*>>") 4942 4943 class Foo: 4944 @classmethod 4945 def method(cls): 4946 pass 4947 foo = Foo() 4948 self.assertRegex(repr(foo.method), # access via instance 4949 r"<bound method .*Foo\.method of <class '.*Foo'>>") 4950 self.assertRegex(repr(Foo.method), # access via the class 4951 r"<bound method .*Foo\.method of <class '.*Foo'>>") 4952 4953 4954 class MyCallable: 4955 def __call__(self, arg): 4956 pass 4957 func = MyCallable() # func has no __name__ or __qualname__ attributes 4958 instance = object() 4959 method = types.MethodType(func, instance) 4960 self.assertRegex(repr(method), 4961 r"<bound method \? of <object object at .*>>") 4962 func.__name__ = "name" 4963 self.assertRegex(repr(method), 4964 r"<bound method name of <object object at .*>>") 4965 func.__qualname__ = "qualname" 4966 self.assertRegex(repr(method), 4967 r"<bound method qualname of <object object at .*>>") 4968 4969 @unittest.skipIf(_testcapi is None, 'need the _testcapi module') 4970 def test_bpo25750(self): 4971 # bpo-25750: calling a descriptor (implemented as built-in 4972 # function with METH_FASTCALL) should not crash CPython if the 4973 # descriptor deletes itself from the class. 4974 class Descr: 4975 __get__ = _testcapi.bad_get 4976 4977 class X: 4978 descr = Descr() 4979 def __new__(cls): 4980 cls.descr = None 4981 # Create this large list to corrupt some unused memory 4982 cls.lst = [2**i for i in range(10000)] 4983 X.descr 4984 4985 def test_remove_subclass(self): 4986 # bpo-46417: when the last subclass of a type is deleted, 4987 # remove_subclass() clears the internal dictionary of subclasses: 4988 # set PyTypeObject.tp_subclasses to NULL. remove_subclass() is called 4989 # when a type is deallocated. 4990 class Parent: 4991 pass 4992 self.assertEqual(Parent.__subclasses__(), []) 4993 4994 class Child(Parent): 4995 pass 4996 self.assertEqual(Parent.__subclasses__(), [Child]) 4997 4998 del Child 4999 gc.collect() 5000 self.assertEqual(Parent.__subclasses__(), []) 5001 5002 def test_attr_raise_through_property(self): 5003 # add test case for gh-103272 5004 class A: 5005 def __getattr__(self, name): 5006 raise ValueError("FOO") 5007 5008 @property 5009 def foo(self): 5010 return self.__getattr__("asdf") 5011 5012 with self.assertRaisesRegex(ValueError, "FOO"): 5013 A().foo 5014 5015 5016class DictProxyTests(unittest.TestCase): 5017 def setUp(self): 5018 class C(object): 5019 def meth(self): 5020 pass 5021 self.C = C 5022 5023 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(), 5024 'trace function introduces __local__') 5025 def test_iter_keys(self): 5026 # Testing dict-proxy keys... 5027 it = self.C.__dict__.keys() 5028 self.assertNotIsInstance(it, list) 5029 keys = list(it) 5030 keys.sort() 5031 self.assertEqual(keys, ['__dict__', '__doc__', '__module__', 5032 '__weakref__', 'meth']) 5033 5034 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(), 5035 'trace function introduces __local__') 5036 def test_iter_values(self): 5037 # Testing dict-proxy values... 5038 it = self.C.__dict__.values() 5039 self.assertNotIsInstance(it, list) 5040 values = list(it) 5041 self.assertEqual(len(values), 5) 5042 5043 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(), 5044 'trace function introduces __local__') 5045 def test_iter_items(self): 5046 # Testing dict-proxy iteritems... 5047 it = self.C.__dict__.items() 5048 self.assertNotIsInstance(it, list) 5049 keys = [item[0] for item in it] 5050 keys.sort() 5051 self.assertEqual(keys, ['__dict__', '__doc__', '__module__', 5052 '__weakref__', 'meth']) 5053 5054 def test_dict_type_with_metaclass(self): 5055 # Testing type of __dict__ when metaclass set... 5056 class B(object): 5057 pass 5058 class M(type): 5059 pass 5060 class C(metaclass=M): 5061 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy 5062 pass 5063 self.assertEqual(type(C.__dict__), type(B.__dict__)) 5064 5065 def test_repr(self): 5066 # Testing mappingproxy.__repr__. 5067 # We can't blindly compare with the repr of another dict as ordering 5068 # of keys and values is arbitrary and may differ. 5069 r = repr(self.C.__dict__) 5070 self.assertTrue(r.startswith('mappingproxy('), r) 5071 self.assertTrue(r.endswith(')'), r) 5072 for k, v in self.C.__dict__.items(): 5073 self.assertIn('{!r}: {!r}'.format(k, v), r) 5074 5075 5076class AAAPTypesLongInitTest(unittest.TestCase): 5077 # This is in its own TestCase so that it can be run before any other tests. 5078 # (Hence the 'AAA' in the test class name: to make it the first 5079 # item in a list sorted by name, like 5080 # unittest.TestLoader.getTestCaseNames() does.) 5081 def test_pytype_long_ready(self): 5082 # Testing SF bug 551412 ... 5083 5084 # This dumps core when SF bug 551412 isn't fixed -- 5085 # but only when test_descr.py is run separately. 5086 # (That can't be helped -- as soon as PyType_Ready() 5087 # is called for PyLong_Type, the bug is gone.) 5088 class UserLong(object): 5089 def __pow__(self, *args): 5090 pass 5091 try: 5092 pow(0, UserLong(), 0) 5093 except: 5094 pass 5095 5096 # Another segfault only when run early 5097 # (before PyType_Ready(tuple) is called) 5098 type.mro(tuple) 5099 5100 5101class MiscTests(unittest.TestCase): 5102 def test_type_lookup_mro_reference(self): 5103 # Issue #14199: _PyType_Lookup() has to keep a strong reference to 5104 # the type MRO because it may be modified during the lookup, if 5105 # __bases__ is set during the lookup for example. 5106 class MyKey(object): 5107 def __hash__(self): 5108 return hash('mykey') 5109 5110 def __eq__(self, other): 5111 X.__bases__ = (Base2,) 5112 5113 class Base(object): 5114 mykey = 'from Base' 5115 mykey2 = 'from Base' 5116 5117 class Base2(object): 5118 mykey = 'from Base2' 5119 mykey2 = 'from Base2' 5120 5121 X = type('X', (Base,), {MyKey(): 5}) 5122 # mykey is read from Base 5123 self.assertEqual(X.mykey, 'from Base') 5124 # mykey2 is read from Base2 because MyKey.__eq__ has set __bases__ 5125 self.assertEqual(X.mykey2, 'from Base2') 5126 5127 5128class PicklingTests(unittest.TestCase): 5129 5130 def _check_reduce(self, proto, obj, args=(), kwargs={}, state=None, 5131 listitems=None, dictitems=None): 5132 if proto >= 2: 5133 reduce_value = obj.__reduce_ex__(proto) 5134 if kwargs: 5135 self.assertEqual(reduce_value[0], copyreg.__newobj_ex__) 5136 self.assertEqual(reduce_value[1], (type(obj), args, kwargs)) 5137 else: 5138 self.assertEqual(reduce_value[0], copyreg.__newobj__) 5139 self.assertEqual(reduce_value[1], (type(obj),) + args) 5140 self.assertEqual(reduce_value[2], state) 5141 if listitems is not None: 5142 self.assertListEqual(list(reduce_value[3]), listitems) 5143 else: 5144 self.assertIsNone(reduce_value[3]) 5145 if dictitems is not None: 5146 self.assertDictEqual(dict(reduce_value[4]), dictitems) 5147 else: 5148 self.assertIsNone(reduce_value[4]) 5149 else: 5150 base_type = type(obj).__base__ 5151 reduce_value = (copyreg._reconstructor, 5152 (type(obj), 5153 base_type, 5154 None if base_type is object else base_type(obj))) 5155 if state is not None: 5156 reduce_value += (state,) 5157 self.assertEqual(obj.__reduce_ex__(proto), reduce_value) 5158 self.assertEqual(obj.__reduce__(), reduce_value) 5159 5160 def test_reduce(self): 5161 protocols = range(pickle.HIGHEST_PROTOCOL + 1) 5162 args = (-101, "spam") 5163 kwargs = {'bacon': -201, 'fish': -301} 5164 state = {'cheese': -401} 5165 5166 class C1: 5167 def __getnewargs__(self): 5168 return args 5169 obj = C1() 5170 for proto in protocols: 5171 self._check_reduce(proto, obj, args) 5172 5173 for name, value in state.items(): 5174 setattr(obj, name, value) 5175 for proto in protocols: 5176 self._check_reduce(proto, obj, args, state=state) 5177 5178 class C2: 5179 def __getnewargs__(self): 5180 return "bad args" 5181 obj = C2() 5182 for proto in protocols: 5183 if proto >= 2: 5184 with self.assertRaises(TypeError): 5185 obj.__reduce_ex__(proto) 5186 5187 class C3: 5188 def __getnewargs_ex__(self): 5189 return (args, kwargs) 5190 obj = C3() 5191 for proto in protocols: 5192 if proto >= 2: 5193 self._check_reduce(proto, obj, args, kwargs) 5194 5195 class C4: 5196 def __getnewargs_ex__(self): 5197 return (args, "bad dict") 5198 class C5: 5199 def __getnewargs_ex__(self): 5200 return ("bad tuple", kwargs) 5201 class C6: 5202 def __getnewargs_ex__(self): 5203 return () 5204 class C7: 5205 def __getnewargs_ex__(self): 5206 return "bad args" 5207 for proto in protocols: 5208 for cls in C4, C5, C6, C7: 5209 obj = cls() 5210 if proto >= 2: 5211 with self.assertRaises((TypeError, ValueError)): 5212 obj.__reduce_ex__(proto) 5213 5214 class C9: 5215 def __getnewargs_ex__(self): 5216 return (args, {}) 5217 obj = C9() 5218 for proto in protocols: 5219 self._check_reduce(proto, obj, args) 5220 5221 class C10: 5222 def __getnewargs_ex__(self): 5223 raise IndexError 5224 obj = C10() 5225 for proto in protocols: 5226 if proto >= 2: 5227 with self.assertRaises(IndexError): 5228 obj.__reduce_ex__(proto) 5229 5230 class C11: 5231 def __getstate__(self): 5232 return state 5233 obj = C11() 5234 for proto in protocols: 5235 self._check_reduce(proto, obj, state=state) 5236 5237 class C12: 5238 def __getstate__(self): 5239 return "not dict" 5240 obj = C12() 5241 for proto in protocols: 5242 self._check_reduce(proto, obj, state="not dict") 5243 5244 class C13: 5245 def __getstate__(self): 5246 raise IndexError 5247 obj = C13() 5248 for proto in protocols: 5249 with self.assertRaises(IndexError): 5250 obj.__reduce_ex__(proto) 5251 if proto < 2: 5252 with self.assertRaises(IndexError): 5253 obj.__reduce__() 5254 5255 class C14: 5256 __slots__ = tuple(state) 5257 def __init__(self): 5258 for name, value in state.items(): 5259 setattr(self, name, value) 5260 5261 obj = C14() 5262 for proto in protocols: 5263 if proto >= 2: 5264 self._check_reduce(proto, obj, state=(None, state)) 5265 else: 5266 with self.assertRaises(TypeError): 5267 obj.__reduce_ex__(proto) 5268 with self.assertRaises(TypeError): 5269 obj.__reduce__() 5270 5271 class C15(dict): 5272 pass 5273 obj = C15({"quebec": -601}) 5274 for proto in protocols: 5275 self._check_reduce(proto, obj, dictitems=dict(obj)) 5276 5277 class C16(list): 5278 pass 5279 obj = C16(["yukon"]) 5280 for proto in protocols: 5281 self._check_reduce(proto, obj, listitems=list(obj)) 5282 5283 def test_special_method_lookup(self): 5284 protocols = range(pickle.HIGHEST_PROTOCOL + 1) 5285 class Picky: 5286 def __getstate__(self): 5287 return {} 5288 5289 def __getattr__(self, attr): 5290 if attr in ("__getnewargs__", "__getnewargs_ex__"): 5291 raise AssertionError(attr) 5292 return None 5293 for protocol in protocols: 5294 state = {} if protocol >= 2 else None 5295 self._check_reduce(protocol, Picky(), state=state) 5296 5297 def _assert_is_copy(self, obj, objcopy, msg=None): 5298 """Utility method to verify if two objects are copies of each others. 5299 """ 5300 if msg is None: 5301 msg = "{!r} is not a copy of {!r}".format(obj, objcopy) 5302 if type(obj).__repr__ is object.__repr__: 5303 # We have this limitation for now because we use the object's repr 5304 # to help us verify that the two objects are copies. This allows 5305 # us to delegate the non-generic verification logic to the objects 5306 # themselves. 5307 raise ValueError("object passed to _assert_is_copy must " + 5308 "override the __repr__ method.") 5309 self.assertIsNot(obj, objcopy, msg=msg) 5310 self.assertIs(type(obj), type(objcopy), msg=msg) 5311 if hasattr(obj, '__dict__'): 5312 self.assertDictEqual(obj.__dict__, objcopy.__dict__, msg=msg) 5313 self.assertIsNot(obj.__dict__, objcopy.__dict__, msg=msg) 5314 if hasattr(obj, '__slots__'): 5315 self.assertListEqual(obj.__slots__, objcopy.__slots__, msg=msg) 5316 for slot in obj.__slots__: 5317 self.assertEqual( 5318 hasattr(obj, slot), hasattr(objcopy, slot), msg=msg) 5319 self.assertEqual(getattr(obj, slot, None), 5320 getattr(objcopy, slot, None), msg=msg) 5321 self.assertEqual(repr(obj), repr(objcopy), msg=msg) 5322 5323 @staticmethod 5324 def _generate_pickle_copiers(): 5325 """Utility method to generate the many possible pickle configurations. 5326 """ 5327 class PickleCopier: 5328 "This class copies object using pickle." 5329 def __init__(self, proto, dumps, loads): 5330 self.proto = proto 5331 self.dumps = dumps 5332 self.loads = loads 5333 def copy(self, obj): 5334 return self.loads(self.dumps(obj, self.proto)) 5335 def __repr__(self): 5336 # We try to be as descriptive as possible here since this is 5337 # the string which we will allow us to tell the pickle 5338 # configuration we are using during debugging. 5339 return ("PickleCopier(proto={}, dumps={}.{}, loads={}.{})" 5340 .format(self.proto, 5341 self.dumps.__module__, self.dumps.__qualname__, 5342 self.loads.__module__, self.loads.__qualname__)) 5343 return (PickleCopier(*args) for args in 5344 itertools.product(range(pickle.HIGHEST_PROTOCOL + 1), 5345 {pickle.dumps, pickle._dumps}, 5346 {pickle.loads, pickle._loads})) 5347 5348 def test_pickle_slots(self): 5349 # Tests pickling of classes with __slots__. 5350 5351 # Pickling of classes with __slots__ but without __getstate__ should 5352 # fail (if using protocol 0 or 1) 5353 global C 5354 class C: 5355 __slots__ = ['a'] 5356 with self.assertRaises(TypeError): 5357 pickle.dumps(C(), 0) 5358 5359 global D 5360 class D(C): 5361 pass 5362 with self.assertRaises(TypeError): 5363 pickle.dumps(D(), 0) 5364 5365 class C: 5366 "A class with __getstate__ and __setstate__ implemented." 5367 __slots__ = ['a'] 5368 def __getstate__(self): 5369 state = getattr(self, '__dict__', {}).copy() 5370 for cls in type(self).__mro__: 5371 for slot in cls.__dict__.get('__slots__', ()): 5372 try: 5373 state[slot] = getattr(self, slot) 5374 except AttributeError: 5375 pass 5376 return state 5377 def __setstate__(self, state): 5378 for k, v in state.items(): 5379 setattr(self, k, v) 5380 def __repr__(self): 5381 return "%s()<%r>" % (type(self).__name__, self.__getstate__()) 5382 5383 class D(C): 5384 "A subclass of a class with slots." 5385 pass 5386 5387 global E 5388 class E(C): 5389 "A subclass with an extra slot." 5390 __slots__ = ['b'] 5391 5392 # Now it should work 5393 for pickle_copier in self._generate_pickle_copiers(): 5394 with self.subTest(pickle_copier=pickle_copier): 5395 x = C() 5396 y = pickle_copier.copy(x) 5397 self._assert_is_copy(x, y) 5398 5399 x.a = 42 5400 y = pickle_copier.copy(x) 5401 self._assert_is_copy(x, y) 5402 5403 x = D() 5404 x.a = 42 5405 x.b = 100 5406 y = pickle_copier.copy(x) 5407 self._assert_is_copy(x, y) 5408 5409 x = E() 5410 x.a = 42 5411 x.b = "foo" 5412 y = pickle_copier.copy(x) 5413 self._assert_is_copy(x, y) 5414 5415 def test_reduce_copying(self): 5416 # Tests pickling and copying new-style classes and objects. 5417 global C1 5418 class C1: 5419 "The state of this class is copyable via its instance dict." 5420 ARGS = (1, 2) 5421 NEED_DICT_COPYING = True 5422 def __init__(self, a, b): 5423 super().__init__() 5424 self.a = a 5425 self.b = b 5426 def __repr__(self): 5427 return "C1(%r, %r)" % (self.a, self.b) 5428 5429 global C2 5430 class C2(list): 5431 "A list subclass copyable via __getnewargs__." 5432 ARGS = (1, 2) 5433 NEED_DICT_COPYING = False 5434 def __new__(cls, a, b): 5435 self = super().__new__(cls) 5436 self.a = a 5437 self.b = b 5438 return self 5439 def __init__(self, *args): 5440 super().__init__() 5441 # This helps testing that __init__ is not called during the 5442 # unpickling process, which would cause extra appends. 5443 self.append("cheese") 5444 @classmethod 5445 def __getnewargs__(cls): 5446 return cls.ARGS 5447 def __repr__(self): 5448 return "C2(%r, %r)<%r>" % (self.a, self.b, list(self)) 5449 5450 global C3 5451 class C3(list): 5452 "A list subclass copyable via __getstate__." 5453 ARGS = (1, 2) 5454 NEED_DICT_COPYING = False 5455 def __init__(self, a, b): 5456 self.a = a 5457 self.b = b 5458 # This helps testing that __init__ is not called during the 5459 # unpickling process, which would cause extra appends. 5460 self.append("cheese") 5461 @classmethod 5462 def __getstate__(cls): 5463 return cls.ARGS 5464 def __setstate__(self, state): 5465 a, b = state 5466 self.a = a 5467 self.b = b 5468 def __repr__(self): 5469 return "C3(%r, %r)<%r>" % (self.a, self.b, list(self)) 5470 5471 global C4 5472 class C4(int): 5473 "An int subclass copyable via __getnewargs__." 5474 ARGS = ("hello", "world", 1) 5475 NEED_DICT_COPYING = False 5476 def __new__(cls, a, b, value): 5477 self = super().__new__(cls, value) 5478 self.a = a 5479 self.b = b 5480 return self 5481 @classmethod 5482 def __getnewargs__(cls): 5483 return cls.ARGS 5484 def __repr__(self): 5485 return "C4(%r, %r)<%r>" % (self.a, self.b, int(self)) 5486 5487 global C5 5488 class C5(int): 5489 "An int subclass copyable via __getnewargs_ex__." 5490 ARGS = (1, 2) 5491 KWARGS = {'value': 3} 5492 NEED_DICT_COPYING = False 5493 def __new__(cls, a, b, *, value=0): 5494 self = super().__new__(cls, value) 5495 self.a = a 5496 self.b = b 5497 return self 5498 @classmethod 5499 def __getnewargs_ex__(cls): 5500 return (cls.ARGS, cls.KWARGS) 5501 def __repr__(self): 5502 return "C5(%r, %r)<%r>" % (self.a, self.b, int(self)) 5503 5504 test_classes = (C1, C2, C3, C4, C5) 5505 # Testing copying through pickle 5506 pickle_copiers = self._generate_pickle_copiers() 5507 for cls, pickle_copier in itertools.product(test_classes, pickle_copiers): 5508 with self.subTest(cls=cls, pickle_copier=pickle_copier): 5509 kwargs = getattr(cls, 'KWARGS', {}) 5510 obj = cls(*cls.ARGS, **kwargs) 5511 proto = pickle_copier.proto 5512 objcopy = pickle_copier.copy(obj) 5513 self._assert_is_copy(obj, objcopy) 5514 # For test classes that supports this, make sure we didn't go 5515 # around the reduce protocol by simply copying the attribute 5516 # dictionary. We clear attributes using the previous copy to 5517 # not mutate the original argument. 5518 if proto >= 2 and not cls.NEED_DICT_COPYING: 5519 objcopy.__dict__.clear() 5520 objcopy2 = pickle_copier.copy(objcopy) 5521 self._assert_is_copy(obj, objcopy2) 5522 5523 # Testing copying through copy.deepcopy() 5524 for cls in test_classes: 5525 with self.subTest(cls=cls): 5526 kwargs = getattr(cls, 'KWARGS', {}) 5527 obj = cls(*cls.ARGS, **kwargs) 5528 objcopy = deepcopy(obj) 5529 self._assert_is_copy(obj, objcopy) 5530 # For test classes that supports this, make sure we didn't go 5531 # around the reduce protocol by simply copying the attribute 5532 # dictionary. We clear attributes using the previous copy to 5533 # not mutate the original argument. 5534 if not cls.NEED_DICT_COPYING: 5535 objcopy.__dict__.clear() 5536 objcopy2 = deepcopy(objcopy) 5537 self._assert_is_copy(obj, objcopy2) 5538 5539 def test_issue24097(self): 5540 # Slot name is freed inside __getattr__ and is later used. 5541 class S(str): # Not interned 5542 pass 5543 class A: 5544 __slotnames__ = [S('spam')] 5545 def __getattr__(self, attr): 5546 if attr == 'spam': 5547 A.__slotnames__[:] = [S('spam')] 5548 return 42 5549 else: 5550 raise AttributeError 5551 5552 import copyreg 5553 expected = (copyreg.__newobj__, (A,), (None, {'spam': 42}), None, None) 5554 self.assertEqual(A().__reduce_ex__(2), expected) # Shouldn't crash 5555 5556 def test_object_reduce(self): 5557 # Issue #29914 5558 # __reduce__() takes no arguments 5559 object().__reduce__() 5560 with self.assertRaises(TypeError): 5561 object().__reduce__(0) 5562 # __reduce_ex__() takes one integer argument 5563 object().__reduce_ex__(0) 5564 with self.assertRaises(TypeError): 5565 object().__reduce_ex__() 5566 with self.assertRaises(TypeError): 5567 object().__reduce_ex__(None) 5568 5569 5570class SharedKeyTests(unittest.TestCase): 5571 5572 @support.cpython_only 5573 def test_subclasses(self): 5574 # Verify that subclasses can share keys (per PEP 412) 5575 class A: 5576 pass 5577 class B(A): 5578 pass 5579 5580 #Shrink keys by repeatedly creating instances 5581 [(A(), B()) for _ in range(30)] 5582 5583 a, b = A(), B() 5584 self.assertEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b))) 5585 self.assertLess(sys.getsizeof(vars(a)), sys.getsizeof({"a":1})) 5586 # Initial hash table can contain only one or two elements. 5587 # Set 6 attributes to cause internal resizing. 5588 a.x, a.y, a.z, a.w, a.v, a.u = range(6) 5589 self.assertNotEqual(sys.getsizeof(vars(a)), sys.getsizeof(vars(b))) 5590 a2 = A() 5591 self.assertGreater(sys.getsizeof(vars(a)), sys.getsizeof(vars(a2))) 5592 self.assertLess(sys.getsizeof(vars(a2)), sys.getsizeof({"a":1})) 5593 self.assertLess(sys.getsizeof(vars(b)), sys.getsizeof({"a":1})) 5594 5595 5596class DebugHelperMeta(type): 5597 """ 5598 Sets default __doc__ and simplifies repr() output. 5599 """ 5600 def __new__(mcls, name, bases, attrs): 5601 if attrs.get('__doc__') is None: 5602 attrs['__doc__'] = name # helps when debugging with gdb 5603 return type.__new__(mcls, name, bases, attrs) 5604 def __repr__(cls): 5605 return repr(cls.__name__) 5606 5607 5608class MroTest(unittest.TestCase): 5609 """ 5610 Regressions for some bugs revealed through 5611 mcsl.mro() customization (typeobject.c: mro_internal()) and 5612 cls.__bases__ assignment (typeobject.c: type_set_bases()). 5613 """ 5614 5615 def setUp(self): 5616 self.step = 0 5617 self.ready = False 5618 5619 def step_until(self, limit): 5620 ret = (self.step < limit) 5621 if ret: 5622 self.step += 1 5623 return ret 5624 5625 def test_incomplete_set_bases_on_self(self): 5626 """ 5627 type_set_bases must be aware that type->tp_mro can be NULL. 5628 """ 5629 class M(DebugHelperMeta): 5630 def mro(cls): 5631 if self.step_until(1): 5632 assert cls.__mro__ is None 5633 cls.__bases__ += () 5634 5635 return type.mro(cls) 5636 5637 class A(metaclass=M): 5638 pass 5639 5640 def test_reent_set_bases_on_base(self): 5641 """ 5642 Deep reentrancy must not over-decref old_mro. 5643 """ 5644 class M(DebugHelperMeta): 5645 def mro(cls): 5646 if cls.__mro__ is not None and cls.__name__ == 'B': 5647 # 4-5 steps are usually enough to make it crash somewhere 5648 if self.step_until(10): 5649 A.__bases__ += () 5650 5651 return type.mro(cls) 5652 5653 class A(metaclass=M): 5654 pass 5655 class B(A): 5656 pass 5657 B.__bases__ += () 5658 5659 def test_reent_set_bases_on_direct_base(self): 5660 """ 5661 Similar to test_reent_set_bases_on_base, but may crash differently. 5662 """ 5663 class M(DebugHelperMeta): 5664 def mro(cls): 5665 base = cls.__bases__[0] 5666 if base is not object: 5667 if self.step_until(5): 5668 base.__bases__ += () 5669 5670 return type.mro(cls) 5671 5672 class A(metaclass=M): 5673 pass 5674 class B(A): 5675 pass 5676 class C(B): 5677 pass 5678 5679 def test_reent_set_bases_tp_base_cycle(self): 5680 """ 5681 type_set_bases must check for an inheritance cycle not only through 5682 MRO of the type, which may be not yet updated in case of reentrance, 5683 but also through tp_base chain, which is assigned before diving into 5684 inner calls to mro(). 5685 5686 Otherwise, the following snippet can loop forever: 5687 do { 5688 // ... 5689 type = type->tp_base; 5690 } while (type != NULL); 5691 5692 Functions that rely on tp_base (like solid_base and PyType_IsSubtype) 5693 would not be happy in that case, causing a stack overflow. 5694 """ 5695 class M(DebugHelperMeta): 5696 def mro(cls): 5697 if self.ready: 5698 if cls.__name__ == 'B1': 5699 B2.__bases__ = (B1,) 5700 if cls.__name__ == 'B2': 5701 B1.__bases__ = (B2,) 5702 return type.mro(cls) 5703 5704 class A(metaclass=M): 5705 pass 5706 class B1(A): 5707 pass 5708 class B2(A): 5709 pass 5710 5711 self.ready = True 5712 with self.assertRaises(TypeError): 5713 B1.__bases__ += () 5714 5715 def test_tp_subclasses_cycle_in_update_slots(self): 5716 """ 5717 type_set_bases must check for reentrancy upon finishing its job 5718 by updating tp_subclasses of old/new bases of the type. 5719 Otherwise, an implicit inheritance cycle through tp_subclasses 5720 can break functions that recurse on elements of that field 5721 (like recurse_down_subclasses and mro_hierarchy) eventually 5722 leading to a stack overflow. 5723 """ 5724 class M(DebugHelperMeta): 5725 def mro(cls): 5726 if self.ready and cls.__name__ == 'C': 5727 self.ready = False 5728 C.__bases__ = (B2,) 5729 return type.mro(cls) 5730 5731 class A(metaclass=M): 5732 pass 5733 class B1(A): 5734 pass 5735 class B2(A): 5736 pass 5737 class C(A): 5738 pass 5739 5740 self.ready = True 5741 C.__bases__ = (B1,) 5742 B1.__bases__ = (C,) 5743 5744 self.assertEqual(C.__bases__, (B2,)) 5745 self.assertEqual(B2.__subclasses__(), [C]) 5746 self.assertEqual(B1.__subclasses__(), []) 5747 5748 self.assertEqual(B1.__bases__, (C,)) 5749 self.assertEqual(C.__subclasses__(), [B1]) 5750 5751 def test_tp_subclasses_cycle_error_return_path(self): 5752 """ 5753 The same as test_tp_subclasses_cycle_in_update_slots, but tests 5754 a code path executed on error (goto bail). 5755 """ 5756 class E(Exception): 5757 pass 5758 class M(DebugHelperMeta): 5759 def mro(cls): 5760 if self.ready and cls.__name__ == 'C': 5761 if C.__bases__ == (B2,): 5762 self.ready = False 5763 else: 5764 C.__bases__ = (B2,) 5765 raise E 5766 return type.mro(cls) 5767 5768 class A(metaclass=M): 5769 pass 5770 class B1(A): 5771 pass 5772 class B2(A): 5773 pass 5774 class C(A): 5775 pass 5776 5777 self.ready = True 5778 with self.assertRaises(E): 5779 C.__bases__ = (B1,) 5780 B1.__bases__ = (C,) 5781 5782 self.assertEqual(C.__bases__, (B2,)) 5783 self.assertEqual(C.__mro__, tuple(type.mro(C))) 5784 5785 def test_incomplete_extend(self): 5786 """ 5787 Extending an uninitialized type with type->tp_mro == NULL must 5788 throw a reasonable TypeError exception, instead of failing 5789 with PyErr_BadInternalCall. 5790 """ 5791 class M(DebugHelperMeta): 5792 def mro(cls): 5793 if cls.__mro__ is None and cls.__name__ != 'X': 5794 with self.assertRaises(TypeError): 5795 class X(cls): 5796 pass 5797 5798 return type.mro(cls) 5799 5800 class A(metaclass=M): 5801 pass 5802 5803 def test_incomplete_super(self): 5804 """ 5805 Attribute lookup on a super object must be aware that 5806 its target type can be uninitialized (type->tp_mro == NULL). 5807 """ 5808 class M(DebugHelperMeta): 5809 def mro(cls): 5810 if cls.__mro__ is None: 5811 with self.assertRaises(AttributeError): 5812 super(cls, cls).xxx 5813 5814 return type.mro(cls) 5815 5816 class A(metaclass=M): 5817 pass 5818 5819 def test_disappearing_custom_mro(self): 5820 """ 5821 gh-92112: A custom mro() returning a result conflicting with 5822 __bases__ and deleting itself caused a double free. 5823 """ 5824 class B: 5825 pass 5826 5827 class M(DebugHelperMeta): 5828 def mro(cls): 5829 del M.mro 5830 return (B,) 5831 5832 with self.assertRaises(TypeError): 5833 class A(metaclass=M): 5834 pass 5835 5836 5837if __name__ == "__main__": 5838 unittest.main() 5839