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