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