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