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