0001 # Test enhancements related to descriptors and new-style classes 0002 0003 from test.test_support import verify, vereq, verbose, TestFailed, TESTFN, get_original_stdout 0004 from copy import deepcopy 0005 import warnings 0006 0007 warnings.filterwarnings("ignore", 0008 r'complex divmod\(\), // and % are deprecated$', 0009 DeprecationWarning, r'(<string>|%s)$' % __name__) 0010 0011 def veris(a, b): 0012 if a is not b: 0013 raise TestFailed, "%r is %r" % (a, b) 0014 0015 def testunop(a, res, expr="len(a)", meth="__len__"): 0016 if verbose: print "checking", expr 0017 dict = {'a': a} 0018 vereq(eval(expr, dict), res) 0019 t = type(a) 0020 m = getattr(t, meth) 0021 while meth not in t.__dict__: 0022 t = t.__bases__[0] 0023 vereq(m, t.__dict__[meth]) 0024 vereq(m(a), res) 0025 bm = getattr(a, meth) 0026 vereq(bm(), res) 0027 0028 def testbinop(a, b, res, expr="a+b", meth="__add__"): 0029 if verbose: print "checking", expr 0030 dict = {'a': a, 'b': b} 0031 0032 # XXX Hack so this passes before 2.3 when -Qnew is specified. 0033 if meth == "__div__" and 1/2 == 0.5: 0034 meth = "__truediv__" 0035 0036 vereq(eval(expr, dict), res) 0037 t = type(a) 0038 m = getattr(t, meth) 0039 while meth not in t.__dict__: 0040 t = t.__bases__[0] 0041 vereq(m, t.__dict__[meth]) 0042 vereq(m(a, b), res) 0043 bm = getattr(a, meth) 0044 vereq(bm(b), res) 0045 0046 def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"): 0047 if verbose: print "checking", expr 0048 dict = {'a': a, 'b': b, 'c': c} 0049 vereq(eval(expr, dict), res) 0050 t = type(a) 0051 m = getattr(t, meth) 0052 while meth not in t.__dict__: 0053 t = t.__bases__[0] 0054 vereq(m, t.__dict__[meth]) 0055 vereq(m(a, b, c), res) 0056 bm = getattr(a, meth) 0057 vereq(bm(b, c), res) 0058 0059 def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"): 0060 if verbose: print "checking", stmt 0061 dict = {'a': deepcopy(a), 'b': b} 0062 exec stmt in dict 0063 vereq(dict['a'], res) 0064 t = type(a) 0065 m = getattr(t, meth) 0066 while meth not in t.__dict__: 0067 t = t.__bases__[0] 0068 vereq(m, t.__dict__[meth]) 0069 dict['a'] = deepcopy(a) 0070 m(dict['a'], b) 0071 vereq(dict['a'], res) 0072 dict['a'] = deepcopy(a) 0073 bm = getattr(dict['a'], meth) 0074 bm(b) 0075 vereq(dict['a'], res) 0076 0077 def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"): 0078 if verbose: print "checking", stmt 0079 dict = {'a': deepcopy(a), 'b': b, 'c': c} 0080 exec stmt in dict 0081 vereq(dict['a'], res) 0082 t = type(a) 0083 m = getattr(t, meth) 0084 while meth not in t.__dict__: 0085 t = t.__bases__[0] 0086 vereq(m, t.__dict__[meth]) 0087 dict['a'] = deepcopy(a) 0088 m(dict['a'], b, c) 0089 vereq(dict['a'], res) 0090 dict['a'] = deepcopy(a) 0091 bm = getattr(dict['a'], meth) 0092 bm(b, c) 0093 vereq(dict['a'], res) 0094 0095 def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"): 0096 if verbose: print "checking", stmt 0097 dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d} 0098 exec stmt in dict 0099 vereq(dict['a'], res) 0100 t = type(a) 0101 while meth not in t.__dict__: 0102 t = t.__bases__[0] 0103 m = getattr(t, meth) 0104 vereq(m, t.__dict__[meth]) 0105 dict['a'] = deepcopy(a) 0106 m(dict['a'], b, c, d) 0107 vereq(dict['a'], res) 0108 dict['a'] = deepcopy(a) 0109 bm = getattr(dict['a'], meth) 0110 bm(b, c, d) 0111 vereq(dict['a'], res) 0112 0113 def class_docstrings(): 0114 class Classic: 0115 "A classic docstring." 0116 vereq(Classic.__doc__, "A classic docstring.") 0117 vereq(Classic.__dict__['__doc__'], "A classic docstring.") 0118 0119 class Classic2: 0120 pass 0121 verify(Classic2.__doc__ is None) 0122 0123 class NewStatic(object): 0124 "Another docstring." 0125 vereq(NewStatic.__doc__, "Another docstring.") 0126 vereq(NewStatic.__dict__['__doc__'], "Another docstring.") 0127 0128 class NewStatic2(object): 0129 pass 0130 verify(NewStatic2.__doc__ is None) 0131 0132 class NewDynamic(object): 0133 "Another docstring." 0134 vereq(NewDynamic.__doc__, "Another docstring.") 0135 vereq(NewDynamic.__dict__['__doc__'], "Another docstring.") 0136 0137 class NewDynamic2(object): 0138 pass 0139 verify(NewDynamic2.__doc__ is None) 0140 0141 def lists(): 0142 if verbose: print "Testing list operations..." 0143 testbinop([1], [2], [1,2], "a+b", "__add__") 0144 testbinop([1,2,3], 2, 1, "b in a", "__contains__") 0145 testbinop([1,2,3], 4, 0, "b in a", "__contains__") 0146 testbinop([1,2,3], 1, 2, "a[b]", "__getitem__") 0147 testternop([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__") 0148 testsetop([1], [2], [1,2], "a+=b", "__iadd__") 0149 testsetop([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__") 0150 testunop([1,2,3], 3, "len(a)", "__len__") 0151 testbinop([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__") 0152 testbinop([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__") 0153 testset2op([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__") 0154 testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__") 0155 0156 def dicts(): 0157 if verbose: print "Testing dict operations..." 0158 testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__") 0159 testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__") 0160 testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__") 0161 testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__") 0162 d = {1:2,3:4} 0163 l1 = [] 0164 for i in d.keys(): l1.append(i) 0165 l = [] 0166 for i in iter(d): l.append(i) 0167 vereq(l, l1) 0168 l = [] 0169 for i in d.__iter__(): l.append(i) 0170 vereq(l, l1) 0171 l = [] 0172 for i in dict.__iter__(d): l.append(i) 0173 vereq(l, l1) 0174 d = {1:2, 3:4} 0175 testunop(d, 2, "len(a)", "__len__") 0176 vereq(eval(repr(d), {}), d) 0177 vereq(eval(d.__repr__(), {}), d) 0178 testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__") 0179 0180 def dict_constructor(): 0181 if verbose: 0182 print "Testing dict constructor ..." 0183 d = dict() 0184 vereq(d, {}) 0185 d = dict({}) 0186 vereq(d, {}) 0187 d = dict({1: 2, 'a': 'b'}) 0188 vereq(d, {1: 2, 'a': 'b'}) 0189 vereq(d, dict(d.items())) 0190 vereq(d, dict(d.iteritems())) 0191 d = dict({'one':1, 'two':2}) 0192 vereq(d, dict(one=1, two=2)) 0193 vereq(d, dict(**d)) 0194 vereq(d, dict({"one": 1}, two=2)) 0195 vereq(d, dict([("two", 2)], one=1)) 0196 vereq(d, dict([("one", 100), ("two", 200)], **d)) 0197 verify(d is not dict(**d)) 0198 for badarg in 0, 0L, 0j, "0", [0], (0,): 0199 try: 0200 dict(badarg) 0201 except TypeError: 0202 pass 0203 except ValueError: 0204 if badarg == "0": 0205 # It's a sequence, and its elements are also sequences (gotta 0206 # love strings <wink>), but they aren't of length 2, so this 0207 # one seemed better as a ValueError than a TypeError. 0208 pass 0209 else: 0210 raise TestFailed("no TypeError from dict(%r)" % badarg) 0211 else: 0212 raise TestFailed("no TypeError from dict(%r)" % badarg) 0213 0214 try: 0215 dict({}, {}) 0216 except TypeError: 0217 pass 0218 else: 0219 raise TestFailed("no TypeError from dict({}, {})") 0220 0221 class Mapping: 0222 # Lacks a .keys() method; will be added later. 0223 dict = {1:2, 3:4, 'a':1j} 0224 0225 try: 0226 dict(Mapping()) 0227 except TypeError: 0228 pass 0229 else: 0230 raise TestFailed("no TypeError from dict(incomplete mapping)") 0231 0232 Mapping.keys = lambda self: self.dict.keys() 0233 Mapping.__getitem__ = lambda self, i: self.dict[i] 0234 d = dict(Mapping()) 0235 vereq(d, Mapping.dict) 0236 0237 # Init from sequence of iterable objects, each producing a 2-sequence. 0238 class AddressBookEntry: 0239 def __init__(self, first, last): 0240 self.first = first 0241 self.last = last 0242 def __iter__(self): 0243 return iter([self.first, self.last]) 0244 0245 d = dict([AddressBookEntry('Tim', 'Warsaw'), 0246 AddressBookEntry('Barry', 'Peters'), 0247 AddressBookEntry('Tim', 'Peters'), 0248 AddressBookEntry('Barry', 'Warsaw')]) 0249 vereq(d, {'Barry': 'Warsaw', 'Tim': 'Peters'}) 0250 0251 d = dict(zip(range(4), range(1, 5))) 0252 vereq(d, dict([(i, i+1) for i in range(4)])) 0253 0254 # Bad sequence lengths. 0255 for bad in [('tooshort',)], [('too', 'long', 'by 1')]: 0256 try: 0257 dict(bad) 0258 except ValueError: 0259 pass 0260 else: 0261 raise TestFailed("no ValueError from dict(%r)" % bad) 0262 0263 def test_dir(): 0264 if verbose: 0265 print "Testing dir() ..." 0266 junk = 12 0267 vereq(dir(), ['junk']) 0268 del junk 0269 0270 # Just make sure these don't blow up! 0271 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir: 0272 dir(arg) 0273 0274 # Try classic classes. 0275 class C: 0276 Cdata = 1 0277 def Cmethod(self): pass 0278 0279 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__'] 0280 vereq(dir(C), cstuff) 0281 verify('im_self' in dir(C.Cmethod)) 0282 0283 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__. 0284 vereq(dir(c), cstuff) 0285 0286 c.cdata = 2 0287 c.cmethod = lambda self: 0 0288 vereq(dir(c), cstuff + ['cdata', 'cmethod']) 0289 verify('im_self' in dir(c.Cmethod)) 0290 0291 class A(C): 0292 Adata = 1 0293 def Amethod(self): pass 0294 0295 astuff = ['Adata', 'Amethod'] + cstuff 0296 vereq(dir(A), astuff) 0297 verify('im_self' in dir(A.Amethod)) 0298 a = A() 0299 vereq(dir(a), astuff) 0300 verify('im_self' in dir(a.Amethod)) 0301 a.adata = 42 0302 a.amethod = lambda self: 3 0303 vereq(dir(a), astuff + ['adata', 'amethod']) 0304 0305 # The same, but with new-style classes. Since these have object as a 0306 # base class, a lot more gets sucked in. 0307 def interesting(strings): 0308 return [s for s in strings if not s.startswith('_')] 0309 0310 class C(object): 0311 Cdata = 1 0312 def Cmethod(self): pass 0313 0314 cstuff = ['Cdata', 'Cmethod'] 0315 vereq(interesting(dir(C)), cstuff) 0316 0317 c = C() 0318 vereq(interesting(dir(c)), cstuff) 0319 verify('im_self' in dir(C.Cmethod)) 0320 0321 c.cdata = 2 0322 c.cmethod = lambda self: 0 0323 vereq(interesting(dir(c)), cstuff + ['cdata', 'cmethod']) 0324 verify('im_self' in dir(c.Cmethod)) 0325 0326 class A(C): 0327 Adata = 1 0328 def Amethod(self): pass 0329 0330 astuff = ['Adata', 'Amethod'] + cstuff 0331 vereq(interesting(dir(A)), astuff) 0332 verify('im_self' in dir(A.Amethod)) 0333 a = A() 0334 vereq(interesting(dir(a)), astuff) 0335 a.adata = 42 0336 a.amethod = lambda self: 3 0337 vereq(interesting(dir(a)), astuff + ['adata', 'amethod']) 0338 verify('im_self' in dir(a.Amethod)) 0339 0340 # Try a module subclass. 0341 import sys 0342 class M(type(sys)): 0343 pass 0344 minstance = M("m") 0345 minstance.b = 2 0346 minstance.a = 1 0347 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]] 0348 vereq(names, ['a', 'b']) 0349 0350 class M2(M): 0351 def getdict(self): 0352 return "Not a dict!" 0353 __dict__ = property(getdict) 0354 0355 m2instance = M2("m2") 0356 m2instance.b = 2 0357 m2instance.a = 1 0358 vereq(m2instance.__dict__, "Not a dict!") 0359 try: 0360 dir(m2instance) 0361 except TypeError: 0362 pass 0363 0364 # Two essentially featureless objects, just inheriting stuff from 0365 # object. 0366 vereq(dir(None), dir(Ellipsis)) 0367 0368 # Nasty test case for proxied objects 0369 class Wrapper(object): 0370 def __init__(self, obj): 0371 self.__obj = obj 0372 def __repr__(self): 0373 return "Wrapper(%s)" % repr(self.__obj) 0374 def __getitem__(self, key): 0375 return Wrapper(self.__obj[key]) 0376 def __len__(self): 0377 return len(self.__obj) 0378 def __getattr__(self, name): 0379 return Wrapper(getattr(self.__obj, name)) 0380 0381 class C(object): 0382 def __getclass(self): 0383 return Wrapper(type(self)) 0384 __class__ = property(__getclass) 0385 0386 dir(C()) # This used to segfault 0387 0388 binops = { 0389 'add': '+', 0390 'sub': '-', 0391 'mul': '*', 0392 'div': '/', 0393 'mod': '%', 0394 'divmod': 'divmod', 0395 'pow': '**', 0396 'lshift': '<<', 0397 'rshift': '>>', 0398 'and': '&', 0399 'xor': '^', 0400 'or': '|', 0401 'cmp': 'cmp', 0402 'lt': '<', 0403 'le': '<=', 0404 'eq': '==', 0405 'ne': '!=', 0406 'gt': '>', 0407 'ge': '>=', 0408 } 0409 0410 for name, expr in binops.items(): 0411 if expr.islower(): 0412 expr = expr + "(a, b)" 0413 else: 0414 expr = 'a %s b' % expr 0415 binops[name] = expr 0416 0417 unops = { 0418 'pos': '+', 0419 'neg': '-', 0420 'abs': 'abs', 0421 'invert': '~', 0422 'int': 'int', 0423 'long': 'long', 0424 'float': 'float', 0425 'oct': 'oct', 0426 'hex': 'hex', 0427 } 0428 0429 for name, expr in unops.items(): 0430 if expr.islower(): 0431 expr = expr + "(a)" 0432 else: 0433 expr = '%s a' % expr 0434 unops[name] = expr 0435 0436 def numops(a, b, skip=[]): 0437 dict = {'a': a, 'b': b} 0438 for name, expr in binops.items(): 0439 if name not in skip: 0440 name = "__%s__" % name 0441 if hasattr(a, name): 0442 res = eval(expr, dict) 0443 testbinop(a, b, res, expr, name) 0444 for name, expr in unops.items(): 0445 if name not in skip: 0446 name = "__%s__" % name 0447 if hasattr(a, name): 0448 res = eval(expr, dict) 0449 testunop(a, res, expr, name) 0450 0451 def ints(): 0452 if verbose: print "Testing int operations..." 0453 numops(100, 3) 0454 # The following crashes in Python 2.2 0455 vereq((1).__nonzero__(), 1) 0456 vereq((0).__nonzero__(), 0) 0457 # This returns 'NotImplemented' in Python 2.2 0458 class C(int): 0459 def __add__(self, other): 0460 return NotImplemented 0461 vereq(C(5L), 5) 0462 try: 0463 C() + "" 0464 except TypeError: 0465 pass 0466 else: 0467 raise TestFailed, "NotImplemented should have caused TypeError" 0468 import sys 0469 try: 0470 C(sys.maxint+1) 0471 except OverflowError: 0472 pass 0473 else: 0474 raise TestFailed, "should have raised OverflowError" 0475 0476 def longs(): 0477 if verbose: print "Testing long operations..." 0478 numops(100L, 3L) 0479 0480 def floats(): 0481 if verbose: print "Testing float operations..." 0482 numops(100.0, 3.0) 0483 0484 def complexes(): 0485 if verbose: print "Testing complex operations..." 0486 numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float']) 0487 class Number(complex): 0488 __slots__ = ['prec'] 0489 def __new__(cls, *args, **kwds): 0490 result = complex.__new__(cls, *args) 0491 result.prec = kwds.get('prec', 12) 0492 return result 0493 def __repr__(self): 0494 prec = self.prec 0495 if self.imag == 0.0: 0496 return "%.*g" % (prec, self.real) 0497 if self.real == 0.0: 0498 return "%.*gj" % (prec, self.imag) 0499 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag) 0500 __str__ = __repr__ 0501 0502 a = Number(3.14, prec=6) 0503 vereq(repr(a), "3.14") 0504 vereq(a.prec, 6) 0505 0506 a = Number(a, prec=2) 0507 vereq(repr(a), "3.1") 0508 vereq(a.prec, 2) 0509 0510 a = Number(234.5) 0511 vereq(repr(a), "234.5") 0512 vereq(a.prec, 12) 0513 0514 def spamlists(): 0515 if verbose: print "Testing spamlist operations..." 0516 import copy, xxsubtype as spam 0517 def spamlist(l, memo=None): 0518 import xxsubtype as spam 0519 return spam.spamlist(l) 0520 # This is an ugly hack: 0521 copy._deepcopy_dispatch[spam.spamlist] = spamlist 0522 0523 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__") 0524 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__") 0525 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__") 0526 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__") 0527 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]), 0528 "a[b:c]", "__getslice__") 0529 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]), 0530 "a+=b", "__iadd__") 0531 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__") 0532 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__") 0533 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__") 0534 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__") 0535 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__") 0536 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]), 0537 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__") 0538 # Test subclassing 0539 class C(spam.spamlist): 0540 def foo(self): return 1 0541 a = C() 0542 vereq(a, []) 0543 vereq(a.foo(), 1) 0544 a.append(100) 0545 vereq(a, [100]) 0546 vereq(a.getstate(), 0) 0547 a.setstate(42) 0548 vereq(a.getstate(), 42) 0549 0550 def spamdicts(): 0551 if verbose: print "Testing spamdict operations..." 0552 import copy, xxsubtype as spam 0553 def spamdict(d, memo=None): 0554 import xxsubtype as spam 0555 sd = spam.spamdict() 0556 for k, v in d.items(): sd[k] = v 0557 return sd 0558 # This is an ugly hack: 0559 copy._deepcopy_dispatch[spam.spamdict] = spamdict 0560 0561 testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__") 0562 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__") 0563 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__") 0564 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__") 0565 d = spamdict({1:2,3:4}) 0566 l1 = [] 0567 for i in d.keys(): l1.append(i) 0568 l = [] 0569 for i in iter(d): l.append(i) 0570 vereq(l, l1) 0571 l = [] 0572 for i in d.__iter__(): l.append(i) 0573 vereq(l, l1) 0574 l = [] 0575 for i in type(spamdict({})).__iter__(d): l.append(i) 0576 vereq(l, l1) 0577 straightd = {1:2, 3:4} 0578 spamd = spamdict(straightd) 0579 testunop(spamd, 2, "len(a)", "__len__") 0580 testunop(spamd, repr(straightd), "repr(a)", "__repr__") 0581 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}), 0582 "a[b]=c", "__setitem__") 0583 # Test subclassing 0584 class C(spam.spamdict): 0585 def foo(self): return 1 0586 a = C() 0587 vereq(a.items(), []) 0588 vereq(a.foo(), 1) 0589 a['foo'] = 'bar' 0590 vereq(a.items(), [('foo', 'bar')]) 0591 vereq(a.getstate(), 0) 0592 a.setstate(100) 0593 vereq(a.getstate(), 100) 0594 0595 def pydicts(): 0596 if verbose: print "Testing Python subclass of dict..." 0597 verify(issubclass(dict, dict)) 0598 verify(isinstance({}, dict)) 0599 d = dict() 0600 vereq(d, {}) 0601 verify(d.__class__ is dict) 0602 verify(isinstance(d, dict)) 0603 class C(dict): 0604 state = -1 0605 def __init__(self, *a, **kw): 0606 if a: 0607 vereq(len(a), 1) 0608 self.state = a[0] 0609 if kw: 0610 for k, v in kw.items(): self[v] = k 0611 def __getitem__(self, key): 0612 return self.get(key, 0) 0613 def __setitem__(self, key, value): 0614 verify(isinstance(key, type(0))) 0615 dict.__setitem__(self, key, value) 0616 def setstate(self, state): 0617 self.state = state 0618 def getstate(self): 0619 return self.state 0620 verify(issubclass(C, dict)) 0621 a1 = C(12) 0622 vereq(a1.state, 12) 0623 a2 = C(foo=1, bar=2) 0624 vereq(a2[1] == 'foo' and a2[2], 'bar') 0625 a = C() 0626 vereq(a.state, -1) 0627 vereq(a.getstate(), -1) 0628 a.setstate(0) 0629 vereq(a.state, 0) 0630 vereq(a.getstate(), 0) 0631 a.setstate(10) 0632 vereq(a.state, 10) 0633 vereq(a.getstate(), 10) 0634 vereq(a[42], 0) 0635 a[42] = 24 0636 vereq(a[42], 24) 0637 if verbose: print "pydict stress test ..." 0638 N = 50 0639 for i in range(N): 0640 a[i] = C() 0641 for j in range(N): 0642 a[i][j] = i*j 0643 for i in range(N): 0644 for j in range(N): 0645 vereq(a[i][j], i*j) 0646 0647 def pylists(): 0648 if verbose: print "Testing Python subclass of list..." 0649 class C(list): 0650 def __getitem__(self, i): 0651 return list.__getitem__(self, i) + 100 0652 def __getslice__(self, i, j): 0653 return (i, j) 0654 a = C() 0655 a.extend([0,1,2]) 0656 vereq(a[0], 100) 0657 vereq(a[1], 101) 0658 vereq(a[2], 102) 0659 vereq(a[100:200], (100,200)) 0660 0661 def metaclass(): 0662 if verbose: print "Testing __metaclass__..." 0663 class C: 0664 __metaclass__ = type 0665 def __init__(self): 0666 self.__state = 0 0667 def getstate(self): 0668 return self.__state 0669 def setstate(self, state): 0670 self.__state = state 0671 a = C() 0672 vereq(a.getstate(), 0) 0673 a.setstate(10) 0674 vereq(a.getstate(), 10) 0675 class D: 0676 class __metaclass__(type): 0677 def myself(cls): return cls 0678 vereq(D.myself(), D) 0679 d = D() 0680 verify(d.__class__ is D) 0681 class M1(type): 0682 def __new__(cls, name, bases, dict): 0683 dict['__spam__'] = 1 0684 return type.__new__(cls, name, bases, dict) 0685 class C: 0686 __metaclass__ = M1 0687 vereq(C.__spam__, 1) 0688 c = C() 0689 vereq(c.__spam__, 1) 0690 0691 class _instance(object): 0692 pass 0693 class M2(object): 0694 def __new__(cls, name, bases, dict): 0695 self = object.__new__(cls) 0696 self.name = name 0697 self.bases = bases 0698 self.dict = dict 0699 return self 0700 __new__ = staticmethod(__new__) 0701 def __call__(self): 0702 it = _instance() 0703 # Early binding of methods 0704 for key in self.dict: 0705 if key.startswith("__"): 0706 continue 0707 setattr(it, key, self.dict[key].__get__(it, self)) 0708 return it 0709 class C: 0710 __metaclass__ = M2 0711 def spam(self): 0712 return 42 0713 vereq(C.name, 'C') 0714 vereq(C.bases, ()) 0715 verify('spam' in C.dict) 0716 c = C() 0717 vereq(c.spam(), 42) 0718 0719 # More metaclass examples 0720 0721 class autosuper(type): 0722 # Automatically add __super to the class 0723 # This trick only works for dynamic classes 0724 def __new__(metaclass, name, bases, dict): 0725 cls = super(autosuper, metaclass).__new__(metaclass, 0726 name, bases, dict) 0727 # Name mangling for __super removes leading underscores 0728 while name[:1] == "_": 0729 name = name[1:] 0730 if name: 0731 name = "_%s__super" % name 0732 else: 0733 name = "__super" 0734 setattr(cls, name, super(cls)) 0735 return cls 0736 class A: 0737 __metaclass__ = autosuper 0738 def meth(self): 0739 return "A" 0740 class B(A): 0741 def meth(self): 0742 return "B" + self.__super.meth() 0743 class C(A): 0744 def meth(self): 0745 return "C" + self.__super.meth() 0746 class D(C, B): 0747 def meth(self): 0748 return "D" + self.__super.meth() 0749 vereq(D().meth(), "DCBA") 0750 class E(B, C): 0751 def meth(self): 0752 return "E" + self.__super.meth() 0753 vereq(E().meth(), "EBCA") 0754 0755 class autoproperty(type): 0756 # Automatically create property attributes when methods 0757 # named _get_x and/or _set_x are found 0758 def __new__(metaclass, name, bases, dict): 0759 hits = {} 0760 for key, val in dict.iteritems(): 0761 if key.startswith("_get_"): 0762 key = key[5:] 0763 get, set = hits.get(key, (None, None)) 0764 get = val 0765 hits[key] = get, set 0766 elif key.startswith("_set_"): 0767 key = key[5:] 0768 get, set = hits.get(key, (None, None)) 0769 set = val 0770 hits[key] = get, set 0771 for key, (get, set) in hits.iteritems(): 0772 dict[key] = property(get, set) 0773 return super(autoproperty, metaclass).__new__(metaclass, 0774 name, bases, dict) 0775 class A: 0776 __metaclass__ = autoproperty 0777 def _get_x(self): 0778 return -self.__x 0779 def _set_x(self, x): 0780 self.__x = -x 0781 a = A() 0782 verify(not hasattr(a, "x")) 0783 a.x = 12 0784 vereq(a.x, 12) 0785 vereq(a._A__x, -12) 0786 0787 class multimetaclass(autoproperty, autosuper): 0788 # Merge of multiple cooperating metaclasses 0789 pass 0790 class A: 0791 __metaclass__ = multimetaclass 0792 def _get_x(self): 0793 return "A" 0794 class B(A): 0795 def _get_x(self): 0796 return "B" + self.__super._get_x() 0797 class C(A): 0798 def _get_x(self): 0799 return "C" + self.__super._get_x() 0800 class D(C, B): 0801 def _get_x(self): 0802 return "D" + self.__super._get_x() 0803 vereq(D().x, "DCBA") 0804 0805 # Make sure type(x) doesn't call x.__class__.__init__ 0806 class T(type): 0807 counter = 0 0808 def __init__(self, *args): 0809 T.counter += 1 0810 class C: 0811 __metaclass__ = T 0812 vereq(T.counter, 1) 0813 a = C() 0814 vereq(type(a), C) 0815 vereq(T.counter, 1) 0816 0817 class C(object): pass 0818 c = C() 0819 try: c() 0820 except TypeError: pass 0821 else: raise TestFailed, "calling object w/o call method should raise TypeError" 0822 0823 def pymods(): 0824 if verbose: print "Testing Python subclass of module..." 0825 log = [] 0826 import sys 0827 MT = type(sys) 0828 class MM(MT): 0829 def __init__(self, name): 0830 MT.__init__(self, name) 0831 def __getattribute__(self, name): 0832 log.append(("getattr", name)) 0833 return MT.__getattribute__(self, name) 0834 def __setattr__(self, name, value): 0835 log.append(("setattr", name, value)) 0836 MT.__setattr__(self, name, value) 0837 def __delattr__(self, name): 0838 log.append(("delattr", name)) 0839 MT.__delattr__(self, name) 0840 a = MM("a") 0841 a.foo = 12 0842 x = a.foo 0843 del a.foo 0844 vereq(log, [("setattr", "foo", 12), 0845 ("getattr", "foo"), 0846 ("delattr", "foo")]) 0847 0848 def multi(): 0849 if verbose: print "Testing multiple inheritance..." 0850 class C(object): 0851 def __init__(self): 0852 self.__state = 0 0853 def getstate(self): 0854 return self.__state 0855 def setstate(self, state): 0856 self.__state = state 0857 a = C() 0858 vereq(a.getstate(), 0) 0859 a.setstate(10) 0860 vereq(a.getstate(), 10) 0861 class D(dict, C): 0862 def __init__(self): 0863 type({}).__init__(self) 0864 C.__init__(self) 0865 d = D() 0866 vereq(d.keys(), []) 0867 d["hello"] = "world" 0868 vereq(d.items(), [("hello", "world")]) 0869 vereq(d["hello"], "world") 0870 vereq(d.getstate(), 0) 0871 d.setstate(10) 0872 vereq(d.getstate(), 10) 0873 vereq(D.__mro__, (D, dict, C, object)) 0874 0875 # SF bug #442833 0876 class Node(object): 0877 def __int__(self): 0878 return int(self.foo()) 0879 def foo(self): 0880 return "23" 0881 class Frag(Node, list): 0882 def foo(self): 0883 return "42" 0884 vereq(Node().__int__(), 23) 0885 vereq(int(Node()), 23) 0886 vereq(Frag().__int__(), 42) 0887 vereq(int(Frag()), 42) 0888 0889 # MI mixing classic and new-style classes. 0890 0891 class A: 0892 x = 1 0893 0894 class B(A): 0895 pass 0896 0897 class C(A): 0898 x = 2 0899 0900 class D(B, C): 0901 pass 0902 vereq(D.x, 1) 0903 0904 # Classic MRO is preserved for a classic base class. 0905 class E(D, object): 0906 pass 0907 vereq(E.__mro__, (E, D, B, A, C, object)) 0908 vereq(E.x, 1) 0909 0910 # But with a mix of classic bases, their MROs are combined using 0911 # new-style MRO. 0912 class F(B, C, object): 0913 pass 0914 vereq(F.__mro__, (F, B, C, A, object)) 0915 vereq(F.x, 2) 0916 0917 # Try something else. 0918 class C: 0919 def cmethod(self): 0920 return "C a" 0921 def all_method(self): 0922 return "C b" 0923 0924 class M1(C, object): 0925 def m1method(self): 0926 return "M1 a" 0927 def all_method(self): 0928 return "M1 b" 0929 0930 vereq(M1.__mro__, (M1, C, object)) 0931 m = M1() 0932 vereq(m.cmethod(), "C a") 0933 vereq(m.m1method(), "M1 a") 0934 vereq(m.all_method(), "M1 b") 0935 0936 class D(C): 0937 def dmethod(self): 0938 return "D a" 0939 def all_method(self): 0940 return "D b" 0941 0942 class M2(D, object): 0943 def m2method(self): 0944 return "M2 a" 0945 def all_method(self): 0946 return "M2 b" 0947 0948 vereq(M2.__mro__, (M2, D, C, object)) 0949 m = M2() 0950 vereq(m.cmethod(), "C a") 0951 vereq(m.dmethod(), "D a") 0952 vereq(m.m2method(), "M2 a") 0953 vereq(m.all_method(), "M2 b") 0954 0955 class M3(M1, M2, object): 0956 def m3method(self): 0957 return "M3 a" 0958 def all_method(self): 0959 return "M3 b" 0960 vereq(M3.__mro__, (M3, M1, M2, D, C, object)) 0961 m = M3() 0962 vereq(m.cmethod(), "C a") 0963 vereq(m.dmethod(), "D a") 0964 vereq(m.m1method(), "M1 a") 0965 vereq(m.m2method(), "M2 a") 0966 vereq(m.m3method(), "M3 a") 0967 vereq(m.all_method(), "M3 b") 0968 0969 class Classic: 0970 pass 0971 try: 0972 class New(Classic): 0973 __metaclass__ = type 0974 except TypeError: 0975 pass 0976 else: 0977 raise TestFailed, "new class with only classic bases - shouldn't be" 0978 0979 def diamond(): 0980 if verbose: print "Testing multiple inheritance special cases..." 0981 class A(object): 0982 def spam(self): return "A" 0983 vereq(A().spam(), "A") 0984 class B(A): 0985 def boo(self): return "B" 0986 def spam(self): return "B" 0987 vereq(B().spam(), "B") 0988 vereq(B().boo(), "B") 0989 class C(A): 0990 def boo(self): return "C" 0991 vereq(C().spam(), "A") 0992 vereq(C().boo(), "C") 0993 class D(B, C): pass 0994 vereq(D().spam(), "B") 0995 vereq(D().boo(), "B") 0996 vereq(D.__mro__, (D, B, C, A, object)) 0997 class E(C, B): pass 0998 vereq(E().spam(), "B") 0999 vereq(E().boo(), "C") 1000 vereq(E.__mro__, (E, C, B, A, object)) 1001 # MRO order disagreement 1002 try: 1003 class F(D, E): pass 1004 except TypeError: 1005 pass 1006 else: 1007 raise TestFailed, "expected MRO order disagreement (F)" 1008 try: 1009 class G(E, D): pass 1010 except TypeError: 1011 pass 1012 else: 1013 raise TestFailed, "expected MRO order disagreement (G)" 1014 1015 1016 # see thread python-dev/2002-October/029035.html 1017 def ex5(): 1018 if verbose: print "Testing ex5 from C3 switch discussion..." 1019 class A(object): pass 1020 class B(object): pass 1021 class C(object): pass 1022 class X(A): pass 1023 class Y(A): pass 1024 class Z(X,B,Y,C): pass 1025 vereq(Z.__mro__, (Z, X, B, Y, A, C, object)) 1026 1027 # see "A Monotonic Superclass Linearization for Dylan", 1028 # by Kim Barrett et al. (OOPSLA 1996) 1029 def monotonicity(): 1030 if verbose: print "Testing MRO monotonicity..." 1031 class Boat(object): pass 1032 class DayBoat(Boat): pass 1033 class WheelBoat(Boat): pass 1034 class EngineLess(DayBoat): pass 1035 class SmallMultihull(DayBoat): pass 1036 class PedalWheelBoat(EngineLess,WheelBoat): pass 1037 class SmallCatamaran(SmallMultihull): pass 1038 class Pedalo(PedalWheelBoat,SmallCatamaran): pass 1039 1040 vereq(PedalWheelBoat.__mro__, 1041 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, 1042 object)) 1043 vereq(SmallCatamaran.__mro__, 1044 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object)) 1045 1046 vereq(Pedalo.__mro__, 1047 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran, 1048 SmallMultihull, DayBoat, WheelBoat, Boat, object)) 1049 1050 # see "A Monotonic Superclass Linearization for Dylan", 1051 # by Kim Barrett et al. (OOPSLA 1996) 1052 def consistency_with_epg(): 1053 if verbose: print "Testing consistentcy with EPG..." 1054 class Pane(object): pass 1055 class ScrollingMixin(object): pass 1056 class EditingMixin(object): pass 1057 class ScrollablePane(Pane,ScrollingMixin): pass 1058 class EditablePane(Pane,EditingMixin): pass 1059 class EditableScrollablePane(ScrollablePane,EditablePane): pass 1060 1061 vereq(EditableScrollablePane.__mro__, 1062 (EditableScrollablePane, ScrollablePane, EditablePane, 1063 Pane, ScrollingMixin, EditingMixin, object)) 1064 1065 mro_err_msg = """Cannot create a consistent method resolution 1066 order (MRO) for bases """ 1067 1068 def mro_disagreement(): 1069 if verbose: print "Testing error messages for MRO disagreement..." 1070 def raises(exc, expected, callable, *args): 1071 try: 1072 callable(*args) 1073 except exc, msg: 1074 if not str(msg).startswith(expected): 1075 raise TestFailed, "Message %r, expected %r" % (str(msg), 1076 expected) 1077 else: 1078 raise TestFailed, "Expected %s" % exc 1079 class A(object): pass 1080 class B(A): pass 1081 class C(object): pass 1082 # Test some very simple errors 1083 raises(TypeError, "duplicate base class A", 1084 type, "X", (A, A), {}) 1085 raises(TypeError, mro_err_msg, 1086 type, "X", (A, B), {}) 1087 raises(TypeError, mro_err_msg, 1088 type, "X", (A, C, B), {}) 1089 # Test a slightly more complex error 1090 class GridLayout(object): pass 1091 class HorizontalGrid(GridLayout): pass 1092 class VerticalGrid(GridLayout): pass 1093 class HVGrid(HorizontalGrid, VerticalGrid): pass 1094 class VHGrid(VerticalGrid, HorizontalGrid): pass 1095 raises(TypeError, mro_err_msg, 1096 type, "ConfusedGrid", (HVGrid, VHGrid), {}) 1097 1098 def objects(): 1099 if verbose: print "Testing object class..." 1100 a = object() 1101 vereq(a.__class__, object) 1102 vereq(type(a), object) 1103 b = object() 1104 verify(a is not b) 1105 verify(not hasattr(a, "foo")) 1106 try: 1107 a.foo = 12 1108 except (AttributeError, TypeError): 1109 pass 1110 else: 1111 verify(0, "object() should not allow setting a foo attribute") 1112 verify(not hasattr(object(), "__dict__")) 1113 1114 class Cdict(object): 1115 pass 1116 x = Cdict() 1117 vereq(x.__dict__, {}) 1118 x.foo = 1 1119 vereq(x.foo, 1) 1120 vereq(x.__dict__, {'foo': 1}) 1121 1122 def slots(): 1123 if verbose: print "Testing __slots__..." 1124 class C0(object): 1125 __slots__ = [] 1126 x = C0() 1127 verify(not hasattr(x, "__dict__")) 1128 verify(not hasattr(x, "foo")) 1129 1130 class C1(object): 1131 __slots__ = ['a'] 1132 x = C1() 1133 verify(not hasattr(x, "__dict__")) 1134 verify(not hasattr(x, "a")) 1135 x.a = 1 1136 vereq(x.a, 1) 1137 x.a = None 1138 veris(x.a, None) 1139 del x.a 1140 verify(not hasattr(x, "a")) 1141 1142 class C3(object): 1143 __slots__ = ['a', 'b', 'c'] 1144 x = C3() 1145 verify(not hasattr(x, "__dict__")) 1146 verify(not hasattr(x, 'a')) 1147 verify(not hasattr(x, 'b')) 1148 verify(not hasattr(x, 'c')) 1149 x.a = 1 1150 x.b = 2 1151 x.c = 3 1152 vereq(x.a, 1) 1153 vereq(x.b, 2) 1154 vereq(x.c, 3) 1155 1156 class C4(object): 1157 """Validate name mangling""" 1158 __slots__ = ['__a'] 1159 def __init__(self, value): 1160 self.__a = value 1161 def get(self): 1162 return self.__a 1163 x = C4(5) 1164 verify(not hasattr(x, '__dict__')) 1165 verify(not hasattr(x, '__a')) 1166 vereq(x.get(), 5) 1167 try: 1168 x.__a = 6 1169 except AttributeError: 1170 pass 1171 else: 1172 raise TestFailed, "Double underscored names not mangled" 1173 1174 # Make sure slot names are proper identifiers 1175 try: 1176 class C(object): 1177 __slots__ = [None] 1178 except TypeError: 1179 pass 1180 else: 1181 raise TestFailed, "[None] slots not caught" 1182 try: 1183 class C(object): 1184 __slots__ = ["foo bar"] 1185 except TypeError: 1186 pass 1187 else: 1188 raise TestFailed, "['foo bar'] slots not caught" 1189 try: 1190 class C(object): 1191 __slots__ = ["foo\0bar"] 1192 except TypeError: 1193 pass 1194 else: 1195 raise TestFailed, "['foo\\0bar'] slots not caught" 1196 try: 1197 class C(object): 1198 __slots__ = ["1"] 1199 except TypeError: 1200 pass 1201 else: 1202 raise TestFailed, "['1'] slots not caught" 1203 try: 1204 class C(object): 1205 __slots__ = [""] 1206 except TypeError: 1207 pass 1208 else: 1209 raise TestFailed, "[''] slots not caught" 1210 class C(object): 1211 __slots__ = ["a", "a_b", "_a", "A0123456789Z"] 1212 1213 # Test leaks 1214 class Counted(object): 1215 counter = 0 # counts the number of instances alive 1216 def __init__(self): 1217 Counted.counter += 1 1218 def __del__(self): 1219 Counted.counter -= 1 1220 class C(object): 1221 __slots__ = ['a', 'b', 'c'] 1222 x = C() 1223 x.a = Counted() 1224 x.b = Counted() 1225 x.c = Counted() 1226 vereq(Counted.counter, 3) 1227 del x 1228 vereq(Counted.counter, 0) 1229 class D(C): 1230 pass 1231 x = D() 1232 x.a = Counted() 1233 x.z = Counted() 1234 vereq(Counted.counter, 2) 1235 del x 1236 vereq(Counted.counter, 0) 1237 class E(D): 1238 __slots__ = ['e'] 1239 x = E() 1240 x.a = Counted() 1241 x.z = Counted() 1242 x.e = Counted() 1243 vereq(Counted.counter, 3) 1244 del x 1245 vereq(Counted.counter, 0) 1246 1247 # Test cyclical leaks [SF bug 519621] 1248 class F(object): 1249 __slots__ = ['a', 'b'] 1250 log = [] 1251 s = F() 1252 s.a = [Counted(), s] 1253 vereq(Counted.counter, 1) 1254 s = None 1255 import gc 1256 gc.collect() 1257 vereq(Counted.counter, 0) 1258 1259 # Test lookup leaks [SF bug 572567] 1260 import sys,gc 1261 class G(object): 1262 def __cmp__(self, other): 1263 return 0 1264 g = G() 1265 orig_objects = len(gc.get_objects()) 1266 for i in xrange(10): 1267 g==g 1268 new_objects = len(gc.get_objects()) 1269 vereq(orig_objects, new_objects) 1270 class H(object): 1271 __slots__ = ['a', 'b'] 1272 def __init__(self): 1273 self.a = 1 1274 self.b = 2 1275 def __del__(self): 1276 assert self.a == 1 1277 assert self.b == 2 1278 1279 save_stderr = sys.stderr 1280 sys.stderr = sys.stdout 1281 h = H() 1282 try: 1283 del h 1284 finally: 1285 sys.stderr = save_stderr 1286 1287 def slotspecials(): 1288 if verbose: print "Testing __dict__ and __weakref__ in __slots__..." 1289 1290 class D(object): 1291 __slots__ = ["__dict__"] 1292 a = D() 1293 verify(hasattr(a, "__dict__")) 1294 verify(not hasattr(a, "__weakref__")) 1295 a.foo = 42 1296 vereq(a.__dict__, {"foo": 42}) 1297 1298 class W(object): 1299 __slots__ = ["__weakref__"] 1300 a = W() 1301 verify(hasattr(a, "__weakref__")) 1302 verify(not hasattr(a, "__dict__")) 1303 try: 1304 a.foo = 42 1305 except AttributeError: 1306 pass 1307 else: 1308 raise TestFailed, "shouldn't be allowed to set a.foo" 1309 1310 class C1(W, D): 1311 __slots__ = [] 1312 a = C1() 1313 verify(hasattr(a, "__dict__")) 1314 verify(hasattr(a, "__weakref__")) 1315 a.foo = 42 1316 vereq(a.__dict__, {"foo": 42}) 1317 1318 class C2(D, W): 1319 __slots__ = [] 1320 a = C2() 1321 verify(hasattr(a, "__dict__")) 1322 verify(hasattr(a, "__weakref__")) 1323 a.foo = 42 1324 vereq(a.__dict__, {"foo": 42}) 1325 1326 # MRO order disagreement 1327 # 1328 # class C3(C1, C2): 1329 # __slots__ = [] 1330 # 1331 # class C4(C2, C1): 1332 # __slots__ = [] 1333 1334 def dynamics(): 1335 if verbose: print "Testing class attribute propagation..." 1336 class D(object): 1337 pass 1338 class E(D): 1339 pass 1340 class F(D): 1341 pass 1342 D.foo = 1 1343 vereq(D.foo, 1) 1344 # Test that dynamic attributes are inherited 1345 vereq(E.foo, 1) 1346 vereq(F.foo, 1) 1347 # Test dynamic instances 1348 class C(object): 1349 pass 1350 a = C() 1351 verify(not hasattr(a, "foobar")) 1352 C.foobar = 2 1353 vereq(a.foobar, 2) 1354 C.method = lambda self: 42 1355 vereq(a.method(), 42) 1356 C.__repr__ = lambda self: "C()" 1357 vereq(repr(a), "C()") 1358 C.__int__ = lambda self: 100 1359 vereq(int(a), 100) 1360 vereq(a.foobar, 2) 1361 verify(not hasattr(a, "spam")) 1362 def mygetattr(self, name): 1363 if name == "spam": 1364 return "spam" 1365 raise AttributeError 1366 C.__getattr__ = mygetattr 1367 vereq(a.spam, "spam") 1368 a.new = 12 1369 vereq(a.new, 12) 1370 def mysetattr(self, name, value): 1371 if name == "spam": 1372 raise AttributeError 1373 return object.__setattr__(self, name, value) 1374 C.__setattr__ = mysetattr 1375 try: 1376 a.spam = "not spam" 1377 except AttributeError: 1378 pass 1379 else: 1380 verify(0, "expected AttributeError") 1381 vereq(a.spam, "spam") 1382 class D(C): 1383 pass 1384 d = D() 1385 d.foo = 1 1386 vereq(d.foo, 1) 1387 1388 # Test handling of int*seq and seq*int 1389 class I(int): 1390 pass 1391 vereq("a"*I(2), "aa") 1392 vereq(I(2)*"a", "aa") 1393 vereq(2*I(3), 6) 1394 vereq(I(3)*2, 6) 1395 vereq(I(3)*I(2), 6) 1396 1397 # Test handling of long*seq and seq*long 1398 class L(long): 1399 pass 1400 vereq("a"*L(2L), "aa") 1401 vereq(L(2L)*"a", "aa") 1402 vereq(2*L(3), 6) 1403 vereq(L(3)*2, 6) 1404 vereq(L(3)*L(2), 6) 1405 1406 # Test comparison of classes with dynamic metaclasses 1407 class dynamicmetaclass(type): 1408 pass 1409 class someclass: 1410 __metaclass__ = dynamicmetaclass 1411 verify(someclass != object) 1412 1413 def errors(): 1414 if verbose: print "Testing errors..." 1415 1416 try: 1417 class C(list, dict): 1418 pass 1419 except TypeError: 1420 pass 1421 else: 1422 verify(0, "inheritance from both list and dict should be illegal") 1423 1424 try: 1425 class C(object, None): 1426 pass 1427 except TypeError: 1428 pass 1429 else: 1430 verify(0, "inheritance from non-type should be illegal") 1431 class Classic: 1432 pass 1433 1434 try: 1435 class C(type(len)): 1436 pass 1437 except TypeError: 1438 pass 1439 else: 1440 verify(0, "inheritance from CFunction should be illegal") 1441 1442 try: 1443 class C(object): 1444 __slots__ = 1 1445 except TypeError: 1446 pass 1447 else: 1448 verify(0, "__slots__ = 1 should be illegal") 1449 1450 try: 1451 class C(object): 1452 __slots__ = [1] 1453 except TypeError: 1454 pass 1455 else: 1456 verify(0, "__slots__ = [1] should be illegal") 1457 1458 def classmethods(): 1459 if verbose: print "Testing class methods..." 1460 class C(object): 1461 def foo(*a): return a 1462 goo = classmethod(foo) 1463 c = C() 1464 vereq(C.goo(1), (C, 1)) 1465 vereq(c.goo(1), (C, 1)) 1466 vereq(c.foo(1), (c, 1)) 1467 class D(C): 1468 pass 1469 d = D() 1470 vereq(D.goo(1), (D, 1)) 1471 vereq(d.goo(1), (D, 1)) 1472 vereq(d.foo(1), (d, 1)) 1473 vereq(D.foo(d, 1), (d, 1)) 1474 # Test for a specific crash (SF bug 528132) 1475 def f(cls, arg): return (cls, arg) 1476 ff = classmethod(f) 1477 vereq(ff.__get__(0, int)(42), (int, 42)) 1478 vereq(ff.__get__(0)(42), (int, 42)) 1479 1480 # Test super() with classmethods (SF bug 535444) 1481 veris(C.goo.im_self, C) 1482 veris(D.goo.im_self, D) 1483 veris(super(D,D).goo.im_self, D) 1484 veris(super(D,d).goo.im_self, D) 1485 vereq(super(D,D).goo(), (D,)) 1486 vereq(super(D,d).goo(), (D,)) 1487 1488 # Verify that argument is checked for callability (SF bug 753451) 1489 try: 1490 classmethod(1).__get__(1) 1491 except TypeError: 1492 pass 1493 else: 1494 raise TestFailed, "classmethod should check for callability" 1495 1496 def classmethods_in_c(): 1497 if verbose: print "Testing C-based class methods..." 1498 import xxsubtype as spam 1499 a = (1, 2, 3) 1500 d = {'abc': 123} 1501 x, a1, d1 = spam.spamlist.classmeth(*a, **d) 1502 veris(x, spam.spamlist) 1503 vereq(a, a1) 1504 vereq(d, d1) 1505 x, a1, d1 = spam.spamlist().classmeth(*a, **d) 1506 veris(x, spam.spamlist) 1507 vereq(a, a1) 1508 vereq(d, d1) 1509 1510 def staticmethods(): 1511 if verbose: print "Testing static methods..." 1512 class C(object): 1513 def foo(*a): return a 1514 goo = staticmethod(foo) 1515 c = C() 1516 vereq(C.goo(1), (1,)) 1517 vereq(c.goo(1), (1,)) 1518 vereq(c.foo(1), (c, 1,)) 1519 class D(C): 1520 pass 1521 d = D() 1522 vereq(D.goo(1), (1,)) 1523 vereq(d.goo(1), (1,)) 1524 vereq(d.foo(1), (d, 1)) 1525 vereq(D.foo(d, 1), (d, 1)) 1526 1527 def staticmethods_in_c(): 1528 if verbose: print "Testing C-based static methods..." 1529 import xxsubtype as spam 1530 a = (1, 2, 3) 1531 d = {"abc": 123} 1532 x, a1, d1 = spam.spamlist.staticmeth(*a, **d) 1533 veris(x, None) 1534 vereq(a, a1) 1535 vereq(d, d1) 1536 x, a1, d2 = spam.spamlist().staticmeth(*a, **d) 1537 veris(x, None) 1538 vereq(a, a1) 1539 vereq(d, d1) 1540 1541 def classic(): 1542 if verbose: print "Testing classic classes..." 1543 class C: 1544 def foo(*a): return a 1545 goo = classmethod(foo) 1546 c = C() 1547 vereq(C.goo(1), (C, 1)) 1548 vereq(c.goo(1), (C, 1)) 1549 vereq(c.foo(1), (c, 1)) 1550 class D(C): 1551 pass 1552 d = D() 1553 vereq(D.goo(1), (D, 1)) 1554 vereq(d.goo(1), (D, 1)) 1555 vereq(d.foo(1), (d, 1)) 1556 vereq(D.foo(d, 1), (d, 1)) 1557 class E: # *not* subclassing from C 1558 foo = C.foo 1559 vereq(E().foo, C.foo) # i.e., unbound 1560 verify(repr(C.foo.__get__(C())).startswith("<bound method ")) 1561 1562 def compattr(): 1563 if verbose: print "Testing computed attributes..." 1564 class C(object): 1565 class computed_attribute(object): 1566 def __init__(self, get, set=None, delete=None): 1567 self.__get = get 1568 self.__set = set 1569 self.__delete = delete 1570 def __get__(self, obj, type=None): 1571 return self.__get(obj) 1572 def __set__(self, obj, value): 1573 return self.__set(obj, value) 1574 def __delete__(self, obj): 1575 return self.__delete(obj) 1576 def __init__(self): 1577 self.__x = 0 1578 def __get_x(self): 1579 x = self.__x 1580 self.__x = x+1 1581 return x 1582 def __set_x(self, x): 1583 self.__x = x 1584 def __delete_x(self): 1585 del self.__x 1586 x = computed_attribute(__get_x, __set_x, __delete_x) 1587 a = C() 1588 vereq(a.x, 0) 1589 vereq(a.x, 1) 1590 a.x = 10 1591 vereq(a.x, 10) 1592 vereq(a.x, 11) 1593 del a.x 1594 vereq(hasattr(a, 'x'), 0) 1595 1596 def newslot(): 1597 if verbose: print "Testing __new__ slot override..." 1598 class C(list): 1599 def __new__(cls): 1600 self = list.__new__(cls) 1601 self.foo = 1 1602 return self 1603 def __init__(self): 1604 self.foo = self.foo + 2 1605 a = C() 1606 vereq(a.foo, 3) 1607 verify(a.__class__ is C) 1608 class D(C): 1609 pass 1610 b = D() 1611 vereq(b.foo, 3) 1612 verify(b.__class__ is D) 1613 1614 def altmro(): 1615 if verbose: print "Testing mro() and overriding it..." 1616 class A(object): 1617 def f(self): return "A" 1618 class B(A): 1619 pass 1620 class C(A): 1621 def f(self): return "C" 1622 class D(B, C): 1623 pass 1624 vereq(D.mro(), [D, B, C, A, object]) 1625 vereq(D.__mro__, (D, B, C, A, object)) 1626 vereq(D().f(), "C") 1627 1628 class PerverseMetaType(type): 1629 def mro(cls): 1630 L = type.mro(cls) 1631 L.reverse() 1632 return L 1633 class X(D,B,C,A): 1634 __metaclass__ = PerverseMetaType 1635 vereq(X.__mro__, (object, A, C, B, D, X)) 1636 vereq(X().f(), "A") 1637 1638 def overloading(): 1639 if verbose: print "Testing operator overloading..." 1640 1641 class B(object): 1642 "Intermediate class because object doesn't have a __setattr__" 1643 1644 class C(B): 1645 1646 def __getattr__(self, name): 1647 if name == "foo": 1648 return ("getattr", name) 1649 else: 1650 raise AttributeError 1651 def __setattr__(self, name, value): 1652 if name == "foo": 1653 self.setattr = (name, value) 1654 else: 1655 return B.__setattr__(self, name, value) 1656 def __delattr__(self, name): 1657 if name == "foo": 1658 self.delattr = name 1659 else: 1660 return B.__delattr__(self, name) 1661 1662 def __getitem__(self, key): 1663 return ("getitem", key) 1664 def __setitem__(self, key, value): 1665 self.setitem = (key, value) 1666 def __delitem__(self, key): 1667 self.delitem = key 1668 1669 def __getslice__(self, i, j): 1670 return ("getslice", i, j) 1671 def __setslice__(self, i, j, value): 1672 self.setslice = (i, j, value) 1673 def __delslice__(self, i, j): 1674 self.delslice = (i, j) 1675 1676 a = C() 1677 vereq(a.foo, ("getattr", "foo")) 1678 a.foo = 12 1679 vereq(a.setattr, ("foo", 12)) 1680 del a.foo 1681 vereq(a.delattr, "foo") 1682 1683 vereq(a[12], ("getitem", 12)) 1684 a[12] = 21 1685 vereq(a.setitem, (12, 21)) 1686 del a[12] 1687 vereq(a.delitem, 12) 1688 1689 vereq(a[0:10], ("getslice", 0, 10)) 1690 a[0:10] = "foo" 1691 vereq(a.setslice, (0, 10, "foo")) 1692 del a[0:10] 1693 vereq(a.delslice, (0, 10)) 1694 1695 def methods(): 1696 if verbose: print "Testing methods..." 1697 class C(object): 1698 def __init__(self, x): 1699 self.x = x 1700 def foo(self): 1701 return self.x 1702 c1 = C(1) 1703 vereq(c1.foo(), 1) 1704 class D(C): 1705 boo = C.foo 1706 goo = c1.foo 1707 d2 = D(2) 1708 vereq(d2.foo(), 2) 1709 vereq(d2.boo(), 2) 1710 vereq(d2.goo(), 1) 1711 class E(object): 1712 foo = C.foo 1713 vereq(E().foo, C.foo) # i.e., unbound 1714 verify(repr(C.foo.__get__(C(1))).startswith("<bound method ")) 1715 1716 def specials(): 1717 # Test operators like __hash__ for which a built-in default exists 1718 if verbose: print "Testing special operators..." 1719 # Test the default behavior for static classes 1720 class C(object): 1721 def __getitem__(self, i): 1722 if 0 <= i < 10: return i 1723 raise IndexError 1724 c1 = C() 1725 c2 = C() 1726 verify(not not c1) 1727 vereq(hash(c1), id(c1)) 1728 vereq(cmp(c1, c2), cmp(id(c1), id(c2))) 1729 vereq(c1, c1) 1730 verify(c1 != c2) 1731 verify(not c1 != c1) 1732 verify(not c1 == c2) 1733 # Note that the module name appears in str/repr, and that varies 1734 # depending on whether this test is run standalone or from a framework. 1735 verify(str(c1).find('C object at ') >= 0) 1736 vereq(str(c1), repr(c1)) 1737 verify(-1 not in c1) 1738 for i in range(10): 1739 verify(i in c1) 1740 verify(10 not in c1) 1741 # Test the default behavior for dynamic classes 1742 class D(object): 1743 def __getitem__(self, i): 1744 if 0 <= i < 10: return i 1745 raise IndexError 1746 d1 = D() 1747 d2 = D() 1748 verify(not not d1) 1749 vereq(hash(d1), id(d1)) 1750 vereq(cmp(d1, d2), cmp(id(d1), id(d2))) 1751 vereq(d1, d1) 1752 verify(d1 != d2) 1753 verify(not d1 != d1) 1754 verify(not d1 == d2) 1755 # Note that the module name appears in str/repr, and that varies 1756 # depending on whether this test is run standalone or from a framework. 1757 verify(str(d1).find('D object at ') >= 0) 1758 vereq(str(d1), repr(d1)) 1759 verify(-1 not in d1) 1760 for i in range(10): 1761 verify(i in d1) 1762 verify(10 not in d1) 1763 # Test overridden behavior for static classes 1764 class Proxy(object): 1765 def __init__(self, x): 1766 self.x = x 1767 def __nonzero__(self): 1768 return not not self.x 1769 def __hash__(self): 1770 return hash(self.x) 1771 def __eq__(self, other): 1772 return self.x == other 1773 def __ne__(self, other): 1774 return self.x != other 1775 def __cmp__(self, other): 1776 return cmp(self.x, other.x) 1777 def __str__(self): 1778 return "Proxy:%s" % self.x 1779 def __repr__(self): 1780 return "Proxy(%r)" % self.x 1781 def __contains__(self, value): 1782 return value in self.x 1783 p0 = Proxy(0) 1784 p1 = Proxy(1) 1785 p_1 = Proxy(-1) 1786 verify(not p0) 1787 verify(not not p1) 1788 vereq(hash(p0), hash(0)) 1789 vereq(p0, p0) 1790 verify(p0 != p1) 1791 verify(not p0 != p0) 1792 vereq(not p0, p1) 1793 vereq(cmp(p0, p1), -1) 1794 vereq(cmp(p0, p0), 0) 1795 vereq(cmp(p0, p_1), 1) 1796 vereq(str(p0), "Proxy:0") 1797 vereq(repr(p0), "Proxy(0)") 1798 p10 = Proxy(range(10)) 1799 verify(-1 not in p10) 1800 for i in range(10): 1801 verify(i in p10) 1802 verify(10 not in p10) 1803 # Test overridden behavior for dynamic classes 1804 class DProxy(object): 1805 def __init__(self, x): 1806 self.x = x 1807 def __nonzero__(self): 1808 return not not self.x 1809 def __hash__(self): 1810 return hash(self.x) 1811 def __eq__(self, other): 1812 return self.x == other 1813 def __ne__(self, other): 1814 return self.x != other 1815 def __cmp__(self, other): 1816 return cmp(self.x, other.x) 1817 def __str__(self): 1818 return "DProxy:%s" % self.x 1819 def __repr__(self): 1820 return "DProxy(%r)" % self.x 1821 def __contains__(self, value): 1822 return value in self.x 1823 p0 = DProxy(0) 1824 p1 = DProxy(1) 1825 p_1 = DProxy(-1) 1826 verify(not p0) 1827 verify(not not p1) 1828 vereq(hash(p0), hash(0)) 1829 vereq(p0, p0) 1830 verify(p0 != p1) 1831 verify(not p0 != p0) 1832 vereq(not p0, p1) 1833 vereq(cmp(p0, p1), -1) 1834 vereq(cmp(p0, p0), 0) 1835 vereq(cmp(p0, p_1), 1) 1836 vereq(str(p0), "DProxy:0") 1837 vereq(repr(p0), "DProxy(0)") 1838 p10 = DProxy(range(10)) 1839 verify(-1 not in p10) 1840 for i in range(10): 1841 verify(i in p10) 1842 verify(10 not in p10) 1843 # Safety test for __cmp__ 1844 def unsafecmp(a, b): 1845 try: 1846 a.__class__.__cmp__(a, b) 1847 except TypeError: 1848 pass 1849 else: 1850 raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % ( 1851 a.__class__, a, b) 1852 unsafecmp(u"123", "123") 1853 unsafecmp("123", u"123") 1854 unsafecmp(1, 1.0) 1855 unsafecmp(1.0, 1) 1856 unsafecmp(1, 1L) 1857 unsafecmp(1L, 1) 1858 1859 class Letter(str): 1860 def __new__(cls, letter): 1861 if letter == 'EPS': 1862 return str.__new__(cls) 1863 return str.__new__(cls, letter) 1864 def __str__(self): 1865 if not self: 1866 return 'EPS' 1867 return self 1868 1869 # sys.stdout needs to be the original to trigger the recursion bug 1870 import sys 1871 test_stdout = sys.stdout 1872 sys.stdout = get_original_stdout() 1873 try: 1874 # nothing should actually be printed, this should raise an exception 1875 print Letter('w') 1876 except RuntimeError: 1877 pass 1878 else: 1879 raise TestFailed, "expected a RuntimeError for print recursion" 1880 sys.stdout = test_stdout 1881 1882 def weakrefs(): 1883 if verbose: print "Testing weak references..." 1884 import weakref 1885 class C(object): 1886 pass 1887 c = C() 1888 r = weakref.ref(c) 1889 verify(r() is c) 1890 del c 1891 verify(r() is None) 1892 del r 1893 class NoWeak(object): 1894 __slots__ = ['foo'] 1895 no = NoWeak() 1896 try: 1897 weakref.ref(no) 1898 except TypeError, msg: 1899 verify(str(msg).find("weak reference") >= 0) 1900 else: 1901 verify(0, "weakref.ref(no) should be illegal") 1902 class Weak(object): 1903 __slots__ = ['foo', '__weakref__'] 1904 yes = Weak() 1905 r = weakref.ref(yes) 1906 verify(r() is yes) 1907 del yes 1908 verify(r() is None) 1909 del r 1910 1911 def properties(): 1912 if verbose: print "Testing property..." 1913 class C(object): 1914 def getx(self): 1915 return self.__x 1916 def setx(self, value): 1917 self.__x = value 1918 def delx(self): 1919 del self.__x 1920 x = property(getx, setx, delx, doc="I'm the x property.") 1921 a = C() 1922 verify(not hasattr(a, "x")) 1923 a.x = 42 1924 vereq(a._C__x, 42) 1925 vereq(a.x, 42) 1926 del a.x 1927 verify(not hasattr(a, "x")) 1928 verify(not hasattr(a, "_C__x")) 1929 C.x.__set__(a, 100) 1930 vereq(C.x.__get__(a), 100) 1931 C.x.__delete__(a) 1932 verify(not hasattr(a, "x")) 1933 1934 raw = C.__dict__['x'] 1935 verify(isinstance(raw, property)) 1936 1937 attrs = dir(raw) 1938 verify("__doc__" in attrs) 1939 verify("fget" in attrs) 1940 verify("fset" in attrs) 1941 verify("fdel" in attrs) 1942 1943 vereq(raw.__doc__, "I'm the x property.") 1944 verify(raw.fget is C.__dict__['getx']) 1945 verify(raw.fset is C.__dict__['setx']) 1946 verify(raw.fdel is C.__dict__['delx']) 1947 1948 for attr in "__doc__", "fget", "fset", "fdel": 1949 try: 1950 setattr(raw, attr, 42) 1951 except TypeError, msg: 1952 if str(msg).find('readonly') < 0: 1953 raise TestFailed("when setting readonly attr %r on a " 1954 "property, got unexpected TypeError " 1955 "msg %r" % (attr, str(msg))) 1956 else: 1957 raise TestFailed("expected TypeError from trying to set " 1958 "readonly %r attr on a property" % attr) 1959 1960 class D(object): 1961 __getitem__ = property(lambda s: 1/0) 1962 1963 d = D() 1964 try: 1965 for i in d: 1966 str(i) 1967 except ZeroDivisionError: 1968 pass 1969 else: 1970 raise TestFailed, "expected ZeroDivisionError from bad property" 1971 1972 def supers(): 1973 if verbose: print "Testing super..." 1974 1975 class A(object): 1976 def meth(self, a): 1977 return "A(%r)" % a 1978 1979 vereq(A().meth(1), "A(1)") 1980 1981 class B(A): 1982 def __init__(self): 1983 self.__super = super(B, self) 1984 def meth(self, a): 1985 return "B(%r)" % a + self.__super.meth(a) 1986 1987 vereq(B().meth(2), "B(2)A(2)") 1988 1989 class C(A): 1990 def meth(self, a): 1991 return "C(%r)" % a + self.__super.meth(a) 1992 C._C__super = super(C) 1993 1994 vereq(C().meth(3), "C(3)A(3)") 1995 1996 class D(C, B): 1997 def meth(self, a): 1998 return "D(%r)" % a + super(D, self).meth(a) 1999 2000 vereq(D().meth(4), "D(4)C(4)B(4)A(4)") 2001 2002 # Test for subclassing super 2003 2004 class mysuper(super): 2005 def __init__(self, *args): 2006 return super(mysuper, self).__init__(*args) 2007 2008 class E(D): 2009 def meth(self, a): 2010 return "E(%r)" % a + mysuper(E, self).meth(a) 2011 2012 vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)") 2013 2014 class F(E): 2015 def meth(self, a): 2016 s = self.__super # == mysuper(F, self) 2017 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a) 2018 F._F__super = mysuper(F) 2019 2020 vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)") 2021 2022 # Make sure certain errors are raised 2023 2024 try: 2025 super(D, 42) 2026 except TypeError: 2027 pass 2028 else: 2029 raise TestFailed, "shouldn't allow super(D, 42)" 2030 2031 try: 2032 super(D, C()) 2033 except TypeError: 2034 pass 2035 else: 2036 raise TestFailed, "shouldn't allow super(D, C())" 2037 2038 try: 2039 super(D).__get__(12) 2040 except TypeError: 2041 pass 2042 else: 2043 raise TestFailed, "shouldn't allow super(D).__get__(12)" 2044 2045 try: 2046 super(D).__get__(C()) 2047 except TypeError: 2048 pass 2049 else: 2050 raise TestFailed, "shouldn't allow super(D).__get__(C())" 2051 2052 # Make sure data descriptors can be overridden and accessed via super 2053 # (new feature in Python 2.3) 2054 2055 class DDbase(object): 2056 def getx(self): return 42 2057 x = property(getx) 2058 2059 class DDsub(DDbase): 2060 def getx(self): return "hello" 2061 x = property(getx) 2062 2063 dd = DDsub() 2064 vereq(dd.x, "hello") 2065 vereq(super(DDsub, dd).x, 42) 2066 2067 # Ensure that super() lookup of descriptor from classmethod 2068 # works (SF ID# 743627) 2069 2070 class Base(object): 2071 aProp = property(lambda self: "foo") 2072 2073 class Sub(Base): 2074 def test(klass): 2075 return super(Sub,klass).aProp 2076 test = classmethod(test) 2077 2078 veris(Sub.test(), Base.aProp) 2079 2080 2081 def inherits(): 2082 if verbose: print "Testing inheritance from basic types..." 2083 2084 class hexint(int): 2085 def __repr__(self): 2086 return hex(self) 2087 def __add__(self, other): 2088 return hexint(int.__add__(self, other)) 2089 # (Note that overriding __radd__ doesn't work, 2090 # because the int type gets first dibs.) 2091 vereq(repr(hexint(7) + 9), "0x10") 2092 vereq(repr(hexint(1000) + 7), "0x3ef") 2093 a = hexint(12345) 2094 vereq(a, 12345) 2095 vereq(int(a), 12345) 2096 verify(int(a).__class__ is int) 2097 vereq(hash(a), hash(12345)) 2098 verify((+a).__class__ is int) 2099 verify((a >> 0).__class__ is int) 2100 verify((a << 0).__class__ is int) 2101 verify((hexint(0) << 12).__class__ is int) 2102 verify((hexint(0) >> 12).__class__ is int) 2103 2104 class octlong(long): 2105 __slots__ = [] 2106 def __str__(self): 2107 s = oct(self) 2108 if s[-1] == 'L': 2109 s = s[:-1] 2110 return s 2111 def __add__(self, other): 2112 return self.__class__(super(octlong, self).__add__(other)) 2113 __radd__ = __add__ 2114 vereq(str(octlong(3) + 5), "010") 2115 # (Note that overriding __radd__ here only seems to work 2116 # because the example uses a short int left argument.) 2117 vereq(str(5 + octlong(3000)), "05675") 2118 a = octlong(12345) 2119 vereq(a, 12345L) 2120 vereq(long(a), 12345L) 2121 vereq(hash(a), hash(12345L)) 2122 verify(long(a).__class__ is long) 2123 verify((+a).__class__ is long) 2124 verify((-a).__class__ is long) 2125 verify((-octlong(0)).__class__ is long) 2126 verify((a >> 0).__class__ is long) 2127 verify((a << 0).__class__ is long) 2128 verify((a - 0).__class__ is long) 2129 verify((a * 1).__class__ is long) 2130 verify((a ** 1).__class__ is long) 2131 verify((a // 1).__class__ is long) 2132 verify((1 * a).__class__ is long) 2133 verify((a | 0).__class__ is long) 2134 verify((a ^ 0).__class__ is long) 2135 verify((a & -1L).__class__ is long) 2136 verify((octlong(0) << 12).__class__ is long) 2137 verify((octlong(0) >> 12).__class__ is long) 2138 verify(abs(octlong(0)).__class__ is long) 2139 2140 # Because octlong overrides __add__, we can't check the absence of +0 2141 # optimizations using octlong. 2142 class longclone(long): 2143 pass 2144 a = longclone(1) 2145 verify((a + 0).__class__ is long) 2146 verify((0 + a).__class__ is long) 2147 2148 # Check that negative clones don't segfault 2149 a = longclone(-1) 2150 vereq(a.__dict__, {}) 2151 vereq(long(a), -1) # verify PyNumber_Long() copies the sign bit 2152 2153 class precfloat(float): 2154 __slots__ = ['prec'] 2155 def __init__(self, value=0.0, prec=12): 2156 self.prec = int(prec) 2157 float.__init__(value) 2158 def __repr__(self): 2159 return "%.*g" % (self.prec, self) 2160 vereq(repr(precfloat(1.1)), "1.1") 2161 a = precfloat(12345) 2162 vereq(a, 12345.0) 2163 vereq(float(a), 12345.0) 2164 verify(float(a).__class__ is float) 2165 vereq(hash(a), hash(12345.0)) 2166 verify((+a).__class__ is float) 2167 2168 class madcomplex(complex): 2169 def __repr__(self): 2170 return "%.17gj%+.17g" % (self.imag, self.real) 2171 a = madcomplex(-3, 4) 2172 vereq(repr(a), "4j-3") 2173 base = complex(-3, 4) 2174 veris(base.__class__, complex) 2175 vereq(a, base) 2176 vereq(complex(a), base) 2177 veris(complex(a).__class__, complex) 2178 a = madcomplex(a) # just trying another form of the constructor 2179 vereq(repr(a), "4j-3") 2180 vereq(a, base) 2181 vereq(complex(a), base) 2182 veris(complex(a).__class__, complex) 2183 vereq(hash(a), hash(base)) 2184 veris((+a).__class__, complex) 2185 veris((a + 0).__class__, complex) 2186 vereq(a + 0, base) 2187 veris((a - 0).__class__, complex) 2188 vereq(a - 0, base) 2189 veris((a * 1).__class__, complex) 2190 vereq(a * 1, base) 2191 veris((a / 1).__class__, complex) 2192 vereq(a / 1, base) 2193 2194 class madtuple(tuple): 2195 _rev = None 2196 def rev(self): 2197 if self._rev is not None: 2198 return self._rev 2199 L = list(self) 2200 L.reverse() 2201 self._rev = self.__class__(L) 2202 return self._rev 2203 a = madtuple((1,2,3,4,5,6,7,8,9,0)) 2204 vereq(a, (1,2,3,4,5,6,7,8,9,0)) 2205 vereq(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1))) 2206 vereq(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0))) 2207 for i in range(512): 2208 t = madtuple(range(i)) 2209 u = t.rev() 2210 v = u.rev() 2211 vereq(v, t) 2212 a = madtuple((1,2,3,4,5)) 2213 vereq(tuple(a), (1,2,3,4,5)) 2214 verify(tuple(a).__class__ is tuple) 2215 vereq(hash(a), hash((1,2,3,4,5))) 2216 verify(a[:].__class__ is tuple) 2217 verify((a * 1).__class__ is tuple) 2218 verify((a * 0).__class__ is tuple) 2219 verify((a + ()).__class__ is tuple) 2220 a = madtuple(()) 2221 vereq(tuple(a), ()) 2222 verify(tuple(a).__class__ is tuple) 2223 verify((a + a).__class__ is tuple) 2224 verify((a * 0).__class__ is tuple) 2225 verify((a * 1).__class__ is tuple) 2226 verify((a * 2).__class__ is tuple) 2227 verify(a[:].__class__ is tuple) 2228 2229 class madstring(str): 2230 _rev = None 2231 def rev(self): 2232 if self._rev is not None: 2233 return self._rev 2234 L = list(self) 2235 L.reverse() 2236 self._rev = self.__class__("".join(L)) 2237 return self._rev 2238 s = madstring("abcdefghijklmnopqrstuvwxyz") 2239 vereq(s, "abcdefghijklmnopqrstuvwxyz") 2240 vereq(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba")) 2241 vereq(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz")) 2242 for i in range(256): 2243 s = madstring("".join(map(chr, range(i)))) 2244 t = s.rev() 2245 u = t.rev() 2246 vereq(u, s) 2247 s = madstring("12345") 2248 vereq(str(s), "12345") 2249 verify(str(s).__class__ is str) 2250 2251 base = "\x00" * 5 2252 s = madstring(base) 2253 vereq(s, base) 2254 vereq(str(s), base) 2255 verify(str(s).__class__ is str) 2256 vereq(hash(s), hash(base)) 2257 vereq({s: 1}[base], 1) 2258 vereq({base: 1}[s], 1) 2259 verify((s + "").__class__ is str) 2260 vereq(s + "", base) 2261 verify(("" + s).__class__ is str) 2262 vereq("" + s, base) 2263 verify((s * 0).__class__ is str) 2264 vereq(s * 0, "") 2265 verify((s * 1).__class__ is str) 2266 vereq(s * 1, base) 2267 verify((s * 2).__class__ is str) 2268 vereq(s * 2, base + base) 2269 verify(s[:].__class__ is str) 2270 vereq(s[:], base) 2271 verify(s[0:0].__class__ is str) 2272 vereq(s[0:0], "") 2273 verify(s.strip().__class__ is str) 2274 vereq(s.strip(), base) 2275 verify(s.lstrip().__class__ is str) 2276 vereq(s.lstrip(), base) 2277 verify(s.rstrip().__class__ is str) 2278 vereq(s.rstrip(), base) 2279 identitytab = ''.join([chr(i) for i in range(256)]) 2280 verify(s.translate(identitytab).__class__ is str) 2281 vereq(s.translate(identitytab), base) 2282 verify(s.translate(identitytab, "x").__class__ is str) 2283 vereq(s.translate(identitytab, "x"), base) 2284 vereq(s.translate(identitytab, "\x00"), "") 2285 verify(s.replace("x", "x").__class__ is str) 2286 vereq(s.replace("x", "x"), base) 2287 verify(s.ljust(len(s)).__class__ is str) 2288 vereq(s.ljust(len(s)), base) 2289 verify(s.rjust(len(s)).__class__ is str) 2290 vereq(s.rjust(len(s)), base) 2291 verify(s.center(len(s)).__class__ is str) 2292 vereq(s.center(len(s)), base) 2293 verify(s.lower().__class__ is str) 2294 vereq(s.lower(), base) 2295 2296 class madunicode(unicode): 2297 _rev = None 2298 def rev(self): 2299 if self._rev is not None: 2300 return self._rev 2301 L = list(self) 2302 L.reverse() 2303 self._rev = self.__class__(u"".join(L)) 2304 return self._rev 2305 u = madunicode("ABCDEF") 2306 vereq(u, u"ABCDEF") 2307 vereq(u.rev(), madunicode(u"FEDCBA")) 2308 vereq(u.rev().rev(), madunicode(u"ABCDEF")) 2309 base = u"12345" 2310 u = madunicode(base) 2311 vereq(unicode(u), base) 2312 verify(unicode(u).__class__ is unicode) 2313 vereq(hash(u), hash(base)) 2314 vereq({u: 1}[base], 1) 2315 vereq({base: 1}[u], 1) 2316 verify(u.strip().__class__ is unicode) 2317 vereq(u.strip(), base) 2318 verify(u.lstrip().__class__ is unicode) 2319 vereq(u.lstrip(), base) 2320 verify(u.rstrip().__class__ is unicode) 2321 vereq(u.rstrip(), base) 2322 verify(u.replace(u"x", u"x").__class__ is unicode) 2323 vereq(u.replace(u"x", u"x"), base) 2324 verify(u.replace(u"xy", u"xy").__class__ is unicode) 2325 vereq(u.replace(u"xy", u"xy"), base) 2326 verify(u.center(len(u)).__class__ is unicode) 2327 vereq(u.center(len(u)), base) 2328 verify(u.ljust(len(u)).__class__ is unicode) 2329 vereq(u.ljust(len(u)), base) 2330 verify(u.rjust(len(u)).__class__ is unicode) 2331 vereq(u.rjust(len(u)), base) 2332 verify(u.lower().__class__ is unicode) 2333 vereq(u.lower(), base) 2334 verify(u.upper().__class__ is unicode) 2335 vereq(u.upper(), base) 2336 verify(u.capitalize().__class__ is unicode) 2337 vereq(u.capitalize(), base) 2338 verify(u.title().__class__ is unicode) 2339 vereq(u.title(), base) 2340 verify((u + u"").__class__ is unicode) 2341 vereq(u + u"", base) 2342 verify((u"" + u).__class__ is unicode) 2343 vereq(u"" + u, base) 2344 verify((u * 0).__class__ is unicode) 2345 vereq(u * 0, u"") 2346 verify((u * 1).__class__ is unicode) 2347 vereq(u * 1, base) 2348 verify((u * 2).__class__ is unicode) 2349 vereq(u * 2, base + base) 2350 verify(u[:].__class__ is unicode) 2351 vereq(u[:], base) 2352 verify(u[0:0].__class__ is unicode) 2353 vereq(u[0:0], u"") 2354 2355 class sublist(list): 2356 pass 2357 a = sublist(range(5)) 2358 vereq(a, range(5)) 2359 a.append("hello") 2360 vereq(a, range(5) + ["hello"]) 2361 a[5] = 5 2362 vereq(a, range(6)) 2363 a.extend(range(6, 20)) 2364 vereq(a, range(20)) 2365 a[-5:] = [] 2366 vereq(a, range(15)) 2367 del a[10:15] 2368 vereq(len(a), 10) 2369 vereq(a, range(10)) 2370 vereq(list(a), range(10)) 2371 vereq(a[0], 0) 2372 vereq(a[9], 9) 2373 vereq(a[-10], 0) 2374 vereq(a[-1], 9) 2375 vereq(a[:5], range(5)) 2376 2377 class CountedInput(file): 2378 """Counts lines read by self.readline(). 2379 2380 self.lineno is the 0-based ordinal of the last line read, up to 2381 a maximum of one greater than the number of lines in the file. 2382 2383 self.ateof is true if and only if the final "" line has been read, 2384 at which point self.lineno stops incrementing, and further calls 2385 to readline() continue to return "". 2386 """ 2387 2388 lineno = 0 2389 ateof = 0 2390 def readline(self): 2391 if self.ateof: 2392 return "" 2393 s = file.readline(self) 2394 # Next line works too. 2395 # s = super(CountedInput, self).readline() 2396 self.lineno += 1 2397 if s == "": 2398 self.ateof = 1 2399 return s 2400 2401 f = file(name=TESTFN, mode='w') 2402 lines = ['a\n', 'b\n', 'c\n'] 2403 try: 2404 f.writelines(lines) 2405 f.close() 2406 f = CountedInput(TESTFN) 2407 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]): 2408 got = f.readline() 2409 vereq(expected, got) 2410 vereq(f.lineno, i) 2411 vereq(f.ateof, (i > len(lines))) 2412 f.close() 2413 finally: 2414 try: 2415 f.close() 2416 except: 2417 pass 2418 try: 2419 import os 2420 os.unlink(TESTFN) 2421 except: 2422 pass 2423 2424 def keywords(): 2425 if verbose: 2426 print "Testing keyword args to basic type constructors ..." 2427 vereq(int(x=1), 1) 2428 vereq(float(x=2), 2.0) 2429 vereq(long(x=3), 3L) 2430 vereq(complex(imag=42, real=666), complex(666, 42)) 2431 vereq(str(object=500), '500') 2432 vereq(unicode(string='abc', errors='strict'), u'abc') 2433 vereq(tuple(sequence=range(3)), (0, 1, 2)) 2434 vereq(list(sequence=(0, 1, 2)), range(3)) 2435 # note: as of Python 2.3, dict() no longer has an "items" keyword arg 2436 2437 for constructor in (int, float, long, complex, str, unicode, 2438 tuple, list, file): 2439 try: 2440 constructor(bogus_keyword_arg=1) 2441 except TypeError: 2442 pass 2443 else: 2444 raise TestFailed("expected TypeError from bogus keyword " 2445 "argument to %r" % constructor) 2446 2447 def restricted(): 2448 # XXX This test is disabled because rexec is not deemed safe 2449 return 2450 import rexec 2451 if verbose: 2452 print "Testing interaction with restricted execution ..." 2453 2454 sandbox = rexec.RExec() 2455 2456 code1 = """f = open(%r, 'w')""" % TESTFN 2457 code2 = """f = file(%r, 'w')""" % TESTFN 2458 code3 = """\ 2459 f = open(%r) 2460 t = type(f) # a sneaky way to get the file() constructor 2461 f.close() 2462 f = t(%r, 'w') # rexec can't catch this by itself 2463 """ % (TESTFN, TESTFN) 2464 2465 f = open(TESTFN, 'w') # Create the file so code3 can find it. 2466 f.close() 2467 2468 try: 2469 for code in code1, code2, code3: 2470 try: 2471 sandbox.r_exec(code) 2472 except IOError, msg: 2473 if str(msg).find("restricted") >= 0: 2474 outcome = "OK" 2475 else: 2476 outcome = "got an exception, but not an expected one" 2477 else: 2478 outcome = "expected a restricted-execution exception" 2479 2480 if outcome != "OK": 2481 raise TestFailed("%s, in %r" % (outcome, code)) 2482 2483 finally: 2484 try: 2485 import os 2486 os.unlink(TESTFN) 2487 except: 2488 pass 2489 2490 def str_subclass_as_dict_key(): 2491 if verbose: 2492 print "Testing a str subclass used as dict key .." 2493 2494 class cistr(str): 2495 """Sublcass of str that computes __eq__ case-insensitively. 2496 2497 Also computes a hash code of the string in canonical form. 2498 """ 2499 2500 def __init__(self, value): 2501 self.canonical = value.lower() 2502 self.hashcode = hash(self.canonical) 2503 2504 def __eq__(self, other): 2505 if not isinstance(other, cistr): 2506 other = cistr(other) 2507 return self.canonical == other.canonical 2508 2509 def __hash__(self): 2510 return self.hashcode 2511 2512 vereq(cistr('ABC'), 'abc') 2513 vereq('aBc', cistr('ABC')) 2514 vereq(str(cistr('ABC')), 'ABC') 2515 2516 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3} 2517 vereq(d[cistr('one')], 1) 2518 vereq(d[cistr('tWo')], 2) 2519 vereq(d[cistr('THrEE')], 3) 2520 verify(cistr('ONe') in d) 2521 vereq(d.get(cistr('thrEE')), 3) 2522 2523 def classic_comparisons(): 2524 if verbose: print "Testing classic comparisons..." 2525 class classic: 2526 pass 2527 for base in (classic, int, object): 2528 if verbose: print " (base = %s)" % base 2529 class C(base): 2530 def __init__(self, value): 2531 self.value = int(value) 2532 def __cmp__(self, other): 2533 if isinstance(other, C): 2534 return cmp(self.value, other.value) 2535 if isinstance(other, int) or isinstance(other, long): 2536 return cmp(self.value, other) 2537 return NotImplemented 2538 c1 = C(1) 2539 c2 = C(2) 2540 c3 = C(3) 2541 vereq(c1, 1) 2542 c = {1: c1, 2: c2, 3: c3} 2543 for x in 1, 2, 3: 2544 for y in 1, 2, 3: 2545 verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y)) 2546 for op in "<", "<=", "==", "!=", ">", ">=": 2547 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op), 2548 "x=%d, y=%d" % (x, y)) 2549 verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y)) 2550 verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y)) 2551 2552 def rich_comparisons(): 2553 if verbose: 2554 print "Testing rich comparisons..." 2555 class Z(complex): 2556 pass 2557 z = Z(1) 2558 vereq(z, 1+0j) 2559 vereq(1+0j, z) 2560 class ZZ(complex): 2561 def __eq__(self, other): 2562 try: 2563 return abs(self - other) <= 1e-6 2564 except: 2565 return NotImplemented 2566 zz = ZZ(1.0000003) 2567 vereq(zz, 1+0j) 2568 vereq(1+0j, zz) 2569 2570 class classic: 2571 pass 2572 for base in (classic, int, object, list): 2573 if verbose: print " (base = %s)" % base 2574 class C(base): 2575 def __init__(self, value): 2576 self.value = int(value) 2577 def __cmp__(self, other): 2578 raise TestFailed, "shouldn't call __cmp__" 2579 def __eq__(self, other): 2580 if isinstance(other, C): 2581 return self.value == other.value 2582 if isinstance(other, int) or isinstance(other, long): 2583 return self.value == other 2584 return NotImplemented 2585 def __ne__(self, other): 2586 if isinstance(other, C): 2587 return self.value != other.value 2588 if isinstance(other, int) or isinstance(other, long): 2589 return self.value != other 2590 return NotImplemented 2591 def __lt__(self, other): 2592 if isinstance(other, C): 2593 return self.value < other.value 2594 if isinstance(other, int) or isinstance(other, long): 2595 return self.value < other 2596 return NotImplemented 2597 def __le__(self, other): 2598 if isinstance(other, C): 2599 return self.value <= other.value 2600 if isinstance(other, int) or isinstance(other, long): 2601 return self.value <= other 2602 return NotImplemented 2603 def __gt__(self, other): 2604 if isinstance(other, C): 2605 return self.value > other.value 2606 if isinstance(other, int) or isinstance(other, long): 2607 return self.value > other 2608 return NotImplemented 2609 def __ge__(self, other): 2610 if isinstance(other, C): 2611 return self.value >= other.value 2612 if isinstance(other, int) or isinstance(other, long): 2613 return self.value >= other 2614 return NotImplemented 2615 c1 = C(1) 2616 c2 = C(2) 2617 c3 = C(3) 2618 vereq(c1, 1) 2619 c = {1: c1, 2: c2, 3: c3} 2620 for x in 1, 2, 3: 2621 for y in 1, 2, 3: 2622 for op in "<", "<=", "==", "!=", ">", ">=": 2623 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op), 2624 "x=%d, y=%d" % (x, y)) 2625 verify(eval("c[x] %s y" % op) == eval("x %s y" % op), 2626 "x=%d, y=%d" % (x, y)) 2627 verify(eval("x %s c[y]" % op) == eval("x %s y" % op), 2628 "x=%d, y=%d" % (x, y)) 2629 2630 def coercions(): 2631 if verbose: print "Testing coercions..." 2632 class I(int): pass 2633 coerce(I(0), 0) 2634 coerce(0, I(0)) 2635 class L(long): pass 2636 coerce(L(0), 0) 2637 coerce(L(0), 0L) 2638 coerce(0, L(0)) 2639 coerce(0L, L(0)) 2640 class F(float): pass 2641 coerce(F(0), 0) 2642 coerce(F(0), 0L) 2643 coerce(F(0), 0.) 2644 coerce(0, F(0)) 2645 coerce(0L, F(0)) 2646 coerce(0., F(0)) 2647 class C(complex): pass 2648 coerce(C(0), 0) 2649 coerce(C(0), 0L) 2650 coerce(C(0), 0.) 2651 coerce(C(0), 0j) 2652 coerce(0, C(0)) 2653 coerce(0L, C(0)) 2654 coerce(0., C(0)) 2655 coerce(0j, C(0)) 2656 2657 def descrdoc(): 2658 if verbose: print "Testing descriptor doc strings..." 2659 def check(descr, what): 2660 vereq(descr.__doc__, what) 2661 check(file.closed, "True if the file is closed") # getset descriptor 2662 check(file.name, "file name") # member descriptor 2663 2664 def setclass(): 2665 if verbose: print "Testing __class__ assignment..." 2666 class C(object): pass 2667 class D(object): pass 2668 class E(object): pass 2669 class F(D, E): pass 2670 for cls in C, D, E, F: 2671 for cls2 in C, D, E, F: 2672 x = cls() 2673 x.__class__ = cls2 2674 verify(x.__class__ is cls2) 2675 x.__class__ = cls 2676 verify(x.__class__ is cls) 2677 def cant(x, C): 2678 try: 2679 x.__class__ = C 2680 except TypeError: 2681 pass 2682 else: 2683 raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C) 2684 try: 2685 delattr(x, "__class__") 2686 except TypeError: 2687 pass 2688 else: 2689 raise TestFailed, "shouldn't allow del %r.__class__" % x 2690 cant(C(), list) 2691 cant(list(), C) 2692 cant(C(), 1) 2693 cant(C(), object) 2694 cant(object(), list) 2695 cant(list(), object) 2696 class Int(int): __slots__ = [] 2697 cant(2, Int) 2698 cant(Int(), int) 2699 cant(True, int) 2700 cant(2, bool) 2701 o = object() 2702 cant(o, type(1)) 2703 cant(o, type(None)) 2704 del o 2705 2706 def setdict(): 2707 if verbose: print "Testing __dict__ assignment..." 2708 class C(object): pass 2709 a = C() 2710 a.__dict__ = {'b': 1} 2711 vereq(a.b, 1) 2712 def cant(x, dict): 2713 try: 2714 x.__dict__ = dict 2715 except TypeError: 2716 pass 2717 else: 2718 raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict) 2719 cant(a, None) 2720 cant(a, []) 2721 cant(a, 1) 2722 del a.__dict__ # Deleting __dict__ is allowed 2723 # Classes don't allow __dict__ assignment 2724 cant(C, {}) 2725 2726 def pickles(): 2727 if verbose: 2728 print "Testing pickling and copying new-style classes and objects..." 2729 import pickle, cPickle 2730 2731 def sorteditems(d): 2732 L = d.items() 2733 L.sort() 2734 return L 2735 2736 global C 2737 class C(object): 2738 def __init__(self, a, b): 2739 super(C, self).__init__() 2740 self.a = a 2741 self.b = b 2742 def __repr__(self): 2743 return "C(%r, %r)" % (self.a, self.b) 2744 2745 global C1 2746 class C1(list): 2747 def __new__(cls, a, b): 2748 return super(C1, cls).__new__(cls) 2749 def __getnewargs__(self): 2750 return (self.a, self.b) 2751 def __init__(self, a, b): 2752 self.a = a 2753 self.b = b 2754 def __repr__(self): 2755 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self)) 2756 2757 global C2 2758 class C2(int): 2759 def __new__(cls, a, b, val=0): 2760 return super(C2, cls).__new__(cls, val) 2761 def __getnewargs__(self): 2762 return (self.a, self.b, int(self)) 2763 def __init__(self, a, b, val=0): 2764 self.a = a 2765 self.b = b 2766 def __repr__(self): 2767 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self)) 2768 2769 global C3 2770 class C3(object): 2771 def __init__(self, foo): 2772 self.foo = foo 2773 def __getstate__(self): 2774 return self.foo 2775 def __setstate__(self, foo): 2776 self.foo = foo 2777 2778 global C4classic, C4 2779 class C4classic: # classic 2780 pass 2781 class C4(C4classic, object): # mixed inheritance 2782 pass 2783 2784 for p in pickle, cPickle: 2785 for bin in 0, 1: 2786 if verbose: 2787 print p.__name__, ["text", "binary"][bin] 2788 2789 for cls in C, C1, C2: 2790 s = p.dumps(cls, bin) 2791 cls2 = p.loads(s) 2792 verify(cls2 is cls) 2793 2794 a = C1(1, 2); a.append(42); a.append(24) 2795 b = C2("hello", "world", 42) 2796 s = p.dumps((a, b), bin) 2797 x, y = p.loads(s) 2798 vereq(x.__class__, a.__class__) 2799 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__)) 2800 vereq(y.__class__, b.__class__) 2801 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__)) 2802 vereq(repr(x), repr(a)) 2803 vereq(repr(y), repr(b)) 2804 if verbose: 2805 print "a = x =", a 2806 print "b = y =", b 2807 # Test for __getstate__ and __setstate__ on new style class 2808 u = C3(42) 2809 s = p.dumps(u, bin) 2810 v = p.loads(s) 2811 veris(u.__class__, v.__class__) 2812 vereq(u.foo, v.foo) 2813 # Test for picklability of hybrid class 2814 u = C4() 2815 u.foo = 42 2816 s = p.dumps(u, bin) 2817 v = p.loads(s) 2818 veris(u.__class__, v.__class__) 2819 vereq(u.foo, v.foo) 2820 2821 # Testing copy.deepcopy() 2822 if verbose: 2823 print "deepcopy" 2824 import copy 2825 for cls in C, C1, C2: 2826 cls2 = copy.deepcopy(cls) 2827 verify(cls2 is cls) 2828 2829 a = C1(1, 2); a.append(42); a.append(24) 2830 b = C2("hello", "world", 42) 2831 x, y = copy.deepcopy((a, b)) 2832 vereq(x.__class__, a.__class__) 2833 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__)) 2834 vereq(y.__class__, b.__class__) 2835 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__)) 2836 vereq(repr(x), repr(a)) 2837 vereq(repr(y), repr(b)) 2838 if verbose: 2839 print "a = x =", a 2840 print "b = y =", b 2841 2842 def pickleslots(): 2843 if verbose: print "Testing pickling of classes with __slots__ ..." 2844 import pickle, cPickle 2845 # Pickling of classes with __slots__ but without __getstate__ should fail 2846 global B, C, D, E 2847 class B(object): 2848 pass 2849 for base in [object, B]: 2850 class C(base): 2851 __slots__ = ['a'] 2852 class D(C): 2853 pass 2854 try: 2855 pickle.dumps(C()) 2856 except TypeError: 2857 pass 2858 else: 2859 raise TestFailed, "should fail: pickle C instance - %s" % base 2860 try: 2861 cPickle.dumps(C()) 2862 except TypeError: 2863 pass 2864 else: 2865 raise TestFailed, "should fail: cPickle C instance - %s" % base 2866 try: 2867 pickle.dumps(C()) 2868 except TypeError: 2869 pass 2870 else: 2871 raise TestFailed, "should fail: pickle D instance - %s" % base 2872 try: 2873 cPickle.dumps(D()) 2874 except TypeError: 2875 pass 2876 else: 2877 raise TestFailed, "should fail: cPickle D instance - %s" % base 2878 # Give C a nice generic __getstate__ and __setstate__ 2879 class C(base): 2880 __slots__ = ['a'] 2881 def __getstate__(self): 2882 try: 2883 d = self.__dict__.copy() 2884 except AttributeError: 2885 d = {} 2886 for cls in self.__class__.__mro__: 2887 for sn in cls.__dict__.get('__slots__', ()): 2888 try: 2889 d[sn] = getattr(self, sn) 2890 except AttributeError: 2891 pass 2892 return d 2893 def __setstate__(self, d): 2894 for k, v in d.items(): 2895 setattr(self, k, v) 2896 class D(C): 2897 pass 2898 # Now it should work 2899 x = C() 2900 y = pickle.loads(pickle.dumps(x)) 2901 vereq(hasattr(y, 'a'), 0) 2902 y = cPickle.loads(cPickle.dumps(x)) 2903 vereq(hasattr(y, 'a'), 0) 2904 x.a = 42 2905 y = pickle.loads(pickle.dumps(x)) 2906 vereq(y.a, 42) 2907 y = cPickle.loads(cPickle.dumps(x)) 2908 vereq(y.a, 42) 2909 x = D() 2910 x.a = 42 2911 x.b = 100 2912 y = pickle.loads(pickle.dumps(x)) 2913 vereq(y.a + y.b, 142) 2914 y = cPickle.loads(cPickle.dumps(x)) 2915 vereq(y.a + y.b, 142) 2916 # A subclass that adds a slot should also work 2917 class E(C): 2918 __slots__ = ['b'] 2919 x = E() 2920 x.a = 42 2921 x.b = "foo" 2922 y = pickle.loads(pickle.dumps(x)) 2923 vereq(y.a, x.a) 2924 vereq(y.b, x.b) 2925 y = cPickle.loads(cPickle.dumps(x)) 2926 vereq(y.a, x.a) 2927 vereq(y.b, x.b) 2928 2929 def copies(): 2930 if verbose: print "Testing copy.copy() and copy.deepcopy()..." 2931 import copy 2932 class C(object): 2933 pass 2934 2935 a = C() 2936 a.foo = 12 2937 b = copy.copy(a) 2938 vereq(b.__dict__, a.__dict__) 2939 2940 a.bar = [1,2,3] 2941 c = copy.copy(a) 2942 vereq(c.bar, a.bar) 2943 verify(c.bar is a.bar) 2944 2945 d = copy.deepcopy(a) 2946 vereq(d.__dict__, a.__dict__) 2947 a.bar.append(4) 2948 vereq(d.bar, [1,2,3]) 2949 2950 def binopoverride(): 2951 if verbose: print "Testing overrides of binary operations..." 2952 class I(int): 2953 def __repr__(self): 2954 return "I(%r)" % int(self) 2955 def __add__(self, other): 2956 return I(int(self) + int(other)) 2957 __radd__ = __add__ 2958 def __pow__(self, other, mod=None): 2959 if mod is None: 2960 return I(pow(int(self), int(other))) 2961 else: 2962 return I(pow(int(self), int(other), int(mod))) 2963 def __rpow__(self, other, mod=None): 2964 if mod is None: 2965 return I(pow(int(other), int(self), mod)) 2966 else: 2967 return I(pow(int(other), int(self), int(mod))) 2968 2969 vereq(repr(I(1) + I(2)), "I(3)") 2970 vereq(repr(I(1) + 2), "I(3)") 2971 vereq(repr(1 + I(2)), "I(3)") 2972 vereq(repr(I(2) ** I(3)), "I(8)") 2973 vereq(repr(2 ** I(3)), "I(8)") 2974 vereq(repr(I(2) ** 3), "I(8)") 2975 vereq(repr(pow(I(2), I(3), I(5))), "I(3)") 2976 class S(str): 2977 def __eq__(self, other): 2978 return self.lower() == other.lower() 2979 2980 def subclasspropagation(): 2981 if verbose: print "Testing propagation of slot functions to subclasses..." 2982 class A(object): 2983 pass 2984 class B(A): 2985 pass 2986 class C(A): 2987 pass 2988 class D(B, C): 2989 pass 2990 d = D() 2991 vereq(hash(d), id(d)) 2992 A.__hash__ = lambda self: 42 2993 vereq(hash(d), 42) 2994 C.__hash__ = lambda self: 314 2995 vereq(hash(d), 314) 2996 B.__hash__ = lambda self: 144 2997 vereq(hash(d), 144) 2998 D.__hash__ = lambda self: 100 2999 vereq(hash(d), 100) 3000 del D.__hash__ 3001 vereq(hash(d), 144) 3002 del B.__hash__ 3003 vereq(hash(d), 314) 3004 del C.__hash__ 3005 vereq(hash(d), 42) 3006 del A.__hash__ 3007 vereq(hash(d), id(d)) 3008 d.foo = 42 3009 d.bar = 42 3010 vereq(d.foo, 42) 3011 vereq(d.bar, 42) 3012 def __getattribute__(self, name): 3013 if name == "foo": 3014 return 24 3015 return object.__getattribute__(self, name) 3016 A.__getattribute__ = __getattribute__ 3017 vereq(d.foo, 24) 3018 vereq(d.bar, 42) 3019 def __getattr__(self, name): 3020 if name in ("spam", "foo", "bar"): 3021 return "hello" 3022 raise AttributeError, name 3023 B.__getattr__ = __getattr__ 3024 vereq(d.spam, "hello") 3025 vereq(d.foo, 24) 3026 vereq(d.bar, 42) 3027 del A.__getattribute__ 3028 vereq(d.foo, 42) 3029 del d.foo 3030 vereq(d.foo, "hello") 3031 vereq(d.bar, 42) 3032 del B.__getattr__ 3033 try: 3034 d.foo 3035 except AttributeError: 3036 pass 3037 else: 3038 raise TestFailed, "d.foo should be undefined now" 3039 3040 # Test a nasty bug in recurse_down_subclasses() 3041 import gc 3042 class A(object): 3043 pass 3044 class B(A): 3045 pass 3046 del B 3047 gc.collect() 3048 A.__setitem__ = lambda *a: None # crash 3049 3050 def buffer_inherit(): 3051 import binascii 3052 # SF bug [#470040] ParseTuple t# vs subclasses. 3053 if verbose: 3054 print "Testing that buffer interface is inherited ..." 3055 3056 class MyStr(str): 3057 pass 3058 base = 'abc' 3059 m = MyStr(base) 3060 # b2a_hex uses the buffer interface to get its argument's value, via 3061 # PyArg_ParseTuple 't#' code. 3062 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base)) 3063 3064 # It's not clear that unicode will continue to support the character 3065 # buffer interface, and this test will fail if that's taken away. 3066 class MyUni(unicode): 3067 pass 3068 base = u'abc' 3069 m = MyUni(base) 3070 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base)) 3071 3072 class MyInt(int): 3073 pass 3074 m = MyInt(42) 3075 try: 3076 binascii.b2a_hex(m) 3077 raise TestFailed('subclass of int should not have a buffer interface') 3078 except TypeError: 3079 pass 3080 3081 def str_of_str_subclass(): 3082 import binascii 3083 import cStringIO 3084 3085 if verbose: 3086 print "Testing __str__ defined in subclass of str ..." 3087 3088 class octetstring(str): 3089 def __str__(self): 3090 return binascii.b2a_hex(self) 3091 def __repr__(self): 3092 return self + " repr" 3093 3094 o = octetstring('A') 3095 vereq(type(o), octetstring) 3096 vereq(type(str(o)), str) 3097 vereq(type(repr(o)), str) 3098 vereq(ord(o), 0x41) 3099 vereq(str(o), '41') 3100 vereq(repr(o), 'A repr') 3101 vereq(o.__str__(), '41') 3102 vereq(o.__repr__(), 'A repr') 3103 3104 capture = cStringIO.StringIO() 3105 # Calling str() or not exercises different internal paths. 3106 print >> capture, o 3107 print >> capture, str(o) 3108 vereq(capture.getvalue(), '41\n41\n') 3109 capture.close() 3110 3111 def kwdargs(): 3112 if verbose: print "Testing keyword arguments to __init__, __call__..." 3113 def f(a): return a 3114 vereq(f.__call__(a=42), 42) 3115 a = [] 3116 list.__init__(a, sequence=[0, 1, 2]) 3117 vereq(a, [0, 1, 2]) 3118 3119 def delhook(): 3120 if verbose: print "Testing __del__ hook..." 3121 log = [] 3122 class C(object): 3123 def __del__(self): 3124 log.append(1) 3125 c = C() 3126 vereq(log, []) 3127 del c 3128 vereq(log, [1]) 3129 3130 class D(object): pass 3131 d = D() 3132 try: del d[0] 3133 except TypeError: pass 3134 else: raise TestFailed, "invalid del() didn't raise TypeError" 3135 3136 def hashinherit(): 3137 if verbose: print "Testing hash of mutable subclasses..." 3138 3139 class mydict(dict): 3140 pass 3141 d = mydict() 3142 try: 3143 hash(d) 3144 except TypeError: 3145 pass 3146 else: 3147 raise TestFailed, "hash() of dict subclass should fail" 3148 3149 class mylist(list): 3150 pass 3151 d = mylist() 3152 try: 3153 hash(d) 3154 except TypeError: 3155 pass 3156 else: 3157 raise TestFailed, "hash() of list subclass should fail" 3158 3159 def strops(): 3160 try: 'a' + 5 3161 except TypeError: pass 3162 else: raise TestFailed, "'' + 5 doesn't raise TypeError" 3163 3164 try: ''.split('') 3165 except ValueError: pass 3166 else: raise TestFailed, "''.split('') doesn't raise ValueError" 3167 3168 try: ''.join([0]) 3169 except TypeError: pass 3170 else: raise TestFailed, "''.join([0]) doesn't raise TypeError" 3171 3172 try: ''.rindex('5') 3173 except ValueError: pass 3174 else: raise TestFailed, "''.rindex('5') doesn't raise ValueError" 3175 3176 try: '%(n)s' % None 3177 except TypeError: pass 3178 else: raise TestFailed, "'%(n)s' % None doesn't raise TypeError" 3179 3180 try: '%(n' % {} 3181 except ValueError: pass 3182 else: raise TestFailed, "'%(n' % {} '' doesn't raise ValueError" 3183 3184 try: '%*s' % ('abc') 3185 except TypeError: pass 3186 else: raise TestFailed, "'%*s' % ('abc') doesn't raise TypeError" 3187 3188 try: '%*.*s' % ('abc', 5) 3189 except TypeError: pass 3190 else: raise TestFailed, "'%*.*s' % ('abc', 5) doesn't raise TypeError" 3191 3192 try: '%s' % (1, 2) 3193 except TypeError: pass 3194 else: raise TestFailed, "'%s' % (1, 2) doesn't raise TypeError" 3195 3196 try: '%' % None 3197 except ValueError: pass 3198 else: raise TestFailed, "'%' % None doesn't raise ValueError" 3199 3200 vereq('534253'.isdigit(), 1) 3201 vereq('534253x'.isdigit(), 0) 3202 vereq('%c' % 5, '\x05') 3203 vereq('%c' % '5', '5') 3204 3205 def deepcopyrecursive(): 3206 if verbose: print "Testing deepcopy of recursive objects..." 3207 class Node: 3208 pass 3209 a = Node() 3210 b = Node() 3211 a.b = b 3212 b.a = a 3213 z = deepcopy(a) # This blew up before 3214 3215 def modules(): 3216 if verbose: print "Testing uninitialized module objects..." 3217 from types import ModuleType as M 3218 m = M.__new__(M) 3219 str(m) 3220 vereq(hasattr(m, "__name__"), 0) 3221 vereq(hasattr(m, "__file__"), 0) 3222 vereq(hasattr(m, "foo"), 0) 3223 vereq(m.__dict__, None) 3224 m.foo = 1 3225 vereq(m.__dict__, {"foo": 1}) 3226 3227 def dictproxyiterkeys(): 3228 class C(object): 3229 def meth(self): 3230 pass 3231 if verbose: print "Testing dict-proxy iterkeys..." 3232 keys = [ key for key in C.__dict__.iterkeys() ] 3233 keys.sort() 3234 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth']) 3235 3236 def dictproxyitervalues(): 3237 class C(object): 3238 def meth(self): 3239 pass 3240 if verbose: print "Testing dict-proxy itervalues..." 3241 values = [ values for values in C.__dict__.itervalues() ] 3242 vereq(len(values), 5) 3243 3244 def dictproxyiteritems(): 3245 class C(object): 3246 def meth(self): 3247 pass 3248 if verbose: print "Testing dict-proxy iteritems..." 3249 keys = [ key for (key, value) in C.__dict__.iteritems() ] 3250 keys.sort() 3251 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth']) 3252 3253 def funnynew(): 3254 if verbose: print "Testing __new__ returning something unexpected..." 3255 class C(object): 3256 def __new__(cls, arg): 3257 if isinstance(arg, str): return [1, 2, 3] 3258 elif isinstance(arg, int): return object.__new__(D) 3259 else: return object.__new__(cls) 3260 class D(C): 3261 def __init__(self, arg): 3262 self.foo = arg 3263 vereq(C("1"), [1, 2, 3]) 3264 vereq(D("1"), [1, 2, 3]) 3265 d = D(None) 3266 veris(d.foo, None) 3267 d = C(1) 3268 vereq(isinstance(d, D), True) 3269 vereq(d.foo, 1) 3270 d = D(1) 3271 vereq(isinstance(d, D), True) 3272 vereq(d.foo, 1) 3273 3274 def imulbug(): 3275 # SF bug 544647 3276 if verbose: print "Testing for __imul__ problems..." 3277 class C(object): 3278 def __imul__(self, other): 3279 return (self, other) 3280 x = C() 3281 y = x 3282 y *= 1.0 3283 vereq(y, (x, 1.0)) 3284 y = x 3285 y *= 2 3286 vereq(y, (x, 2)) 3287 y = x 3288 y *= 3L 3289 vereq(y, (x, 3L)) 3290 y = x 3291 y *= 1L<<100 3292 vereq(y, (x, 1L<<100)) 3293 y = x 3294 y *= None 3295 vereq(y, (x, None)) 3296 y = x 3297 y *= "foo" 3298 vereq(y, (x, "foo")) 3299 3300 def docdescriptor(): 3301 # SF bug 542984 3302 if verbose: print "Testing __doc__ descriptor..." 3303 class DocDescr(object): 3304 def __get__(self, object, otype): 3305 if object: 3306 object = object.__class__.__name__ + ' instance' 3307 if otype: 3308 otype = otype.__name__ 3309 return 'object=%s; type=%s' % (object, otype) 3310 class OldClass: 3311 __doc__ = DocDescr() 3312 class NewClass(object): 3313 __doc__ = DocDescr() 3314 vereq(OldClass.__doc__, 'object=None; type=OldClass') 3315 vereq(OldClass().__doc__, 'object=OldClass instance; type=OldClass') 3316 vereq(NewClass.__doc__, 'object=None; type=NewClass') 3317 vereq(NewClass().__doc__, 'object=NewClass instance; type=NewClass') 3318 3319 def string_exceptions(): 3320 if verbose: 3321 print "Testing string exceptions ..." 3322 3323 # Ensure builtin strings work OK as exceptions. 3324 astring = "An exception string." 3325 try: 3326 raise astring 3327 except astring: 3328 pass 3329 else: 3330 raise TestFailed, "builtin string not usable as exception" 3331 3332 # Ensure string subclass instances do not. 3333 class MyStr(str): 3334 pass 3335 3336 newstring = MyStr("oops -- shouldn't work") 3337 try: 3338 raise newstring 3339 except TypeError: 3340 pass 3341 except: 3342 raise TestFailed, "string subclass allowed as exception" 3343 3344 def copy_setstate(): 3345 if verbose: 3346 print "Testing that copy.*copy() correctly uses __setstate__..." 3347 import copy 3348 class C(object): 3349 def __init__(self, foo=None): 3350 self.foo = foo 3351 self.__foo = foo 3352 def setfoo(self, foo=None): 3353 self.foo = foo 3354 def getfoo(self): 3355 return self.__foo 3356 def __getstate__(self): 3357 return [self.foo] 3358 def __setstate__(self, lst): 3359 assert len(lst) == 1 3360 self.__foo = self.foo = lst[0] 3361 a = C(42) 3362 a.setfoo(24) 3363 vereq(a.foo, 24) 3364 vereq(a.getfoo(), 42) 3365 b = copy.copy(a) 3366 vereq(b.foo, 24) 3367 vereq(b.getfoo(), 24) 3368 b = copy.deepcopy(a) 3369 vereq(b.foo, 24) 3370 vereq(b.getfoo(), 24) 3371 3372 def slices(): 3373 if verbose: 3374 print "Testing cases with slices and overridden __getitem__ ..." 3375 # Strings 3376 vereq("hello"[:4], "hell") 3377 vereq("hello"[slice(4)], "hell") 3378 vereq(str.__getitem__("hello", slice(4)), "hell") 3379 class S(str): 3380 def __getitem__(self, x): 3381 return str.__getitem__(self, x) 3382 vereq(S("hello")[:4], "hell") 3383 vereq(S("hello")[slice(4)], "hell") 3384 vereq(S("hello").__getitem__(slice(4)), "hell") 3385 # Tuples 3386 vereq((1,2,3)[:2], (1,2)) 3387 vereq((1,2,3)[slice(2)], (1,2)) 3388 vereq(tuple.__getitem__((1,2,3), slice(2)), (1,2)) 3389 class T(tuple): 3390 def __getitem__(self, x): 3391 return tuple.__getitem__(self, x) 3392 vereq(T((1,2,3))[:2], (1,2)) 3393 vereq(T((1,2,3))[slice(2)], (1,2)) 3394 vereq(T((1,2,3)).__getitem__(slice(2)), (1,2)) 3395 # Lists 3396 vereq([1,2,3][:2], [1,2]) 3397 vereq([1,2,3][slice(2)], [1,2]) 3398 vereq(list.__getitem__([1,2,3], slice(2)), [1,2]) 3399 class L(list): 3400 def __getitem__(self, x): 3401 return list.__getitem__(self, x) 3402 vereq(L([1,2,3])[:2], [1,2]) 3403 vereq(L([1,2,3])[slice(2)], [1,2]) 3404 vereq(L([1,2,3]).__getitem__(slice(2)), [1,2]) 3405 # Now do lists and __setitem__ 3406 a = L([1,2,3]) 3407 a[slice(1, 3)] = [3,2] 3408 vereq(a, [1,3,2]) 3409 a[slice(0, 2, 1)] = [3,1] 3410 vereq(a, [3,1,2]) 3411 a.__setitem__(slice(1, 3), [2,1]) 3412 vereq(a, [3,2,1]) 3413 a.__setitem__(slice(0, 2, 1), [2,3]) 3414 vereq(a, [2,3,1]) 3415 3416 def subtype_resurrection(): 3417 if verbose: 3418 print "Testing resurrection of new-style instance..." 3419 3420 class C(object): 3421 container = [] 3422 3423 def __del__(self): 3424 # resurrect the instance 3425 C.container.append(self) 3426 3427 c = C() 3428 c.attr = 42 3429 # The most interesting thing here is whether this blows up, due to flawed 3430 # GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 bug). 3431 del c 3432 3433 # If that didn't blow up, it's also interesting to see whether clearing 3434 # the last container slot works: that will attempt to delete c again, 3435 # which will cause c to get appended back to the container again "during" 3436 # the del. 3437 del C.container[-1] 3438 vereq(len(C.container), 1) 3439 vereq(C.container[-1].attr, 42) 3440 3441 # Make c mortal again, so that the test framework with -l doesn't report 3442 # it as a leak. 3443 del C.__del__ 3444 3445 def slottrash(): 3446 # Deallocating deeply nested slotted trash caused stack overflows 3447 if verbose: 3448 print "Testing slot trash..." 3449 class trash(object): 3450 __slots__ = ['x'] 3451 def __init__(self, x): 3452 self.x = x 3453 o = None 3454 for i in xrange(50000): 3455 o = trash(o) 3456 del o 3457 3458 def slotmultipleinheritance(): 3459 # SF bug 575229, multiple inheritance w/ slots dumps core 3460 class A(object): 3461 __slots__=() 3462 class B(object): 3463 pass 3464 class C(A,B) : 3465 __slots__=() 3466 vereq(C.__basicsize__, B.__basicsize__) 3467 verify(hasattr(C, '__dict__')) 3468 verify(hasattr(C, '__weakref__')) 3469 C().x = 2 3470 3471 def testrmul(): 3472 # SF patch 592646 3473 if verbose: 3474 print "Testing correct invocation of __rmul__..." 3475 class C(object): 3476 def __mul__(self, other): 3477 return "mul" 3478 def __rmul__(self, other): 3479 return "rmul" 3480 a = C() 3481 vereq(a*2, "mul") 3482 vereq(a*2.2, "mul") 3483 vereq(2*a, "rmul") 3484 vereq(2.2*a, "rmul") 3485 3486 def testipow(): 3487 # [SF bug 620179] 3488 if verbose: 3489 print "Testing correct invocation of __ipow__..." 3490 class C(object): 3491 def __ipow__(self, other): 3492 pass 3493 a = C() 3494 a **= 2 3495 3496 def do_this_first(): 3497 if verbose: 3498 print "Testing SF bug 551412 ..." 3499 # This dumps core when SF bug 551412 isn't fixed -- 3500 # but only when test_descr.py is run separately. 3501 # (That can't be helped -- as soon as PyType_Ready() 3502 # is called for PyLong_Type, the bug is gone.) 3503 class UserLong(object): 3504 def __pow__(self, *args): 3505 pass 3506 try: 3507 pow(0L, UserLong(), 0L) 3508 except: 3509 pass 3510 3511 if verbose: 3512 print "Testing SF bug 570483..." 3513 # Another segfault only when run early 3514 # (before PyType_Ready(tuple) is called) 3515 type.mro(tuple) 3516 3517 def test_mutable_bases(): 3518 if verbose: 3519 print "Testing mutable bases..." 3520 # stuff that should work: 3521 class C(object): 3522 pass 3523 class C2(object): 3524 def __getattribute__(self, attr): 3525 if attr == 'a': 3526 return 2 3527 else: 3528 return super(C2, self).__getattribute__(attr) 3529 def meth(self): 3530 return 1 3531 class D(C): 3532 pass 3533 class E(D): 3534 pass 3535 d = D() 3536 e = E() 3537 D.__bases__ = (C,) 3538 D.__bases__ = (C2,) 3539 vereq(d.meth(), 1) 3540 vereq(e.meth(), 1) 3541 vereq(d.a, 2) 3542 vereq(e.a, 2) 3543 vereq(C2.__subclasses__(), [D]) 3544 3545 # stuff that shouldn't: 3546 class L(list): 3547 pass 3548 3549 try: 3550 L.__bases__ = (dict,) 3551 except TypeError: 3552 pass 3553 else: 3554 raise TestFailed, "shouldn't turn list subclass into dict subclass" 3555 3556 try: 3557 list.__bases__ = (dict,) 3558 except TypeError: 3559 pass 3560 else: 3561 raise TestFailed, "shouldn't be able to assign to list.__bases__" 3562 3563 try: 3564 del D.__bases__ 3565 except TypeError: 3566 pass 3567 else: 3568 raise TestFailed, "shouldn't be able to delete .__bases__" 3569 3570 try: 3571 D.__bases__ = () 3572 except TypeError, msg: 3573 if str(msg) == "a new-style class can't have only classic bases": 3574 raise TestFailed, "wrong error message for .__bases__ = ()" 3575 else: 3576 raise TestFailed, "shouldn't be able to set .__bases__ to ()" 3577 3578 try: 3579 D.__bases__ = (D,) 3580 except TypeError: 3581 pass 3582 else: 3583 # actually, we'll have crashed by here... 3584 raise TestFailed, "shouldn't be able to create inheritance cycles" 3585 3586 try: 3587 D.__bases__ = (C, C) 3588 except TypeError: 3589 pass 3590 else: 3591 raise TestFailed, "didn't detect repeated base classes" 3592 3593 try: 3594 D.__bases__ = (E,) 3595 except TypeError: 3596 pass 3597 else: 3598 raise TestFailed, "shouldn't be able to create inheritance cycles" 3599 3600 # let's throw a classic class into the mix: 3601 class Classic: 3602 def meth2(self): 3603 return 3 3604 3605 D.__bases__ = (C, Classic) 3606 3607 vereq(d.meth2(), 3) 3608 vereq(e.meth2(), 3) 3609 try: 3610 d.a 3611 except AttributeError: 3612 pass 3613 else: 3614 raise TestFailed, "attribute should have vanished" 3615 3616 try: 3617 D.__bases__ = (Classic,) 3618 except TypeError: 3619 pass 3620 else: 3621 raise TestFailed, "new-style class must have a new-style base" 3622 3623 def test_mutable_bases_with_failing_mro(): 3624 if verbose: 3625 print "Testing mutable bases with failing mro..." 3626 class WorkOnce(type): 3627 def __new__(self, name, bases, ns): 3628 self.flag = 0 3629 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns) 3630 def mro(self): 3631 if self.flag > 0: 3632 raise RuntimeError, "bozo" 3633 else: 3634 self.flag += 1 3635 return type.mro(self) 3636 3637 class WorkAlways(type): 3638 def mro(self): 3639 # this is here to make sure that .mro()s aren't called 3640 # with an exception set (which was possible at one point). 3641 # An error message will be printed in a debug build. 3642 # What's a good way to test for this? 3643 return type.mro(self) 3644 3645 class C(object): 3646 pass 3647 3648 class C2(object): 3649 pass 3650 3651 class D(C): 3652 pass 3653 3654 class E(D): 3655 pass 3656 3657 class F(D): 3658 __metaclass__ = WorkOnce 3659 3660 class G(D): 3661 __metaclass__ = WorkAlways 3662 3663 # Immediate subclasses have their mro's adjusted in alphabetical 3664 # order, so E's will get adjusted before adjusting F's fails. We 3665 # check here that E's gets restored. 3666 3667 E_mro_before = E.__mro__ 3668 D_mro_before = D.__mro__ 3669 3670 try: 3671 D.__bases__ = (C2,) 3672 except RuntimeError: 3673 vereq(E.__mro__, E_mro_before) 3674 vereq(D.__mro__, D_mro_before) 3675 else: 3676 raise TestFailed, "exception not propagated" 3677 3678 def test_mutable_bases_catch_mro_conflict(): 3679 if verbose: 3680 print "Testing mutable bases catch mro conflict..." 3681 class A(object): 3682 pass 3683 3684 class B(object): 3685 pass 3686 3687 class C(A, B): 3688 pass 3689 3690 class D(A, B): 3691 pass 3692 3693 class E(C, D): 3694 pass 3695 3696 try: 3697 C.__bases__ = (B, A) 3698 except TypeError: 3699 pass 3700 else: 3701 raise TestFailed, "didn't catch MRO conflict" 3702 3703 def mutable_names(): 3704 if verbose: 3705 print "Testing mutable names..." 3706 class C(object): 3707 pass 3708 3709 # C.__module__ could be 'test_descr' or '__main__' 3710 mod = C.__module__ 3711 3712 C.__name__ = 'D' 3713 vereq((C.__module__, C.__name__), (mod, 'D')) 3714 3715 C.__name__ = 'D.E' 3716 vereq((C.__module__, C.__name__), (mod, 'D.E')) 3717 3718 def subclass_right_op(): 3719 if verbose: 3720 print "Testing correct dispatch of subclass overloading __r<op>__..." 3721 3722 # This code tests various cases where right-dispatch of a subclass 3723 # should be preferred over left-dispatch of a base class. 3724 3725 # Case 1: subclass of int; this tests code in abstract.c::binary_op1() 3726 3727 class B(int): 3728 def __floordiv__(self, other): 3729 return "B.__floordiv__" 3730 def __rfloordiv__(self, other): 3731 return "B.__rfloordiv__" 3732 3733 vereq(B(1) // 1, "B.__floordiv__") 3734 vereq(1 // B(1), "B.__rfloordiv__") 3735 3736 # Case 2: subclass of object; this is just the baseline for case 3 3737 3738 class C(object): 3739 def __floordiv__(self, other): 3740 return "C.__floordiv__" 3741 def __rfloordiv__(self, other): 3742 return "C.__rfloordiv__" 3743 3744 vereq(C() // 1, "C.__floordiv__") 3745 vereq(1 // C(), "C.__rfloordiv__") 3746 3747 # Case 3: subclass of new-style class; here it gets interesting 3748 3749 class D(C): 3750 def __floordiv__(self, other): 3751 return "D.__floordiv__" 3752 def __rfloordiv__(self, other): 3753 return "D.__rfloordiv__" 3754 3755 vereq(D() // C(), "D.__floordiv__") 3756 vereq(C() // D(), "D.__rfloordiv__") 3757 3758 # Case 4: this didn't work right in 2.2.2 and 2.3a1 3759 3760 class E(C): 3761 pass 3762 3763 vereq(E.__rfloordiv__, C.__rfloordiv__) 3764 3765 vereq(E() // 1, "C.__floordiv__") 3766 vereq(1 // E(), "C.__rfloordiv__") 3767 vereq(E() // C(), "C.__floordiv__") 3768 vereq(C() // E(), "C.__floordiv__") # This one would fail 3769 3770 def dict_type_with_metaclass(): 3771 if verbose: 3772 print "Testing type of __dict__ when __metaclass__ set..." 3773 3774 class B(object): 3775 pass 3776 class M(type): 3777 pass 3778 class C: 3779 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy 3780 __metaclass__ = M 3781 veris(type(C.__dict__), type(B.__dict__)) 3782 3783 def meth_class_get(): 3784 # Full coverage of descrobject.c::classmethod_get() 3785 if verbose: 3786 print "Testing __get__ method of METH_CLASS C methods..." 3787 # Baseline 3788 arg = [1, 2, 3] 3789 res = {1: None, 2: None, 3: None} 3790 vereq(dict.fromkeys(arg), res) 3791 vereq({}.fromkeys(arg), res) 3792 # Now get the descriptor 3793 descr = dict.__dict__["fromkeys"] 3794 # More baseline using the descriptor directly 3795 vereq(descr.__get__(None, dict)(arg), res) 3796 vereq(descr.__get__({})(arg), res) 3797 # Now check various error cases 3798 try: 3799 descr.__get__(None, None) 3800 except TypeError: 3801 pass 3802 else: 3803 raise TestFailed, "shouldn't have allowed descr.__get__(None, None)" 3804 try: 3805 descr.__get__(42) 3806 except TypeError: 3807 pass 3808 else: 3809 raise TestFailed, "shouldn't have allowed descr.__get__(42)" 3810 try: 3811 descr.__get__(None, 42) 3812 except TypeError: 3813 pass 3814 else: 3815 raise TestFailed, "shouldn't have allowed descr.__get__(None, 42)" 3816 try: 3817 descr.__get__(None, int) 3818 except TypeError: 3819 pass 3820 else: 3821 raise TestFailed, "shouldn't have allowed descr.__get__(None, int)" 3822 3823 def isinst_isclass(): 3824 if verbose: 3825 print "Testing proxy isinstance() and isclass()..." 3826 class Proxy(object): 3827 def __init__(self, obj): 3828 self.__obj = obj 3829 def __getattribute__(self, name): 3830 if name.startswith("_Proxy__"): 3831 return object.__getattribute__(self, name) 3832 else: 3833 return getattr(self.__obj, name) 3834 # Test with a classic class 3835 class C: 3836 pass 3837 a = C() 3838 pa = Proxy(a) 3839 verify(isinstance(a, C)) # Baseline 3840 verify(isinstance(pa, C)) # Test 3841 # Test with a classic subclass 3842 class D(C): 3843 pass 3844 a = D() 3845 pa = Proxy(a) 3846 verify(isinstance(a, C)) # Baseline 3847 verify(isinstance(pa, C)) # Test 3848 # Test with a new-style class 3849 class C(object): 3850 pass 3851 a = C() 3852 pa = Proxy(a) 3853 verify(isinstance(a, C)) # Baseline 3854 verify(isinstance(pa, C)) # Test 3855 # Test with a new-style subclass 3856 class D(C): 3857 pass 3858 a = D() 3859 pa = Proxy(a) 3860 verify(isinstance(a, C)) # Baseline 3861 verify(isinstance(pa, C)) # Test 3862 3863 def proxysuper(): 3864 if verbose: 3865 print "Testing super() for a proxy object..." 3866 class Proxy(object): 3867 def __init__(self, obj): 3868 self.__obj = obj 3869 def __getattribute__(self, name): 3870 if name.startswith("_Proxy__"): 3871 return object.__getattribute__(self, name) 3872 else: 3873 return getattr(self.__obj, name) 3874 3875 class B(object): 3876 def f(self): 3877 return "B.f" 3878 3879 class C(B): 3880 def f(self): 3881 return super(C, self).f() + "->C.f" 3882 3883 obj = C() 3884 p = Proxy(obj) 3885 vereq(C.__dict__["f"](p), "B.f->C.f") 3886 3887 def carloverre(): 3888 if verbose: 3889 print "Testing prohibition of Carlo Verre's hack..." 3890 try: 3891 object.__setattr__(str, "foo", 42) 3892 except TypeError: 3893 pass 3894 else: 3895 raise TestFailed, "Carlo Verre __setattr__ suceeded!" 3896 try: 3897 object.__delattr__(str, "lower") 3898 except TypeError: 3899 pass 3900 else: 3901 raise TestFailed, "Carlo Verre __delattr__ succeeded!" 3902 3903 def weakref_segfault(): 3904 # SF 742911 3905 if verbose: 3906 print "Testing weakref segfault..." 3907 3908 import weakref 3909 3910 class Provoker: 3911 def __init__(self, referrent): 3912 self.ref = weakref.ref(referrent) 3913 3914 def __del__(self): 3915 x = self.ref() 3916 3917 class Oops(object): 3918 pass 3919 3920 o = Oops() 3921 o.whatever = Provoker(o) 3922 del o 3923 3924 # Fix SF #762455, segfault when sys.stdout is changed in getattr 3925 def filefault(): 3926 if verbose: 3927 print "Testing sys.stdout is changed in getattr..." 3928 import sys 3929 class StdoutGuard: 3930 def __getattr__(self, attr): 3931 sys.stdout = sys.__stdout__ 3932 raise RuntimeError("Premature access to sys.stdout.%s" % attr) 3933 sys.stdout = StdoutGuard() 3934 try: 3935 print "Oops!" 3936 except RuntimeError: 3937 pass 3938 3939 def vicious_descriptor_nonsense(): 3940 # A potential segfault spotted by Thomas Wouters in mail to 3941 # python-dev 2003-04-17, turned into an example & fixed by Michael 3942 # Hudson just less than four months later... 3943 if verbose: 3944 print "Testing vicious_descriptor_nonsense..." 3945 3946 class Evil(object): 3947 def __hash__(self): 3948 return hash('attr') 3949 def __eq__(self, other): 3950 del C.attr 3951 return 0 3952 3953 class Descr(object): 3954 def __get__(self, ob, type=None): 3955 return 1 3956 3957 class C(object): 3958 attr = Descr() 3959 3960 c = C() 3961 c.__dict__[Evil()] = 0 3962 3963 vereq(c.attr, 1) 3964 # this makes a crash more likely: 3965 import gc; gc.collect() 3966 vereq(hasattr(c, 'attr'), False) 3967 3968 3969 def test_main(): 3970 weakref_segfault() # Must be first, somehow 3971 do_this_first() 3972 class_docstrings() 3973 lists() 3974 dicts() 3975 dict_constructor() 3976 test_dir() 3977 ints() 3978 longs() 3979 floats() 3980 complexes() 3981 spamlists() 3982 spamdicts() 3983 pydicts() 3984 pylists() 3985 metaclass() 3986 pymods() 3987 multi() 3988 mro_disagreement() 3989 diamond() 3990 ex5() 3991 monotonicity() 3992 consistency_with_epg() 3993 objects() 3994 slots() 3995 slotspecials() 3996 dynamics() 3997 errors() 3998 classmethods() 3999 classmethods_in_c() 4000 staticmethods() 4001 staticmethods_in_c() 4002 classic() 4003 compattr() 4004 newslot() 4005 altmro() 4006 overloading() 4007 methods() 4008 specials() 4009 weakrefs() 4010 properties() 4011 supers() 4012 inherits() 4013 keywords() 4014 restricted() 4015 str_subclass_as_dict_key() 4016 classic_comparisons() 4017 rich_comparisons() 4018 coercions() 4019 descrdoc() 4020 setclass() 4021 setdict() 4022 pickles() 4023 copies() 4024 binopoverride() 4025 subclasspropagation() 4026 buffer_inherit() 4027 str_of_str_subclass() 4028 kwdargs() 4029 delhook() 4030 hashinherit() 4031 strops() 4032 deepcopyrecursive() 4033 modules() 4034 dictproxyiterkeys() 4035 dictproxyitervalues() 4036 dictproxyiteritems() 4037 pickleslots() 4038 funnynew() 4039 imulbug() 4040 docdescriptor() 4041 string_exceptions() 4042 copy_setstate() 4043 slices() 4044 subtype_resurrection() 4045 slottrash() 4046 slotmultipleinheritance() 4047 testrmul() 4048 testipow() 4049 test_mutable_bases() 4050 test_mutable_bases_with_failing_mro() 4051 test_mutable_bases_catch_mro_conflict() 4052 mutable_names() 4053 subclass_right_op() 4054 dict_type_with_metaclass() 4055 meth_class_get() 4056 isinst_isclass() 4057 proxysuper() 4058 carloverre() 4059 filefault() 4060 vicious_descriptor_nonsense() 4061 4062 if verbose: print "All OK" 4063 4064 if __name__ == "__main__": 4065 test_main() 4066
Generated by PyXR 0.9.4