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