Exceptions raised during renaming in rotating file handlers are now passed to handleE...
[python.git] / Lib / test / test_descr.py
blobd6127662e2fd459b05cffdca62eb02bf9fc85ed2
1 # Test enhancements related to descriptors and new-style classes
3 from test.test_support import verify, vereq, verbose, TestFailed, TESTFN, get_original_stdout
4 from copy import deepcopy
5 import warnings
7 warnings.filterwarnings("ignore",
8 r'complex divmod\(\), // and % are deprecated$',
9 DeprecationWarning, r'(<string>|%s)$' % __name__)
11 def veris(a, b):
12 if a is not b:
13 raise TestFailed, "%r is %r" % (a, b)
15 def testunop(a, res, expr="len(a)", meth="__len__"):
16 if verbose: print "checking", expr
17 dict = {'a': a}
18 vereq(eval(expr, dict), res)
19 t = type(a)
20 m = getattr(t, meth)
21 while meth not in t.__dict__:
22 t = t.__bases__[0]
23 vereq(m, t.__dict__[meth])
24 vereq(m(a), res)
25 bm = getattr(a, meth)
26 vereq(bm(), res)
28 def testbinop(a, b, res, expr="a+b", meth="__add__"):
29 if verbose: print "checking", expr
30 dict = {'a': a, 'b': b}
32 # XXX Hack so this passes before 2.3 when -Qnew is specified.
33 if meth == "__div__" and 1/2 == 0.5:
34 meth = "__truediv__"
36 vereq(eval(expr, dict), res)
37 t = type(a)
38 m = getattr(t, meth)
39 while meth not in t.__dict__:
40 t = t.__bases__[0]
41 vereq(m, t.__dict__[meth])
42 vereq(m(a, b), res)
43 bm = getattr(a, meth)
44 vereq(bm(b), res)
46 def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"):
47 if verbose: print "checking", expr
48 dict = {'a': a, 'b': b, 'c': c}
49 vereq(eval(expr, dict), res)
50 t = type(a)
51 m = getattr(t, meth)
52 while meth not in t.__dict__:
53 t = t.__bases__[0]
54 vereq(m, t.__dict__[meth])
55 vereq(m(a, b, c), res)
56 bm = getattr(a, meth)
57 vereq(bm(b, c), res)
59 def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
60 if verbose: print "checking", stmt
61 dict = {'a': deepcopy(a), 'b': b}
62 exec stmt in dict
63 vereq(dict['a'], res)
64 t = type(a)
65 m = getattr(t, meth)
66 while meth not in t.__dict__:
67 t = t.__bases__[0]
68 vereq(m, t.__dict__[meth])
69 dict['a'] = deepcopy(a)
70 m(dict['a'], b)
71 vereq(dict['a'], res)
72 dict['a'] = deepcopy(a)
73 bm = getattr(dict['a'], meth)
74 bm(b)
75 vereq(dict['a'], res)
77 def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
78 if verbose: print "checking", stmt
79 dict = {'a': deepcopy(a), 'b': b, 'c': c}
80 exec stmt in dict
81 vereq(dict['a'], res)
82 t = type(a)
83 m = getattr(t, meth)
84 while meth not in t.__dict__:
85 t = t.__bases__[0]
86 vereq(m, t.__dict__[meth])
87 dict['a'] = deepcopy(a)
88 m(dict['a'], b, c)
89 vereq(dict['a'], res)
90 dict['a'] = deepcopy(a)
91 bm = getattr(dict['a'], meth)
92 bm(b, c)
93 vereq(dict['a'], res)
95 def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
96 if verbose: print "checking", stmt
97 dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
98 exec stmt in dict
99 vereq(dict['a'], res)
100 t = type(a)
101 while meth not in t.__dict__:
102 t = t.__bases__[0]
103 m = getattr(t, meth)
104 vereq(m, t.__dict__[meth])
105 dict['a'] = deepcopy(a)
106 m(dict['a'], b, c, d)
107 vereq(dict['a'], res)
108 dict['a'] = deepcopy(a)
109 bm = getattr(dict['a'], meth)
110 bm(b, c, d)
111 vereq(dict['a'], res)
113 def class_docstrings():
114 class Classic:
115 "A classic docstring."
116 vereq(Classic.__doc__, "A classic docstring.")
117 vereq(Classic.__dict__['__doc__'], "A classic docstring.")
119 class Classic2:
120 pass
121 verify(Classic2.__doc__ is None)
123 class NewStatic(object):
124 "Another docstring."
125 vereq(NewStatic.__doc__, "Another docstring.")
126 vereq(NewStatic.__dict__['__doc__'], "Another docstring.")
128 class NewStatic2(object):
129 pass
130 verify(NewStatic2.__doc__ is None)
132 class NewDynamic(object):
133 "Another docstring."
134 vereq(NewDynamic.__doc__, "Another docstring.")
135 vereq(NewDynamic.__dict__['__doc__'], "Another docstring.")
137 class NewDynamic2(object):
138 pass
139 verify(NewDynamic2.__doc__ is None)
141 def lists():
142 if verbose: print "Testing list operations..."
143 testbinop([1], [2], [1,2], "a+b", "__add__")
144 testbinop([1,2,3], 2, 1, "b in a", "__contains__")
145 testbinop([1,2,3], 4, 0, "b in a", "__contains__")
146 testbinop([1,2,3], 1, 2, "a[b]", "__getitem__")
147 testternop([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
148 testsetop([1], [2], [1,2], "a+=b", "__iadd__")
149 testsetop([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
150 testunop([1,2,3], 3, "len(a)", "__len__")
151 testbinop([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
152 testbinop([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
153 testset2op([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
154 testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__")
156 def dicts():
157 if verbose: print "Testing dict operations..."
158 testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
159 testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
160 testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
161 testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
162 d = {1:2,3:4}
163 l1 = []
164 for i in d.keys(): l1.append(i)
165 l = []
166 for i in iter(d): l.append(i)
167 vereq(l, l1)
168 l = []
169 for i in d.__iter__(): l.append(i)
170 vereq(l, l1)
171 l = []
172 for i in dict.__iter__(d): l.append(i)
173 vereq(l, l1)
174 d = {1:2, 3:4}
175 testunop(d, 2, "len(a)", "__len__")
176 vereq(eval(repr(d), {}), d)
177 vereq(eval(d.__repr__(), {}), d)
178 testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__")
180 def dict_constructor():
181 if verbose:
182 print "Testing dict constructor ..."
183 d = dict()
184 vereq(d, {})
185 d = dict({})
186 vereq(d, {})
187 d = dict({1: 2, 'a': 'b'})
188 vereq(d, {1: 2, 'a': 'b'})
189 vereq(d, dict(d.items()))
190 vereq(d, dict(d.iteritems()))
191 d = dict({'one':1, 'two':2})
192 vereq(d, dict(one=1, two=2))
193 vereq(d, dict(**d))
194 vereq(d, dict({"one": 1}, two=2))
195 vereq(d, dict([("two", 2)], one=1))
196 vereq(d, dict([("one", 100), ("two", 200)], **d))
197 verify(d is not dict(**d))
198 for badarg in 0, 0L, 0j, "0", [0], (0,):
199 try:
200 dict(badarg)
201 except TypeError:
202 pass
203 except ValueError:
204 if badarg == "0":
205 # It's a sequence, and its elements are also sequences (gotta
206 # love strings <wink>), but they aren't of length 2, so this
207 # one seemed better as a ValueError than a TypeError.
208 pass
209 else:
210 raise TestFailed("no TypeError from dict(%r)" % badarg)
211 else:
212 raise TestFailed("no TypeError from dict(%r)" % badarg)
214 try:
215 dict({}, {})
216 except TypeError:
217 pass
218 else:
219 raise TestFailed("no TypeError from dict({}, {})")
221 class Mapping:
222 # Lacks a .keys() method; will be added later.
223 dict = {1:2, 3:4, 'a':1j}
225 try:
226 dict(Mapping())
227 except TypeError:
228 pass
229 else:
230 raise TestFailed("no TypeError from dict(incomplete mapping)")
232 Mapping.keys = lambda self: self.dict.keys()
233 Mapping.__getitem__ = lambda self, i: self.dict[i]
234 d = dict(Mapping())
235 vereq(d, Mapping.dict)
237 # Init from sequence of iterable objects, each producing a 2-sequence.
238 class AddressBookEntry:
239 def __init__(self, first, last):
240 self.first = first
241 self.last = last
242 def __iter__(self):
243 return iter([self.first, self.last])
245 d = dict([AddressBookEntry('Tim', 'Warsaw'),
246 AddressBookEntry('Barry', 'Peters'),
247 AddressBookEntry('Tim', 'Peters'),
248 AddressBookEntry('Barry', 'Warsaw')])
249 vereq(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
251 d = dict(zip(range(4), range(1, 5)))
252 vereq(d, dict([(i, i+1) for i in range(4)]))
254 # Bad sequence lengths.
255 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
256 try:
257 dict(bad)
258 except ValueError:
259 pass
260 else:
261 raise TestFailed("no ValueError from dict(%r)" % bad)
263 def test_dir():
264 if verbose:
265 print "Testing dir() ..."
266 junk = 12
267 vereq(dir(), ['junk'])
268 del junk
270 # Just make sure these don't blow up!
271 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir:
272 dir(arg)
274 # Try classic classes.
275 class C:
276 Cdata = 1
277 def Cmethod(self): pass
279 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
280 vereq(dir(C), cstuff)
281 verify('im_self' in dir(C.Cmethod))
283 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
284 vereq(dir(c), cstuff)
286 c.cdata = 2
287 c.cmethod = lambda self: 0
288 vereq(dir(c), cstuff + ['cdata', 'cmethod'])
289 verify('im_self' in dir(c.Cmethod))
291 class A(C):
292 Adata = 1
293 def Amethod(self): pass
295 astuff = ['Adata', 'Amethod'] + cstuff
296 vereq(dir(A), astuff)
297 verify('im_self' in dir(A.Amethod))
298 a = A()
299 vereq(dir(a), astuff)
300 verify('im_self' in dir(a.Amethod))
301 a.adata = 42
302 a.amethod = lambda self: 3
303 vereq(dir(a), astuff + ['adata', 'amethod'])
305 # The same, but with new-style classes. Since these have object as a
306 # base class, a lot more gets sucked in.
307 def interesting(strings):
308 return [s for s in strings if not s.startswith('_')]
310 class C(object):
311 Cdata = 1
312 def Cmethod(self): pass
314 cstuff = ['Cdata', 'Cmethod']
315 vereq(interesting(dir(C)), cstuff)
317 c = C()
318 vereq(interesting(dir(c)), cstuff)
319 verify('im_self' in dir(C.Cmethod))
321 c.cdata = 2
322 c.cmethod = lambda self: 0
323 vereq(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
324 verify('im_self' in dir(c.Cmethod))
326 class A(C):
327 Adata = 1
328 def Amethod(self): pass
330 astuff = ['Adata', 'Amethod'] + cstuff
331 vereq(interesting(dir(A)), astuff)
332 verify('im_self' in dir(A.Amethod))
333 a = A()
334 vereq(interesting(dir(a)), astuff)
335 a.adata = 42
336 a.amethod = lambda self: 3
337 vereq(interesting(dir(a)), astuff + ['adata', 'amethod'])
338 verify('im_self' in dir(a.Amethod))
340 # Try a module subclass.
341 import sys
342 class M(type(sys)):
343 pass
344 minstance = M("m")
345 minstance.b = 2
346 minstance.a = 1
347 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
348 vereq(names, ['a', 'b'])
350 class M2(M):
351 def getdict(self):
352 return "Not a dict!"
353 __dict__ = property(getdict)
355 m2instance = M2("m2")
356 m2instance.b = 2
357 m2instance.a = 1
358 vereq(m2instance.__dict__, "Not a dict!")
359 try:
360 dir(m2instance)
361 except TypeError:
362 pass
364 # Two essentially featureless objects, just inheriting stuff from
365 # object.
366 vereq(dir(None), dir(Ellipsis))
368 # Nasty test case for proxied objects
369 class Wrapper(object):
370 def __init__(self, obj):
371 self.__obj = obj
372 def __repr__(self):
373 return "Wrapper(%s)" % repr(self.__obj)
374 def __getitem__(self, key):
375 return Wrapper(self.__obj[key])
376 def __len__(self):
377 return len(self.__obj)
378 def __getattr__(self, name):
379 return Wrapper(getattr(self.__obj, name))
381 class C(object):
382 def __getclass(self):
383 return Wrapper(type(self))
384 __class__ = property(__getclass)
386 dir(C()) # This used to segfault
388 binops = {
389 'add': '+',
390 'sub': '-',
391 'mul': '*',
392 'div': '/',
393 'mod': '%',
394 'divmod': 'divmod',
395 'pow': '**',
396 'lshift': '<<',
397 'rshift': '>>',
398 'and': '&',
399 'xor': '^',
400 'or': '|',
401 'cmp': 'cmp',
402 'lt': '<',
403 'le': '<=',
404 'eq': '==',
405 'ne': '!=',
406 'gt': '>',
407 'ge': '>=',
410 for name, expr in binops.items():
411 if expr.islower():
412 expr = expr + "(a, b)"
413 else:
414 expr = 'a %s b' % expr
415 binops[name] = expr
417 unops = {
418 'pos': '+',
419 'neg': '-',
420 'abs': 'abs',
421 'invert': '~',
422 'int': 'int',
423 'long': 'long',
424 'float': 'float',
425 'oct': 'oct',
426 'hex': 'hex',
429 for name, expr in unops.items():
430 if expr.islower():
431 expr = expr + "(a)"
432 else:
433 expr = '%s a' % expr
434 unops[name] = expr
436 def numops(a, b, skip=[]):
437 dict = {'a': a, 'b': b}
438 for name, expr in binops.items():
439 if name not in skip:
440 name = "__%s__" % name
441 if hasattr(a, name):
442 res = eval(expr, dict)
443 testbinop(a, b, res, expr, name)
444 for name, expr in unops.items():
445 if name not in skip:
446 name = "__%s__" % name
447 if hasattr(a, name):
448 res = eval(expr, dict)
449 testunop(a, res, expr, name)
451 def ints():
452 if verbose: print "Testing int operations..."
453 numops(100, 3)
454 # The following crashes in Python 2.2
455 vereq((1).__nonzero__(), 1)
456 vereq((0).__nonzero__(), 0)
457 # This returns 'NotImplemented' in Python 2.2
458 class C(int):
459 def __add__(self, other):
460 return NotImplemented
461 vereq(C(5L), 5)
462 try:
463 C() + ""
464 except TypeError:
465 pass
466 else:
467 raise TestFailed, "NotImplemented should have caused TypeError"
468 import sys
469 try:
470 C(sys.maxint+1)
471 except OverflowError:
472 pass
473 else:
474 raise TestFailed, "should have raised OverflowError"
476 def longs():
477 if verbose: print "Testing long operations..."
478 numops(100L, 3L)
480 def floats():
481 if verbose: print "Testing float operations..."
482 numops(100.0, 3.0)
484 def complexes():
485 if verbose: print "Testing complex operations..."
486 numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float'])
487 class Number(complex):
488 __slots__ = ['prec']
489 def __new__(cls, *args, **kwds):
490 result = complex.__new__(cls, *args)
491 result.prec = kwds.get('prec', 12)
492 return result
493 def __repr__(self):
494 prec = self.prec
495 if self.imag == 0.0:
496 return "%.*g" % (prec, self.real)
497 if self.real == 0.0:
498 return "%.*gj" % (prec, self.imag)
499 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
500 __str__ = __repr__
502 a = Number(3.14, prec=6)
503 vereq(repr(a), "3.14")
504 vereq(a.prec, 6)
506 a = Number(a, prec=2)
507 vereq(repr(a), "3.1")
508 vereq(a.prec, 2)
510 a = Number(234.5)
511 vereq(repr(a), "234.5")
512 vereq(a.prec, 12)
514 def spamlists():
515 if verbose: print "Testing spamlist operations..."
516 import copy, xxsubtype as spam
517 def spamlist(l, memo=None):
518 import xxsubtype as spam
519 return spam.spamlist(l)
520 # This is an ugly hack:
521 copy._deepcopy_dispatch[spam.spamlist] = spamlist
523 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
524 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
525 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
526 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
527 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
528 "a[b:c]", "__getslice__")
529 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
530 "a+=b", "__iadd__")
531 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
532 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
533 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
534 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
535 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
536 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
537 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
538 # Test subclassing
539 class C(spam.spamlist):
540 def foo(self): return 1
541 a = C()
542 vereq(a, [])
543 vereq(a.foo(), 1)
544 a.append(100)
545 vereq(a, [100])
546 vereq(a.getstate(), 0)
547 a.setstate(42)
548 vereq(a.getstate(), 42)
550 def spamdicts():
551 if verbose: print "Testing spamdict operations..."
552 import copy, xxsubtype as spam
553 def spamdict(d, memo=None):
554 import xxsubtype as spam
555 sd = spam.spamdict()
556 for k, v in d.items(): sd[k] = v
557 return sd
558 # This is an ugly hack:
559 copy._deepcopy_dispatch[spam.spamdict] = spamdict
561 testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
562 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
563 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
564 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
565 d = spamdict({1:2,3:4})
566 l1 = []
567 for i in d.keys(): l1.append(i)
568 l = []
569 for i in iter(d): l.append(i)
570 vereq(l, l1)
571 l = []
572 for i in d.__iter__(): l.append(i)
573 vereq(l, l1)
574 l = []
575 for i in type(spamdict({})).__iter__(d): l.append(i)
576 vereq(l, l1)
577 straightd = {1:2, 3:4}
578 spamd = spamdict(straightd)
579 testunop(spamd, 2, "len(a)", "__len__")
580 testunop(spamd, repr(straightd), "repr(a)", "__repr__")
581 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
582 "a[b]=c", "__setitem__")
583 # Test subclassing
584 class C(spam.spamdict):
585 def foo(self): return 1
586 a = C()
587 vereq(a.items(), [])
588 vereq(a.foo(), 1)
589 a['foo'] = 'bar'
590 vereq(a.items(), [('foo', 'bar')])
591 vereq(a.getstate(), 0)
592 a.setstate(100)
593 vereq(a.getstate(), 100)
595 def pydicts():
596 if verbose: print "Testing Python subclass of dict..."
597 verify(issubclass(dict, dict))
598 verify(isinstance({}, dict))
599 d = dict()
600 vereq(d, {})
601 verify(d.__class__ is dict)
602 verify(isinstance(d, dict))
603 class C(dict):
604 state = -1
605 def __init__(self, *a, **kw):
606 if a:
607 vereq(len(a), 1)
608 self.state = a[0]
609 if kw:
610 for k, v in kw.items(): self[v] = k
611 def __getitem__(self, key):
612 return self.get(key, 0)
613 def __setitem__(self, key, value):
614 verify(isinstance(key, type(0)))
615 dict.__setitem__(self, key, value)
616 def setstate(self, state):
617 self.state = state
618 def getstate(self):
619 return self.state
620 verify(issubclass(C, dict))
621 a1 = C(12)
622 vereq(a1.state, 12)
623 a2 = C(foo=1, bar=2)
624 vereq(a2[1] == 'foo' and a2[2], 'bar')
625 a = C()
626 vereq(a.state, -1)
627 vereq(a.getstate(), -1)
628 a.setstate(0)
629 vereq(a.state, 0)
630 vereq(a.getstate(), 0)
631 a.setstate(10)
632 vereq(a.state, 10)
633 vereq(a.getstate(), 10)
634 vereq(a[42], 0)
635 a[42] = 24
636 vereq(a[42], 24)
637 if verbose: print "pydict stress test ..."
638 N = 50
639 for i in range(N):
640 a[i] = C()
641 for j in range(N):
642 a[i][j] = i*j
643 for i in range(N):
644 for j in range(N):
645 vereq(a[i][j], i*j)
647 def pylists():
648 if verbose: print "Testing Python subclass of list..."
649 class C(list):
650 def __getitem__(self, i):
651 return list.__getitem__(self, i) + 100
652 def __getslice__(self, i, j):
653 return (i, j)
654 a = C()
655 a.extend([0,1,2])
656 vereq(a[0], 100)
657 vereq(a[1], 101)
658 vereq(a[2], 102)
659 vereq(a[100:200], (100,200))
661 def metaclass():
662 if verbose: print "Testing __metaclass__..."
663 class C:
664 __metaclass__ = type
665 def __init__(self):
666 self.__state = 0
667 def getstate(self):
668 return self.__state
669 def setstate(self, state):
670 self.__state = state
671 a = C()
672 vereq(a.getstate(), 0)
673 a.setstate(10)
674 vereq(a.getstate(), 10)
675 class D:
676 class __metaclass__(type):
677 def myself(cls): return cls
678 vereq(D.myself(), D)
679 d = D()
680 verify(d.__class__ is D)
681 class M1(type):
682 def __new__(cls, name, bases, dict):
683 dict['__spam__'] = 1
684 return type.__new__(cls, name, bases, dict)
685 class C:
686 __metaclass__ = M1
687 vereq(C.__spam__, 1)
688 c = C()
689 vereq(c.__spam__, 1)
691 class _instance(object):
692 pass
693 class M2(object):
694 @staticmethod
695 def __new__(cls, name, bases, dict):
696 self = object.__new__(cls)
697 self.name = name
698 self.bases = bases
699 self.dict = dict
700 return self
701 def __call__(self):
702 it = _instance()
703 # Early binding of methods
704 for key in self.dict:
705 if key.startswith("__"):
706 continue
707 setattr(it, key, self.dict[key].__get__(it, self))
708 return it
709 class C:
710 __metaclass__ = M2
711 def spam(self):
712 return 42
713 vereq(C.name, 'C')
714 vereq(C.bases, ())
715 verify('spam' in C.dict)
716 c = C()
717 vereq(c.spam(), 42)
719 # More metaclass examples
721 class autosuper(type):
722 # Automatically add __super to the class
723 # This trick only works for dynamic classes
724 def __new__(metaclass, name, bases, dict):
725 cls = super(autosuper, metaclass).__new__(metaclass,
726 name, bases, dict)
727 # Name mangling for __super removes leading underscores
728 while name[:1] == "_":
729 name = name[1:]
730 if name:
731 name = "_%s__super" % name
732 else:
733 name = "__super"
734 setattr(cls, name, super(cls))
735 return cls
736 class A:
737 __metaclass__ = autosuper
738 def meth(self):
739 return "A"
740 class B(A):
741 def meth(self):
742 return "B" + self.__super.meth()
743 class C(A):
744 def meth(self):
745 return "C" + self.__super.meth()
746 class D(C, B):
747 def meth(self):
748 return "D" + self.__super.meth()
749 vereq(D().meth(), "DCBA")
750 class E(B, C):
751 def meth(self):
752 return "E" + self.__super.meth()
753 vereq(E().meth(), "EBCA")
755 class autoproperty(type):
756 # Automatically create property attributes when methods
757 # named _get_x and/or _set_x are found
758 def __new__(metaclass, name, bases, dict):
759 hits = {}
760 for key, val in dict.iteritems():
761 if key.startswith("_get_"):
762 key = key[5:]
763 get, set = hits.get(key, (None, None))
764 get = val
765 hits[key] = get, set
766 elif key.startswith("_set_"):
767 key = key[5:]
768 get, set = hits.get(key, (None, None))
769 set = val
770 hits[key] = get, set
771 for key, (get, set) in hits.iteritems():
772 dict[key] = property(get, set)
773 return super(autoproperty, metaclass).__new__(metaclass,
774 name, bases, dict)
775 class A:
776 __metaclass__ = autoproperty
777 def _get_x(self):
778 return -self.__x
779 def _set_x(self, x):
780 self.__x = -x
781 a = A()
782 verify(not hasattr(a, "x"))
783 a.x = 12
784 vereq(a.x, 12)
785 vereq(a._A__x, -12)
787 class multimetaclass(autoproperty, autosuper):
788 # Merge of multiple cooperating metaclasses
789 pass
790 class A:
791 __metaclass__ = multimetaclass
792 def _get_x(self):
793 return "A"
794 class B(A):
795 def _get_x(self):
796 return "B" + self.__super._get_x()
797 class C(A):
798 def _get_x(self):
799 return "C" + self.__super._get_x()
800 class D(C, B):
801 def _get_x(self):
802 return "D" + self.__super._get_x()
803 vereq(D().x, "DCBA")
805 # Make sure type(x) doesn't call x.__class__.__init__
806 class T(type):
807 counter = 0
808 def __init__(self, *args):
809 T.counter += 1
810 class C:
811 __metaclass__ = T
812 vereq(T.counter, 1)
813 a = C()
814 vereq(type(a), C)
815 vereq(T.counter, 1)
817 class C(object): pass
818 c = C()
819 try: c()
820 except TypeError: pass
821 else: raise TestFailed, "calling object w/o call method should raise TypeError"
823 def pymods():
824 if verbose: print "Testing Python subclass of module..."
825 log = []
826 import sys
827 MT = type(sys)
828 class MM(MT):
829 def __init__(self, name):
830 MT.__init__(self, name)
831 def __getattribute__(self, name):
832 log.append(("getattr", name))
833 return MT.__getattribute__(self, name)
834 def __setattr__(self, name, value):
835 log.append(("setattr", name, value))
836 MT.__setattr__(self, name, value)
837 def __delattr__(self, name):
838 log.append(("delattr", name))
839 MT.__delattr__(self, name)
840 a = MM("a")
841 a.foo = 12
842 x = a.foo
843 del a.foo
844 vereq(log, [("setattr", "foo", 12),
845 ("getattr", "foo"),
846 ("delattr", "foo")])
848 def multi():
849 if verbose: print "Testing multiple inheritance..."
850 class C(object):
851 def __init__(self):
852 self.__state = 0
853 def getstate(self):
854 return self.__state
855 def setstate(self, state):
856 self.__state = state
857 a = C()
858 vereq(a.getstate(), 0)
859 a.setstate(10)
860 vereq(a.getstate(), 10)
861 class D(dict, C):
862 def __init__(self):
863 type({}).__init__(self)
864 C.__init__(self)
865 d = D()
866 vereq(d.keys(), [])
867 d["hello"] = "world"
868 vereq(d.items(), [("hello", "world")])
869 vereq(d["hello"], "world")
870 vereq(d.getstate(), 0)
871 d.setstate(10)
872 vereq(d.getstate(), 10)
873 vereq(D.__mro__, (D, dict, C, object))
875 # SF bug #442833
876 class Node(object):
877 def __int__(self):
878 return int(self.foo())
879 def foo(self):
880 return "23"
881 class Frag(Node, list):
882 def foo(self):
883 return "42"
884 vereq(Node().__int__(), 23)
885 vereq(int(Node()), 23)
886 vereq(Frag().__int__(), 42)
887 vereq(int(Frag()), 42)
889 # MI mixing classic and new-style classes.
891 class A:
892 x = 1
894 class B(A):
895 pass
897 class C(A):
898 x = 2
900 class D(B, C):
901 pass
902 vereq(D.x, 1)
904 # Classic MRO is preserved for a classic base class.
905 class E(D, object):
906 pass
907 vereq(E.__mro__, (E, D, B, A, C, object))
908 vereq(E.x, 1)
910 # But with a mix of classic bases, their MROs are combined using
911 # new-style MRO.
912 class F(B, C, object):
913 pass
914 vereq(F.__mro__, (F, B, C, A, object))
915 vereq(F.x, 2)
917 # Try something else.
918 class C:
919 def cmethod(self):
920 return "C a"
921 def all_method(self):
922 return "C b"
924 class M1(C, object):
925 def m1method(self):
926 return "M1 a"
927 def all_method(self):
928 return "M1 b"
930 vereq(M1.__mro__, (M1, C, object))
931 m = M1()
932 vereq(m.cmethod(), "C a")
933 vereq(m.m1method(), "M1 a")
934 vereq(m.all_method(), "M1 b")
936 class D(C):
937 def dmethod(self):
938 return "D a"
939 def all_method(self):
940 return "D b"
942 class M2(D, object):
943 def m2method(self):
944 return "M2 a"
945 def all_method(self):
946 return "M2 b"
948 vereq(M2.__mro__, (M2, D, C, object))
949 m = M2()
950 vereq(m.cmethod(), "C a")
951 vereq(m.dmethod(), "D a")
952 vereq(m.m2method(), "M2 a")
953 vereq(m.all_method(), "M2 b")
955 class M3(M1, M2, object):
956 def m3method(self):
957 return "M3 a"
958 def all_method(self):
959 return "M3 b"
960 vereq(M3.__mro__, (M3, M1, M2, D, C, object))
961 m = M3()
962 vereq(m.cmethod(), "C a")
963 vereq(m.dmethod(), "D a")
964 vereq(m.m1method(), "M1 a")
965 vereq(m.m2method(), "M2 a")
966 vereq(m.m3method(), "M3 a")
967 vereq(m.all_method(), "M3 b")
969 class Classic:
970 pass
971 try:
972 class New(Classic):
973 __metaclass__ = type
974 except TypeError:
975 pass
976 else:
977 raise TestFailed, "new class with only classic bases - shouldn't be"
979 def diamond():
980 if verbose: print "Testing multiple inheritance special cases..."
981 class A(object):
982 def spam(self): return "A"
983 vereq(A().spam(), "A")
984 class B(A):
985 def boo(self): return "B"
986 def spam(self): return "B"
987 vereq(B().spam(), "B")
988 vereq(B().boo(), "B")
989 class C(A):
990 def boo(self): return "C"
991 vereq(C().spam(), "A")
992 vereq(C().boo(), "C")
993 class D(B, C): pass
994 vereq(D().spam(), "B")
995 vereq(D().boo(), "B")
996 vereq(D.__mro__, (D, B, C, A, object))
997 class E(C, B): pass
998 vereq(E().spam(), "B")
999 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)"
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))
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
1040 vereq(PedalWheelBoat.__mro__,
1041 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat,
1042 object))
1043 vereq(SmallCatamaran.__mro__,
1044 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
1046 vereq(Pedalo.__mro__,
1047 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
1048 SmallMultihull, DayBoat, WheelBoat, Boat, object))
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
1061 vereq(EditableScrollablePane.__mro__,
1062 (EditableScrollablePane, ScrollablePane, EditablePane,
1063 Pane, ScrollingMixin, EditingMixin, object))
1065 mro_err_msg = """Cannot create a consistent method resolution
1066 order (MRO) for bases """
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), {})
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__"))
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})
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"))
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"))
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)
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"
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"]
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)
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)
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
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
1287 def slotspecials():
1288 if verbose: print "Testing __dict__ and __weakref__ in __slots__..."
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})
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"
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})
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})
1326 # MRO order disagreement
1328 # class C3(C1, C2):
1329 # __slots__ = []
1331 # class C4(C2, C1):
1332 # __slots__ = []
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)
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)
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)
1406 # Test comparison of classes with dynamic metaclasses
1407 class dynamicmetaclass(type):
1408 pass
1409 class someclass:
1410 __metaclass__ = dynamicmetaclass
1411 verify(someclass != object)
1413 def errors():
1414 if verbose: print "Testing errors..."
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")
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
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")
1442 try:
1443 class C(object):
1444 __slots__ = 1
1445 except TypeError:
1446 pass
1447 else:
1448 verify(0, "__slots__ = 1 should be illegal")
1450 try:
1451 class C(object):
1452 __slots__ = [1]
1453 except TypeError:
1454 pass
1455 else:
1456 verify(0, "__slots__ = [1] should be illegal")
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))
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,))
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"
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)
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))
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)
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 "))
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)
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)
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")
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")
1638 try:
1639 class X(object):
1640 class __metaclass__(type):
1641 def mro(self):
1642 return [self, dict, object]
1643 except TypeError:
1644 pass
1645 else:
1646 raise TestFailed, "devious mro() return not caught"
1648 try:
1649 class X(object):
1650 class __metaclass__(type):
1651 def mro(self):
1652 return [1]
1653 except TypeError:
1654 pass
1655 else:
1656 raise TestFailed, "non-class mro() return not caught"
1658 try:
1659 class X(object):
1660 class __metaclass__(type):
1661 def mro(self):
1662 return 1
1663 except TypeError:
1664 pass
1665 else:
1666 raise TestFailed, "non-sequence mro() return not caught"
1669 def overloading():
1670 if verbose: print "Testing operator overloading..."
1672 class B(object):
1673 "Intermediate class because object doesn't have a __setattr__"
1675 class C(B):
1677 def __getattr__(self, name):
1678 if name == "foo":
1679 return ("getattr", name)
1680 else:
1681 raise AttributeError
1682 def __setattr__(self, name, value):
1683 if name == "foo":
1684 self.setattr = (name, value)
1685 else:
1686 return B.__setattr__(self, name, value)
1687 def __delattr__(self, name):
1688 if name == "foo":
1689 self.delattr = name
1690 else:
1691 return B.__delattr__(self, name)
1693 def __getitem__(self, key):
1694 return ("getitem", key)
1695 def __setitem__(self, key, value):
1696 self.setitem = (key, value)
1697 def __delitem__(self, key):
1698 self.delitem = key
1700 def __getslice__(self, i, j):
1701 return ("getslice", i, j)
1702 def __setslice__(self, i, j, value):
1703 self.setslice = (i, j, value)
1704 def __delslice__(self, i, j):
1705 self.delslice = (i, j)
1707 a = C()
1708 vereq(a.foo, ("getattr", "foo"))
1709 a.foo = 12
1710 vereq(a.setattr, ("foo", 12))
1711 del a.foo
1712 vereq(a.delattr, "foo")
1714 vereq(a[12], ("getitem", 12))
1715 a[12] = 21
1716 vereq(a.setitem, (12, 21))
1717 del a[12]
1718 vereq(a.delitem, 12)
1720 vereq(a[0:10], ("getslice", 0, 10))
1721 a[0:10] = "foo"
1722 vereq(a.setslice, (0, 10, "foo"))
1723 del a[0:10]
1724 vereq(a.delslice, (0, 10))
1726 def methods():
1727 if verbose: print "Testing methods..."
1728 class C(object):
1729 def __init__(self, x):
1730 self.x = x
1731 def foo(self):
1732 return self.x
1733 c1 = C(1)
1734 vereq(c1.foo(), 1)
1735 class D(C):
1736 boo = C.foo
1737 goo = c1.foo
1738 d2 = D(2)
1739 vereq(d2.foo(), 2)
1740 vereq(d2.boo(), 2)
1741 vereq(d2.goo(), 1)
1742 class E(object):
1743 foo = C.foo
1744 vereq(E().foo, C.foo) # i.e., unbound
1745 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
1747 def specials():
1748 # Test operators like __hash__ for which a built-in default exists
1749 if verbose: print "Testing special operators..."
1750 # Test the default behavior for static classes
1751 class C(object):
1752 def __getitem__(self, i):
1753 if 0 <= i < 10: return i
1754 raise IndexError
1755 c1 = C()
1756 c2 = C()
1757 verify(not not c1)
1758 vereq(hash(c1), id(c1))
1759 vereq(cmp(c1, c2), cmp(id(c1), id(c2)))
1760 vereq(c1, c1)
1761 verify(c1 != c2)
1762 verify(not c1 != c1)
1763 verify(not c1 == c2)
1764 # Note that the module name appears in str/repr, and that varies
1765 # depending on whether this test is run standalone or from a framework.
1766 verify(str(c1).find('C object at ') >= 0)
1767 vereq(str(c1), repr(c1))
1768 verify(-1 not in c1)
1769 for i in range(10):
1770 verify(i in c1)
1771 verify(10 not in c1)
1772 # Test the default behavior for dynamic classes
1773 class D(object):
1774 def __getitem__(self, i):
1775 if 0 <= i < 10: return i
1776 raise IndexError
1777 d1 = D()
1778 d2 = D()
1779 verify(not not d1)
1780 vereq(hash(d1), id(d1))
1781 vereq(cmp(d1, d2), cmp(id(d1), id(d2)))
1782 vereq(d1, d1)
1783 verify(d1 != d2)
1784 verify(not d1 != d1)
1785 verify(not d1 == d2)
1786 # Note that the module name appears in str/repr, and that varies
1787 # depending on whether this test is run standalone or from a framework.
1788 verify(str(d1).find('D object at ') >= 0)
1789 vereq(str(d1), repr(d1))
1790 verify(-1 not in d1)
1791 for i in range(10):
1792 verify(i in d1)
1793 verify(10 not in d1)
1794 # Test overridden behavior for static classes
1795 class Proxy(object):
1796 def __init__(self, x):
1797 self.x = x
1798 def __nonzero__(self):
1799 return not not self.x
1800 def __hash__(self):
1801 return hash(self.x)
1802 def __eq__(self, other):
1803 return self.x == other
1804 def __ne__(self, other):
1805 return self.x != other
1806 def __cmp__(self, other):
1807 return cmp(self.x, other.x)
1808 def __str__(self):
1809 return "Proxy:%s" % self.x
1810 def __repr__(self):
1811 return "Proxy(%r)" % self.x
1812 def __contains__(self, value):
1813 return value in self.x
1814 p0 = Proxy(0)
1815 p1 = Proxy(1)
1816 p_1 = Proxy(-1)
1817 verify(not p0)
1818 verify(not not p1)
1819 vereq(hash(p0), hash(0))
1820 vereq(p0, p0)
1821 verify(p0 != p1)
1822 verify(not p0 != p0)
1823 vereq(not p0, p1)
1824 vereq(cmp(p0, p1), -1)
1825 vereq(cmp(p0, p0), 0)
1826 vereq(cmp(p0, p_1), 1)
1827 vereq(str(p0), "Proxy:0")
1828 vereq(repr(p0), "Proxy(0)")
1829 p10 = Proxy(range(10))
1830 verify(-1 not in p10)
1831 for i in range(10):
1832 verify(i in p10)
1833 verify(10 not in p10)
1834 # Test overridden behavior for dynamic classes
1835 class DProxy(object):
1836 def __init__(self, x):
1837 self.x = x
1838 def __nonzero__(self):
1839 return not not self.x
1840 def __hash__(self):
1841 return hash(self.x)
1842 def __eq__(self, other):
1843 return self.x == other
1844 def __ne__(self, other):
1845 return self.x != other
1846 def __cmp__(self, other):
1847 return cmp(self.x, other.x)
1848 def __str__(self):
1849 return "DProxy:%s" % self.x
1850 def __repr__(self):
1851 return "DProxy(%r)" % self.x
1852 def __contains__(self, value):
1853 return value in self.x
1854 p0 = DProxy(0)
1855 p1 = DProxy(1)
1856 p_1 = DProxy(-1)
1857 verify(not p0)
1858 verify(not not p1)
1859 vereq(hash(p0), hash(0))
1860 vereq(p0, p0)
1861 verify(p0 != p1)
1862 verify(not p0 != p0)
1863 vereq(not p0, p1)
1864 vereq(cmp(p0, p1), -1)
1865 vereq(cmp(p0, p0), 0)
1866 vereq(cmp(p0, p_1), 1)
1867 vereq(str(p0), "DProxy:0")
1868 vereq(repr(p0), "DProxy(0)")
1869 p10 = DProxy(range(10))
1870 verify(-1 not in p10)
1871 for i in range(10):
1872 verify(i in p10)
1873 verify(10 not in p10)
1874 # Safety test for __cmp__
1875 def unsafecmp(a, b):
1876 try:
1877 a.__class__.__cmp__(a, b)
1878 except TypeError:
1879 pass
1880 else:
1881 raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
1882 a.__class__, a, b)
1883 unsafecmp(u"123", "123")
1884 unsafecmp("123", u"123")
1885 unsafecmp(1, 1.0)
1886 unsafecmp(1.0, 1)
1887 unsafecmp(1, 1L)
1888 unsafecmp(1L, 1)
1890 class Letter(str):
1891 def __new__(cls, letter):
1892 if letter == 'EPS':
1893 return str.__new__(cls)
1894 return str.__new__(cls, letter)
1895 def __str__(self):
1896 if not self:
1897 return 'EPS'
1898 return self
1900 # sys.stdout needs to be the original to trigger the recursion bug
1901 import sys
1902 test_stdout = sys.stdout
1903 sys.stdout = get_original_stdout()
1904 try:
1905 # nothing should actually be printed, this should raise an exception
1906 print Letter('w')
1907 except RuntimeError:
1908 pass
1909 else:
1910 raise TestFailed, "expected a RuntimeError for print recursion"
1911 sys.stdout = test_stdout
1913 def weakrefs():
1914 if verbose: print "Testing weak references..."
1915 import weakref
1916 class C(object):
1917 pass
1918 c = C()
1919 r = weakref.ref(c)
1920 verify(r() is c)
1921 del c
1922 verify(r() is None)
1923 del r
1924 class NoWeak(object):
1925 __slots__ = ['foo']
1926 no = NoWeak()
1927 try:
1928 weakref.ref(no)
1929 except TypeError, msg:
1930 verify(str(msg).find("weak reference") >= 0)
1931 else:
1932 verify(0, "weakref.ref(no) should be illegal")
1933 class Weak(object):
1934 __slots__ = ['foo', '__weakref__']
1935 yes = Weak()
1936 r = weakref.ref(yes)
1937 verify(r() is yes)
1938 del yes
1939 verify(r() is None)
1940 del r
1942 def properties():
1943 if verbose: print "Testing property..."
1944 class C(object):
1945 def getx(self):
1946 return self.__x
1947 def setx(self, value):
1948 self.__x = value
1949 def delx(self):
1950 del self.__x
1951 x = property(getx, setx, delx, doc="I'm the x property.")
1952 a = C()
1953 verify(not hasattr(a, "x"))
1954 a.x = 42
1955 vereq(a._C__x, 42)
1956 vereq(a.x, 42)
1957 del a.x
1958 verify(not hasattr(a, "x"))
1959 verify(not hasattr(a, "_C__x"))
1960 C.x.__set__(a, 100)
1961 vereq(C.x.__get__(a), 100)
1962 C.x.__delete__(a)
1963 verify(not hasattr(a, "x"))
1965 raw = C.__dict__['x']
1966 verify(isinstance(raw, property))
1968 attrs = dir(raw)
1969 verify("__doc__" in attrs)
1970 verify("fget" in attrs)
1971 verify("fset" in attrs)
1972 verify("fdel" in attrs)
1974 vereq(raw.__doc__, "I'm the x property.")
1975 verify(raw.fget is C.__dict__['getx'])
1976 verify(raw.fset is C.__dict__['setx'])
1977 verify(raw.fdel is C.__dict__['delx'])
1979 for attr in "__doc__", "fget", "fset", "fdel":
1980 try:
1981 setattr(raw, attr, 42)
1982 except TypeError, msg:
1983 if str(msg).find('readonly') < 0:
1984 raise TestFailed("when setting readonly attr %r on a "
1985 "property, got unexpected TypeError "
1986 "msg %r" % (attr, str(msg)))
1987 else:
1988 raise TestFailed("expected TypeError from trying to set "
1989 "readonly %r attr on a property" % attr)
1991 class D(object):
1992 __getitem__ = property(lambda s: 1/0)
1994 d = D()
1995 try:
1996 for i in d:
1997 str(i)
1998 except ZeroDivisionError:
1999 pass
2000 else:
2001 raise TestFailed, "expected ZeroDivisionError from bad property"
2003 def supers():
2004 if verbose: print "Testing super..."
2006 class A(object):
2007 def meth(self, a):
2008 return "A(%r)" % a
2010 vereq(A().meth(1), "A(1)")
2012 class B(A):
2013 def __init__(self):
2014 self.__super = super(B, self)
2015 def meth(self, a):
2016 return "B(%r)" % a + self.__super.meth(a)
2018 vereq(B().meth(2), "B(2)A(2)")
2020 class C(A):
2021 def meth(self, a):
2022 return "C(%r)" % a + self.__super.meth(a)
2023 C._C__super = super(C)
2025 vereq(C().meth(3), "C(3)A(3)")
2027 class D(C, B):
2028 def meth(self, a):
2029 return "D(%r)" % a + super(D, self).meth(a)
2031 vereq(D().meth(4), "D(4)C(4)B(4)A(4)")
2033 # Test for subclassing super
2035 class mysuper(super):
2036 def __init__(self, *args):
2037 return super(mysuper, self).__init__(*args)
2039 class E(D):
2040 def meth(self, a):
2041 return "E(%r)" % a + mysuper(E, self).meth(a)
2043 vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2045 class F(E):
2046 def meth(self, a):
2047 s = self.__super # == mysuper(F, self)
2048 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2049 F._F__super = mysuper(F)
2051 vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2053 # Make sure certain errors are raised
2055 try:
2056 super(D, 42)
2057 except TypeError:
2058 pass
2059 else:
2060 raise TestFailed, "shouldn't allow super(D, 42)"
2062 try:
2063 super(D, C())
2064 except TypeError:
2065 pass
2066 else:
2067 raise TestFailed, "shouldn't allow super(D, C())"
2069 try:
2070 super(D).__get__(12)
2071 except TypeError:
2072 pass
2073 else:
2074 raise TestFailed, "shouldn't allow super(D).__get__(12)"
2076 try:
2077 super(D).__get__(C())
2078 except TypeError:
2079 pass
2080 else:
2081 raise TestFailed, "shouldn't allow super(D).__get__(C())"
2083 # Make sure data descriptors can be overridden and accessed via super
2084 # (new feature in Python 2.3)
2086 class DDbase(object):
2087 def getx(self): return 42
2088 x = property(getx)
2090 class DDsub(DDbase):
2091 def getx(self): return "hello"
2092 x = property(getx)
2094 dd = DDsub()
2095 vereq(dd.x, "hello")
2096 vereq(super(DDsub, dd).x, 42)
2098 # Ensure that super() lookup of descriptor from classmethod
2099 # works (SF ID# 743627)
2101 class Base(object):
2102 aProp = property(lambda self: "foo")
2104 class Sub(Base):
2105 @classmethod
2106 def test(klass):
2107 return super(Sub,klass).aProp
2109 veris(Sub.test(), Base.aProp)
2112 def inherits():
2113 if verbose: print "Testing inheritance from basic types..."
2115 class hexint(int):
2116 def __repr__(self):
2117 return hex(self)
2118 def __add__(self, other):
2119 return hexint(int.__add__(self, other))
2120 # (Note that overriding __radd__ doesn't work,
2121 # because the int type gets first dibs.)
2122 vereq(repr(hexint(7) + 9), "0x10")
2123 vereq(repr(hexint(1000) + 7), "0x3ef")
2124 a = hexint(12345)
2125 vereq(a, 12345)
2126 vereq(int(a), 12345)
2127 verify(int(a).__class__ is int)
2128 vereq(hash(a), hash(12345))
2129 verify((+a).__class__ is int)
2130 verify((a >> 0).__class__ is int)
2131 verify((a << 0).__class__ is int)
2132 verify((hexint(0) << 12).__class__ is int)
2133 verify((hexint(0) >> 12).__class__ is int)
2135 class octlong(long):
2136 __slots__ = []
2137 def __str__(self):
2138 s = oct(self)
2139 if s[-1] == 'L':
2140 s = s[:-1]
2141 return s
2142 def __add__(self, other):
2143 return self.__class__(super(octlong, self).__add__(other))
2144 __radd__ = __add__
2145 vereq(str(octlong(3) + 5), "010")
2146 # (Note that overriding __radd__ here only seems to work
2147 # because the example uses a short int left argument.)
2148 vereq(str(5 + octlong(3000)), "05675")
2149 a = octlong(12345)
2150 vereq(a, 12345L)
2151 vereq(long(a), 12345L)
2152 vereq(hash(a), hash(12345L))
2153 verify(long(a).__class__ is long)
2154 verify((+a).__class__ is long)
2155 verify((-a).__class__ is long)
2156 verify((-octlong(0)).__class__ is long)
2157 verify((a >> 0).__class__ is long)
2158 verify((a << 0).__class__ is long)
2159 verify((a - 0).__class__ is long)
2160 verify((a * 1).__class__ is long)
2161 verify((a ** 1).__class__ is long)
2162 verify((a // 1).__class__ is long)
2163 verify((1 * a).__class__ is long)
2164 verify((a | 0).__class__ is long)
2165 verify((a ^ 0).__class__ is long)
2166 verify((a & -1L).__class__ is long)
2167 verify((octlong(0) << 12).__class__ is long)
2168 verify((octlong(0) >> 12).__class__ is long)
2169 verify(abs(octlong(0)).__class__ is long)
2171 # Because octlong overrides __add__, we can't check the absence of +0
2172 # optimizations using octlong.
2173 class longclone(long):
2174 pass
2175 a = longclone(1)
2176 verify((a + 0).__class__ is long)
2177 verify((0 + a).__class__ is long)
2179 # Check that negative clones don't segfault
2180 a = longclone(-1)
2181 vereq(a.__dict__, {})
2182 vereq(long(a), -1) # verify PyNumber_Long() copies the sign bit
2184 class precfloat(float):
2185 __slots__ = ['prec']
2186 def __init__(self, value=0.0, prec=12):
2187 self.prec = int(prec)
2188 float.__init__(value)
2189 def __repr__(self):
2190 return "%.*g" % (self.prec, self)
2191 vereq(repr(precfloat(1.1)), "1.1")
2192 a = precfloat(12345)
2193 vereq(a, 12345.0)
2194 vereq(float(a), 12345.0)
2195 verify(float(a).__class__ is float)
2196 vereq(hash(a), hash(12345.0))
2197 verify((+a).__class__ is float)
2199 class madcomplex(complex):
2200 def __repr__(self):
2201 return "%.17gj%+.17g" % (self.imag, self.real)
2202 a = madcomplex(-3, 4)
2203 vereq(repr(a), "4j-3")
2204 base = complex(-3, 4)
2205 veris(base.__class__, complex)
2206 vereq(a, base)
2207 vereq(complex(a), base)
2208 veris(complex(a).__class__, complex)
2209 a = madcomplex(a) # just trying another form of the constructor
2210 vereq(repr(a), "4j-3")
2211 vereq(a, base)
2212 vereq(complex(a), base)
2213 veris(complex(a).__class__, complex)
2214 vereq(hash(a), hash(base))
2215 veris((+a).__class__, complex)
2216 veris((a + 0).__class__, complex)
2217 vereq(a + 0, base)
2218 veris((a - 0).__class__, complex)
2219 vereq(a - 0, base)
2220 veris((a * 1).__class__, complex)
2221 vereq(a * 1, base)
2222 veris((a / 1).__class__, complex)
2223 vereq(a / 1, base)
2225 class madtuple(tuple):
2226 _rev = None
2227 def rev(self):
2228 if self._rev is not None:
2229 return self._rev
2230 L = list(self)
2231 L.reverse()
2232 self._rev = self.__class__(L)
2233 return self._rev
2234 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2235 vereq(a, (1,2,3,4,5,6,7,8,9,0))
2236 vereq(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2237 vereq(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2238 for i in range(512):
2239 t = madtuple(range(i))
2240 u = t.rev()
2241 v = u.rev()
2242 vereq(v, t)
2243 a = madtuple((1,2,3,4,5))
2244 vereq(tuple(a), (1,2,3,4,5))
2245 verify(tuple(a).__class__ is tuple)
2246 vereq(hash(a), hash((1,2,3,4,5)))
2247 verify(a[:].__class__ is tuple)
2248 verify((a * 1).__class__ is tuple)
2249 verify((a * 0).__class__ is tuple)
2250 verify((a + ()).__class__ is tuple)
2251 a = madtuple(())
2252 vereq(tuple(a), ())
2253 verify(tuple(a).__class__ is tuple)
2254 verify((a + a).__class__ is tuple)
2255 verify((a * 0).__class__ is tuple)
2256 verify((a * 1).__class__ is tuple)
2257 verify((a * 2).__class__ is tuple)
2258 verify(a[:].__class__ is tuple)
2260 class madstring(str):
2261 _rev = None
2262 def rev(self):
2263 if self._rev is not None:
2264 return self._rev
2265 L = list(self)
2266 L.reverse()
2267 self._rev = self.__class__("".join(L))
2268 return self._rev
2269 s = madstring("abcdefghijklmnopqrstuvwxyz")
2270 vereq(s, "abcdefghijklmnopqrstuvwxyz")
2271 vereq(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2272 vereq(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2273 for i in range(256):
2274 s = madstring("".join(map(chr, range(i))))
2275 t = s.rev()
2276 u = t.rev()
2277 vereq(u, s)
2278 s = madstring("12345")
2279 vereq(str(s), "12345")
2280 verify(str(s).__class__ is str)
2282 base = "\x00" * 5
2283 s = madstring(base)
2284 vereq(s, base)
2285 vereq(str(s), base)
2286 verify(str(s).__class__ is str)
2287 vereq(hash(s), hash(base))
2288 vereq({s: 1}[base], 1)
2289 vereq({base: 1}[s], 1)
2290 verify((s + "").__class__ is str)
2291 vereq(s + "", base)
2292 verify(("" + s).__class__ is str)
2293 vereq("" + s, base)
2294 verify((s * 0).__class__ is str)
2295 vereq(s * 0, "")
2296 verify((s * 1).__class__ is str)
2297 vereq(s * 1, base)
2298 verify((s * 2).__class__ is str)
2299 vereq(s * 2, base + base)
2300 verify(s[:].__class__ is str)
2301 vereq(s[:], base)
2302 verify(s[0:0].__class__ is str)
2303 vereq(s[0:0], "")
2304 verify(s.strip().__class__ is str)
2305 vereq(s.strip(), base)
2306 verify(s.lstrip().__class__ is str)
2307 vereq(s.lstrip(), base)
2308 verify(s.rstrip().__class__ is str)
2309 vereq(s.rstrip(), base)
2310 identitytab = ''.join([chr(i) for i in range(256)])
2311 verify(s.translate(identitytab).__class__ is str)
2312 vereq(s.translate(identitytab), base)
2313 verify(s.translate(identitytab, "x").__class__ is str)
2314 vereq(s.translate(identitytab, "x"), base)
2315 vereq(s.translate(identitytab, "\x00"), "")
2316 verify(s.replace("x", "x").__class__ is str)
2317 vereq(s.replace("x", "x"), base)
2318 verify(s.ljust(len(s)).__class__ is str)
2319 vereq(s.ljust(len(s)), base)
2320 verify(s.rjust(len(s)).__class__ is str)
2321 vereq(s.rjust(len(s)), base)
2322 verify(s.center(len(s)).__class__ is str)
2323 vereq(s.center(len(s)), base)
2324 verify(s.lower().__class__ is str)
2325 vereq(s.lower(), base)
2327 class madunicode(unicode):
2328 _rev = None
2329 def rev(self):
2330 if self._rev is not None:
2331 return self._rev
2332 L = list(self)
2333 L.reverse()
2334 self._rev = self.__class__(u"".join(L))
2335 return self._rev
2336 u = madunicode("ABCDEF")
2337 vereq(u, u"ABCDEF")
2338 vereq(u.rev(), madunicode(u"FEDCBA"))
2339 vereq(u.rev().rev(), madunicode(u"ABCDEF"))
2340 base = u"12345"
2341 u = madunicode(base)
2342 vereq(unicode(u), base)
2343 verify(unicode(u).__class__ is unicode)
2344 vereq(hash(u), hash(base))
2345 vereq({u: 1}[base], 1)
2346 vereq({base: 1}[u], 1)
2347 verify(u.strip().__class__ is unicode)
2348 vereq(u.strip(), base)
2349 verify(u.lstrip().__class__ is unicode)
2350 vereq(u.lstrip(), base)
2351 verify(u.rstrip().__class__ is unicode)
2352 vereq(u.rstrip(), base)
2353 verify(u.replace(u"x", u"x").__class__ is unicode)
2354 vereq(u.replace(u"x", u"x"), base)
2355 verify(u.replace(u"xy", u"xy").__class__ is unicode)
2356 vereq(u.replace(u"xy", u"xy"), base)
2357 verify(u.center(len(u)).__class__ is unicode)
2358 vereq(u.center(len(u)), base)
2359 verify(u.ljust(len(u)).__class__ is unicode)
2360 vereq(u.ljust(len(u)), base)
2361 verify(u.rjust(len(u)).__class__ is unicode)
2362 vereq(u.rjust(len(u)), base)
2363 verify(u.lower().__class__ is unicode)
2364 vereq(u.lower(), base)
2365 verify(u.upper().__class__ is unicode)
2366 vereq(u.upper(), base)
2367 verify(u.capitalize().__class__ is unicode)
2368 vereq(u.capitalize(), base)
2369 verify(u.title().__class__ is unicode)
2370 vereq(u.title(), base)
2371 verify((u + u"").__class__ is unicode)
2372 vereq(u + u"", base)
2373 verify((u"" + u).__class__ is unicode)
2374 vereq(u"" + u, base)
2375 verify((u * 0).__class__ is unicode)
2376 vereq(u * 0, u"")
2377 verify((u * 1).__class__ is unicode)
2378 vereq(u * 1, base)
2379 verify((u * 2).__class__ is unicode)
2380 vereq(u * 2, base + base)
2381 verify(u[:].__class__ is unicode)
2382 vereq(u[:], base)
2383 verify(u[0:0].__class__ is unicode)
2384 vereq(u[0:0], u"")
2386 class sublist(list):
2387 pass
2388 a = sublist(range(5))
2389 vereq(a, range(5))
2390 a.append("hello")
2391 vereq(a, range(5) + ["hello"])
2392 a[5] = 5
2393 vereq(a, range(6))
2394 a.extend(range(6, 20))
2395 vereq(a, range(20))
2396 a[-5:] = []
2397 vereq(a, range(15))
2398 del a[10:15]
2399 vereq(len(a), 10)
2400 vereq(a, range(10))
2401 vereq(list(a), range(10))
2402 vereq(a[0], 0)
2403 vereq(a[9], 9)
2404 vereq(a[-10], 0)
2405 vereq(a[-1], 9)
2406 vereq(a[:5], range(5))
2408 class CountedInput(file):
2409 """Counts lines read by self.readline().
2411 self.lineno is the 0-based ordinal of the last line read, up to
2412 a maximum of one greater than the number of lines in the file.
2414 self.ateof is true if and only if the final "" line has been read,
2415 at which point self.lineno stops incrementing, and further calls
2416 to readline() continue to return "".
2419 lineno = 0
2420 ateof = 0
2421 def readline(self):
2422 if self.ateof:
2423 return ""
2424 s = file.readline(self)
2425 # Next line works too.
2426 # s = super(CountedInput, self).readline()
2427 self.lineno += 1
2428 if s == "":
2429 self.ateof = 1
2430 return s
2432 f = file(name=TESTFN, mode='w')
2433 lines = ['a\n', 'b\n', 'c\n']
2434 try:
2435 f.writelines(lines)
2436 f.close()
2437 f = CountedInput(TESTFN)
2438 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2439 got = f.readline()
2440 vereq(expected, got)
2441 vereq(f.lineno, i)
2442 vereq(f.ateof, (i > len(lines)))
2443 f.close()
2444 finally:
2445 try:
2446 f.close()
2447 except:
2448 pass
2449 try:
2450 import os
2451 os.unlink(TESTFN)
2452 except:
2453 pass
2455 def keywords():
2456 if verbose:
2457 print "Testing keyword args to basic type constructors ..."
2458 vereq(int(x=1), 1)
2459 vereq(float(x=2), 2.0)
2460 vereq(long(x=3), 3L)
2461 vereq(complex(imag=42, real=666), complex(666, 42))
2462 vereq(str(object=500), '500')
2463 vereq(unicode(string='abc', errors='strict'), u'abc')
2464 vereq(tuple(sequence=range(3)), (0, 1, 2))
2465 vereq(list(sequence=(0, 1, 2)), range(3))
2466 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2468 for constructor in (int, float, long, complex, str, unicode,
2469 tuple, list, file):
2470 try:
2471 constructor(bogus_keyword_arg=1)
2472 except TypeError:
2473 pass
2474 else:
2475 raise TestFailed("expected TypeError from bogus keyword "
2476 "argument to %r" % constructor)
2478 def restricted():
2479 # XXX This test is disabled because rexec is not deemed safe
2480 return
2481 import rexec
2482 if verbose:
2483 print "Testing interaction with restricted execution ..."
2485 sandbox = rexec.RExec()
2487 code1 = """f = open(%r, 'w')""" % TESTFN
2488 code2 = """f = file(%r, 'w')""" % TESTFN
2489 code3 = """\
2490 f = open(%r)
2491 t = type(f) # a sneaky way to get the file() constructor
2492 f.close()
2493 f = t(%r, 'w') # rexec can't catch this by itself
2494 """ % (TESTFN, TESTFN)
2496 f = open(TESTFN, 'w') # Create the file so code3 can find it.
2497 f.close()
2499 try:
2500 for code in code1, code2, code3:
2501 try:
2502 sandbox.r_exec(code)
2503 except IOError, msg:
2504 if str(msg).find("restricted") >= 0:
2505 outcome = "OK"
2506 else:
2507 outcome = "got an exception, but not an expected one"
2508 else:
2509 outcome = "expected a restricted-execution exception"
2511 if outcome != "OK":
2512 raise TestFailed("%s, in %r" % (outcome, code))
2514 finally:
2515 try:
2516 import os
2517 os.unlink(TESTFN)
2518 except:
2519 pass
2521 def str_subclass_as_dict_key():
2522 if verbose:
2523 print "Testing a str subclass used as dict key .."
2525 class cistr(str):
2526 """Sublcass of str that computes __eq__ case-insensitively.
2528 Also computes a hash code of the string in canonical form.
2531 def __init__(self, value):
2532 self.canonical = value.lower()
2533 self.hashcode = hash(self.canonical)
2535 def __eq__(self, other):
2536 if not isinstance(other, cistr):
2537 other = cistr(other)
2538 return self.canonical == other.canonical
2540 def __hash__(self):
2541 return self.hashcode
2543 vereq(cistr('ABC'), 'abc')
2544 vereq('aBc', cistr('ABC'))
2545 vereq(str(cistr('ABC')), 'ABC')
2547 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2548 vereq(d[cistr('one')], 1)
2549 vereq(d[cistr('tWo')], 2)
2550 vereq(d[cistr('THrEE')], 3)
2551 verify(cistr('ONe') in d)
2552 vereq(d.get(cistr('thrEE')), 3)
2554 def classic_comparisons():
2555 if verbose: print "Testing classic comparisons..."
2556 class classic:
2557 pass
2558 for base in (classic, int, object):
2559 if verbose: print " (base = %s)" % base
2560 class C(base):
2561 def __init__(self, value):
2562 self.value = int(value)
2563 def __cmp__(self, other):
2564 if isinstance(other, C):
2565 return cmp(self.value, other.value)
2566 if isinstance(other, int) or isinstance(other, long):
2567 return cmp(self.value, other)
2568 return NotImplemented
2569 c1 = C(1)
2570 c2 = C(2)
2571 c3 = C(3)
2572 vereq(c1, 1)
2573 c = {1: c1, 2: c2, 3: c3}
2574 for x in 1, 2, 3:
2575 for y in 1, 2, 3:
2576 verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2577 for op in "<", "<=", "==", "!=", ">", ">=":
2578 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2579 "x=%d, y=%d" % (x, y))
2580 verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2581 verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2583 def rich_comparisons():
2584 if verbose:
2585 print "Testing rich comparisons..."
2586 class Z(complex):
2587 pass
2588 z = Z(1)
2589 vereq(z, 1+0j)
2590 vereq(1+0j, z)
2591 class ZZ(complex):
2592 def __eq__(self, other):
2593 try:
2594 return abs(self - other) <= 1e-6
2595 except:
2596 return NotImplemented
2597 zz = ZZ(1.0000003)
2598 vereq(zz, 1+0j)
2599 vereq(1+0j, zz)
2601 class classic:
2602 pass
2603 for base in (classic, int, object, list):
2604 if verbose: print " (base = %s)" % base
2605 class C(base):
2606 def __init__(self, value):
2607 self.value = int(value)
2608 def __cmp__(self, other):
2609 raise TestFailed, "shouldn't call __cmp__"
2610 def __eq__(self, other):
2611 if isinstance(other, C):
2612 return self.value == other.value
2613 if isinstance(other, int) or isinstance(other, long):
2614 return self.value == other
2615 return NotImplemented
2616 def __ne__(self, other):
2617 if isinstance(other, C):
2618 return self.value != other.value
2619 if isinstance(other, int) or isinstance(other, long):
2620 return self.value != other
2621 return NotImplemented
2622 def __lt__(self, other):
2623 if isinstance(other, C):
2624 return self.value < other.value
2625 if isinstance(other, int) or isinstance(other, long):
2626 return self.value < other
2627 return NotImplemented
2628 def __le__(self, other):
2629 if isinstance(other, C):
2630 return self.value <= other.value
2631 if isinstance(other, int) or isinstance(other, long):
2632 return self.value <= other
2633 return NotImplemented
2634 def __gt__(self, other):
2635 if isinstance(other, C):
2636 return self.value > other.value
2637 if isinstance(other, int) or isinstance(other, long):
2638 return self.value > other
2639 return NotImplemented
2640 def __ge__(self, other):
2641 if isinstance(other, C):
2642 return self.value >= other.value
2643 if isinstance(other, int) or isinstance(other, long):
2644 return self.value >= other
2645 return NotImplemented
2646 c1 = C(1)
2647 c2 = C(2)
2648 c3 = C(3)
2649 vereq(c1, 1)
2650 c = {1: c1, 2: c2, 3: c3}
2651 for x in 1, 2, 3:
2652 for y in 1, 2, 3:
2653 for op in "<", "<=", "==", "!=", ">", ">=":
2654 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2655 "x=%d, y=%d" % (x, y))
2656 verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
2657 "x=%d, y=%d" % (x, y))
2658 verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
2659 "x=%d, y=%d" % (x, y))
2661 def coercions():
2662 if verbose: print "Testing coercions..."
2663 class I(int): pass
2664 coerce(I(0), 0)
2665 coerce(0, I(0))
2666 class L(long): pass
2667 coerce(L(0), 0)
2668 coerce(L(0), 0L)
2669 coerce(0, L(0))
2670 coerce(0L, L(0))
2671 class F(float): pass
2672 coerce(F(0), 0)
2673 coerce(F(0), 0L)
2674 coerce(F(0), 0.)
2675 coerce(0, F(0))
2676 coerce(0L, F(0))
2677 coerce(0., F(0))
2678 class C(complex): pass
2679 coerce(C(0), 0)
2680 coerce(C(0), 0L)
2681 coerce(C(0), 0.)
2682 coerce(C(0), 0j)
2683 coerce(0, C(0))
2684 coerce(0L, C(0))
2685 coerce(0., C(0))
2686 coerce(0j, C(0))
2688 def descrdoc():
2689 if verbose: print "Testing descriptor doc strings..."
2690 def check(descr, what):
2691 vereq(descr.__doc__, what)
2692 check(file.closed, "True if the file is closed") # getset descriptor
2693 check(file.name, "file name") # member descriptor
2695 def setclass():
2696 if verbose: print "Testing __class__ assignment..."
2697 class C(object): pass
2698 class D(object): pass
2699 class E(object): pass
2700 class F(D, E): pass
2701 for cls in C, D, E, F:
2702 for cls2 in C, D, E, F:
2703 x = cls()
2704 x.__class__ = cls2
2705 verify(x.__class__ is cls2)
2706 x.__class__ = cls
2707 verify(x.__class__ is cls)
2708 def cant(x, C):
2709 try:
2710 x.__class__ = C
2711 except TypeError:
2712 pass
2713 else:
2714 raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
2715 try:
2716 delattr(x, "__class__")
2717 except TypeError:
2718 pass
2719 else:
2720 raise TestFailed, "shouldn't allow del %r.__class__" % x
2721 cant(C(), list)
2722 cant(list(), C)
2723 cant(C(), 1)
2724 cant(C(), object)
2725 cant(object(), list)
2726 cant(list(), object)
2727 class Int(int): __slots__ = []
2728 cant(2, Int)
2729 cant(Int(), int)
2730 cant(True, int)
2731 cant(2, bool)
2732 o = object()
2733 cant(o, type(1))
2734 cant(o, type(None))
2735 del o
2737 def setdict():
2738 if verbose: print "Testing __dict__ assignment..."
2739 class C(object): pass
2740 a = C()
2741 a.__dict__ = {'b': 1}
2742 vereq(a.b, 1)
2743 def cant(x, dict):
2744 try:
2745 x.__dict__ = dict
2746 except (AttributeError, TypeError):
2747 pass
2748 else:
2749 raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict)
2750 cant(a, None)
2751 cant(a, [])
2752 cant(a, 1)
2753 del a.__dict__ # Deleting __dict__ is allowed
2754 # Classes don't allow __dict__ assignment
2755 cant(C, {})
2757 def pickles():
2758 if verbose:
2759 print "Testing pickling and copying new-style classes and objects..."
2760 import pickle, cPickle
2762 def sorteditems(d):
2763 L = d.items()
2764 L.sort()
2765 return L
2767 global C
2768 class C(object):
2769 def __init__(self, a, b):
2770 super(C, self).__init__()
2771 self.a = a
2772 self.b = b
2773 def __repr__(self):
2774 return "C(%r, %r)" % (self.a, self.b)
2776 global C1
2777 class C1(list):
2778 def __new__(cls, a, b):
2779 return super(C1, cls).__new__(cls)
2780 def __getnewargs__(self):
2781 return (self.a, self.b)
2782 def __init__(self, a, b):
2783 self.a = a
2784 self.b = b
2785 def __repr__(self):
2786 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2788 global C2
2789 class C2(int):
2790 def __new__(cls, a, b, val=0):
2791 return super(C2, cls).__new__(cls, val)
2792 def __getnewargs__(self):
2793 return (self.a, self.b, int(self))
2794 def __init__(self, a, b, val=0):
2795 self.a = a
2796 self.b = b
2797 def __repr__(self):
2798 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2800 global C3
2801 class C3(object):
2802 def __init__(self, foo):
2803 self.foo = foo
2804 def __getstate__(self):
2805 return self.foo
2806 def __setstate__(self, foo):
2807 self.foo = foo
2809 global C4classic, C4
2810 class C4classic: # classic
2811 pass
2812 class C4(C4classic, object): # mixed inheritance
2813 pass
2815 for p in pickle, cPickle:
2816 for bin in 0, 1:
2817 if verbose:
2818 print p.__name__, ["text", "binary"][bin]
2820 for cls in C, C1, C2:
2821 s = p.dumps(cls, bin)
2822 cls2 = p.loads(s)
2823 verify(cls2 is cls)
2825 a = C1(1, 2); a.append(42); a.append(24)
2826 b = C2("hello", "world", 42)
2827 s = p.dumps((a, b), bin)
2828 x, y = p.loads(s)
2829 vereq(x.__class__, a.__class__)
2830 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2831 vereq(y.__class__, b.__class__)
2832 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
2833 vereq(repr(x), repr(a))
2834 vereq(repr(y), repr(b))
2835 if verbose:
2836 print "a = x =", a
2837 print "b = y =", b
2838 # Test for __getstate__ and __setstate__ on new style class
2839 u = C3(42)
2840 s = p.dumps(u, bin)
2841 v = p.loads(s)
2842 veris(u.__class__, v.__class__)
2843 vereq(u.foo, v.foo)
2844 # Test for picklability of hybrid class
2845 u = C4()
2846 u.foo = 42
2847 s = p.dumps(u, bin)
2848 v = p.loads(s)
2849 veris(u.__class__, v.__class__)
2850 vereq(u.foo, v.foo)
2852 # Testing copy.deepcopy()
2853 if verbose:
2854 print "deepcopy"
2855 import copy
2856 for cls in C, C1, C2:
2857 cls2 = copy.deepcopy(cls)
2858 verify(cls2 is cls)
2860 a = C1(1, 2); a.append(42); a.append(24)
2861 b = C2("hello", "world", 42)
2862 x, y = copy.deepcopy((a, b))
2863 vereq(x.__class__, a.__class__)
2864 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2865 vereq(y.__class__, b.__class__)
2866 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
2867 vereq(repr(x), repr(a))
2868 vereq(repr(y), repr(b))
2869 if verbose:
2870 print "a = x =", a
2871 print "b = y =", b
2873 def pickleslots():
2874 if verbose: print "Testing pickling of classes with __slots__ ..."
2875 import pickle, cPickle
2876 # Pickling of classes with __slots__ but without __getstate__ should fail
2877 global B, C, D, E
2878 class B(object):
2879 pass
2880 for base in [object, B]:
2881 class C(base):
2882 __slots__ = ['a']
2883 class D(C):
2884 pass
2885 try:
2886 pickle.dumps(C())
2887 except TypeError:
2888 pass
2889 else:
2890 raise TestFailed, "should fail: pickle C instance - %s" % base
2891 try:
2892 cPickle.dumps(C())
2893 except TypeError:
2894 pass
2895 else:
2896 raise TestFailed, "should fail: cPickle C instance - %s" % base
2897 try:
2898 pickle.dumps(C())
2899 except TypeError:
2900 pass
2901 else:
2902 raise TestFailed, "should fail: pickle D instance - %s" % base
2903 try:
2904 cPickle.dumps(D())
2905 except TypeError:
2906 pass
2907 else:
2908 raise TestFailed, "should fail: cPickle D instance - %s" % base
2909 # Give C a nice generic __getstate__ and __setstate__
2910 class C(base):
2911 __slots__ = ['a']
2912 def __getstate__(self):
2913 try:
2914 d = self.__dict__.copy()
2915 except AttributeError:
2916 d = {}
2917 for cls in self.__class__.__mro__:
2918 for sn in cls.__dict__.get('__slots__', ()):
2919 try:
2920 d[sn] = getattr(self, sn)
2921 except AttributeError:
2922 pass
2923 return d
2924 def __setstate__(self, d):
2925 for k, v in d.items():
2926 setattr(self, k, v)
2927 class D(C):
2928 pass
2929 # Now it should work
2930 x = C()
2931 y = pickle.loads(pickle.dumps(x))
2932 vereq(hasattr(y, 'a'), 0)
2933 y = cPickle.loads(cPickle.dumps(x))
2934 vereq(hasattr(y, 'a'), 0)
2935 x.a = 42
2936 y = pickle.loads(pickle.dumps(x))
2937 vereq(y.a, 42)
2938 y = cPickle.loads(cPickle.dumps(x))
2939 vereq(y.a, 42)
2940 x = D()
2941 x.a = 42
2942 x.b = 100
2943 y = pickle.loads(pickle.dumps(x))
2944 vereq(y.a + y.b, 142)
2945 y = cPickle.loads(cPickle.dumps(x))
2946 vereq(y.a + y.b, 142)
2947 # A subclass that adds a slot should also work
2948 class E(C):
2949 __slots__ = ['b']
2950 x = E()
2951 x.a = 42
2952 x.b = "foo"
2953 y = pickle.loads(pickle.dumps(x))
2954 vereq(y.a, x.a)
2955 vereq(y.b, x.b)
2956 y = cPickle.loads(cPickle.dumps(x))
2957 vereq(y.a, x.a)
2958 vereq(y.b, x.b)
2960 def copies():
2961 if verbose: print "Testing copy.copy() and copy.deepcopy()..."
2962 import copy
2963 class C(object):
2964 pass
2966 a = C()
2967 a.foo = 12
2968 b = copy.copy(a)
2969 vereq(b.__dict__, a.__dict__)
2971 a.bar = [1,2,3]
2972 c = copy.copy(a)
2973 vereq(c.bar, a.bar)
2974 verify(c.bar is a.bar)
2976 d = copy.deepcopy(a)
2977 vereq(d.__dict__, a.__dict__)
2978 a.bar.append(4)
2979 vereq(d.bar, [1,2,3])
2981 def binopoverride():
2982 if verbose: print "Testing overrides of binary operations..."
2983 class I(int):
2984 def __repr__(self):
2985 return "I(%r)" % int(self)
2986 def __add__(self, other):
2987 return I(int(self) + int(other))
2988 __radd__ = __add__
2989 def __pow__(self, other, mod=None):
2990 if mod is None:
2991 return I(pow(int(self), int(other)))
2992 else:
2993 return I(pow(int(self), int(other), int(mod)))
2994 def __rpow__(self, other, mod=None):
2995 if mod is None:
2996 return I(pow(int(other), int(self), mod))
2997 else:
2998 return I(pow(int(other), int(self), int(mod)))
3000 vereq(repr(I(1) + I(2)), "I(3)")
3001 vereq(repr(I(1) + 2), "I(3)")
3002 vereq(repr(1 + I(2)), "I(3)")
3003 vereq(repr(I(2) ** I(3)), "I(8)")
3004 vereq(repr(2 ** I(3)), "I(8)")
3005 vereq(repr(I(2) ** 3), "I(8)")
3006 vereq(repr(pow(I(2), I(3), I(5))), "I(3)")
3007 class S(str):
3008 def __eq__(self, other):
3009 return self.lower() == other.lower()
3011 def subclasspropagation():
3012 if verbose: print "Testing propagation of slot functions to subclasses..."
3013 class A(object):
3014 pass
3015 class B(A):
3016 pass
3017 class C(A):
3018 pass
3019 class D(B, C):
3020 pass
3021 d = D()
3022 vereq(hash(d), id(d))
3023 A.__hash__ = lambda self: 42
3024 vereq(hash(d), 42)
3025 C.__hash__ = lambda self: 314
3026 vereq(hash(d), 314)
3027 B.__hash__ = lambda self: 144
3028 vereq(hash(d), 144)
3029 D.__hash__ = lambda self: 100
3030 vereq(hash(d), 100)
3031 del D.__hash__
3032 vereq(hash(d), 144)
3033 del B.__hash__
3034 vereq(hash(d), 314)
3035 del C.__hash__
3036 vereq(hash(d), 42)
3037 del A.__hash__
3038 vereq(hash(d), id(d))
3039 d.foo = 42
3040 d.bar = 42
3041 vereq(d.foo, 42)
3042 vereq(d.bar, 42)
3043 def __getattribute__(self, name):
3044 if name == "foo":
3045 return 24
3046 return object.__getattribute__(self, name)
3047 A.__getattribute__ = __getattribute__
3048 vereq(d.foo, 24)
3049 vereq(d.bar, 42)
3050 def __getattr__(self, name):
3051 if name in ("spam", "foo", "bar"):
3052 return "hello"
3053 raise AttributeError, name
3054 B.__getattr__ = __getattr__
3055 vereq(d.spam, "hello")
3056 vereq(d.foo, 24)
3057 vereq(d.bar, 42)
3058 del A.__getattribute__
3059 vereq(d.foo, 42)
3060 del d.foo
3061 vereq(d.foo, "hello")
3062 vereq(d.bar, 42)
3063 del B.__getattr__
3064 try:
3065 d.foo
3066 except AttributeError:
3067 pass
3068 else:
3069 raise TestFailed, "d.foo should be undefined now"
3071 # Test a nasty bug in recurse_down_subclasses()
3072 import gc
3073 class A(object):
3074 pass
3075 class B(A):
3076 pass
3077 del B
3078 gc.collect()
3079 A.__setitem__ = lambda *a: None # crash
3081 def buffer_inherit():
3082 import binascii
3083 # SF bug [#470040] ParseTuple t# vs subclasses.
3084 if verbose:
3085 print "Testing that buffer interface is inherited ..."
3087 class MyStr(str):
3088 pass
3089 base = 'abc'
3090 m = MyStr(base)
3091 # b2a_hex uses the buffer interface to get its argument's value, via
3092 # PyArg_ParseTuple 't#' code.
3093 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3095 # It's not clear that unicode will continue to support the character
3096 # buffer interface, and this test will fail if that's taken away.
3097 class MyUni(unicode):
3098 pass
3099 base = u'abc'
3100 m = MyUni(base)
3101 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
3103 class MyInt(int):
3104 pass
3105 m = MyInt(42)
3106 try:
3107 binascii.b2a_hex(m)
3108 raise TestFailed('subclass of int should not have a buffer interface')
3109 except TypeError:
3110 pass
3112 def str_of_str_subclass():
3113 import binascii
3114 import cStringIO
3116 if verbose:
3117 print "Testing __str__ defined in subclass of str ..."
3119 class octetstring(str):
3120 def __str__(self):
3121 return binascii.b2a_hex(self)
3122 def __repr__(self):
3123 return self + " repr"
3125 o = octetstring('A')
3126 vereq(type(o), octetstring)
3127 vereq(type(str(o)), str)
3128 vereq(type(repr(o)), str)
3129 vereq(ord(o), 0x41)
3130 vereq(str(o), '41')
3131 vereq(repr(o), 'A repr')
3132 vereq(o.__str__(), '41')
3133 vereq(o.__repr__(), 'A repr')
3135 capture = cStringIO.StringIO()
3136 # Calling str() or not exercises different internal paths.
3137 print >> capture, o
3138 print >> capture, str(o)
3139 vereq(capture.getvalue(), '41\n41\n')
3140 capture.close()
3142 def kwdargs():
3143 if verbose: print "Testing keyword arguments to __init__, __call__..."
3144 def f(a): return a
3145 vereq(f.__call__(a=42), 42)
3146 a = []
3147 list.__init__(a, sequence=[0, 1, 2])
3148 vereq(a, [0, 1, 2])
3150 def delhook():
3151 if verbose: print "Testing __del__ hook..."
3152 log = []
3153 class C(object):
3154 def __del__(self):
3155 log.append(1)
3156 c = C()
3157 vereq(log, [])
3158 del c
3159 vereq(log, [1])
3161 class D(object): pass
3162 d = D()
3163 try: del d[0]
3164 except TypeError: pass
3165 else: raise TestFailed, "invalid del() didn't raise TypeError"
3167 def hashinherit():
3168 if verbose: print "Testing hash of mutable subclasses..."
3170 class mydict(dict):
3171 pass
3172 d = mydict()
3173 try:
3174 hash(d)
3175 except TypeError:
3176 pass
3177 else:
3178 raise TestFailed, "hash() of dict subclass should fail"
3180 class mylist(list):
3181 pass
3182 d = mylist()
3183 try:
3184 hash(d)
3185 except TypeError:
3186 pass
3187 else:
3188 raise TestFailed, "hash() of list subclass should fail"
3190 def strops():
3191 try: 'a' + 5
3192 except TypeError: pass
3193 else: raise TestFailed, "'' + 5 doesn't raise TypeError"
3195 try: ''.split('')
3196 except ValueError: pass
3197 else: raise TestFailed, "''.split('') doesn't raise ValueError"
3199 try: ''.join([0])
3200 except TypeError: pass
3201 else: raise TestFailed, "''.join([0]) doesn't raise TypeError"
3203 try: ''.rindex('5')
3204 except ValueError: pass
3205 else: raise TestFailed, "''.rindex('5') doesn't raise ValueError"
3207 try: '%(n)s' % None
3208 except TypeError: pass
3209 else: raise TestFailed, "'%(n)s' % None doesn't raise TypeError"
3211 try: '%(n' % {}
3212 except ValueError: pass
3213 else: raise TestFailed, "'%(n' % {} '' doesn't raise ValueError"
3215 try: '%*s' % ('abc')
3216 except TypeError: pass
3217 else: raise TestFailed, "'%*s' % ('abc') doesn't raise TypeError"
3219 try: '%*.*s' % ('abc', 5)
3220 except TypeError: pass
3221 else: raise TestFailed, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
3223 try: '%s' % (1, 2)
3224 except TypeError: pass
3225 else: raise TestFailed, "'%s' % (1, 2) doesn't raise TypeError"
3227 try: '%' % None
3228 except ValueError: pass
3229 else: raise TestFailed, "'%' % None doesn't raise ValueError"
3231 vereq('534253'.isdigit(), 1)
3232 vereq('534253x'.isdigit(), 0)
3233 vereq('%c' % 5, '\x05')
3234 vereq('%c' % '5', '5')
3236 def deepcopyrecursive():
3237 if verbose: print "Testing deepcopy of recursive objects..."
3238 class Node:
3239 pass
3240 a = Node()
3241 b = Node()
3242 a.b = b
3243 b.a = a
3244 z = deepcopy(a) # This blew up before
3246 def modules():
3247 if verbose: print "Testing uninitialized module objects..."
3248 from types import ModuleType as M
3249 m = M.__new__(M)
3250 str(m)
3251 vereq(hasattr(m, "__name__"), 0)
3252 vereq(hasattr(m, "__file__"), 0)
3253 vereq(hasattr(m, "foo"), 0)
3254 vereq(m.__dict__, None)
3255 m.foo = 1
3256 vereq(m.__dict__, {"foo": 1})
3258 def dictproxyiterkeys():
3259 class C(object):
3260 def meth(self):
3261 pass
3262 if verbose: print "Testing dict-proxy iterkeys..."
3263 keys = [ key for key in C.__dict__.iterkeys() ]
3264 keys.sort()
3265 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3267 def dictproxyitervalues():
3268 class C(object):
3269 def meth(self):
3270 pass
3271 if verbose: print "Testing dict-proxy itervalues..."
3272 values = [ values for values in C.__dict__.itervalues() ]
3273 vereq(len(values), 5)
3275 def dictproxyiteritems():
3276 class C(object):
3277 def meth(self):
3278 pass
3279 if verbose: print "Testing dict-proxy iteritems..."
3280 keys = [ key for (key, value) in C.__dict__.iteritems() ]
3281 keys.sort()
3282 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3284 def funnynew():
3285 if verbose: print "Testing __new__ returning something unexpected..."
3286 class C(object):
3287 def __new__(cls, arg):
3288 if isinstance(arg, str): return [1, 2, 3]
3289 elif isinstance(arg, int): return object.__new__(D)
3290 else: return object.__new__(cls)
3291 class D(C):
3292 def __init__(self, arg):
3293 self.foo = arg
3294 vereq(C("1"), [1, 2, 3])
3295 vereq(D("1"), [1, 2, 3])
3296 d = D(None)
3297 veris(d.foo, None)
3298 d = C(1)
3299 vereq(isinstance(d, D), True)
3300 vereq(d.foo, 1)
3301 d = D(1)
3302 vereq(isinstance(d, D), True)
3303 vereq(d.foo, 1)
3305 def imulbug():
3306 # SF bug 544647
3307 if verbose: print "Testing for __imul__ problems..."
3308 class C(object):
3309 def __imul__(self, other):
3310 return (self, other)
3311 x = C()
3312 y = x
3313 y *= 1.0
3314 vereq(y, (x, 1.0))
3315 y = x
3316 y *= 2
3317 vereq(y, (x, 2))
3318 y = x
3319 y *= 3L
3320 vereq(y, (x, 3L))
3321 y = x
3322 y *= 1L<<100
3323 vereq(y, (x, 1L<<100))
3324 y = x
3325 y *= None
3326 vereq(y, (x, None))
3327 y = x
3328 y *= "foo"
3329 vereq(y, (x, "foo"))
3331 def docdescriptor():
3332 # SF bug 542984
3333 if verbose: print "Testing __doc__ descriptor..."
3334 class DocDescr(object):
3335 def __get__(self, object, otype):
3336 if object:
3337 object = object.__class__.__name__ + ' instance'
3338 if otype:
3339 otype = otype.__name__
3340 return 'object=%s; type=%s' % (object, otype)
3341 class OldClass:
3342 __doc__ = DocDescr()
3343 class NewClass(object):
3344 __doc__ = DocDescr()
3345 vereq(OldClass.__doc__, 'object=None; type=OldClass')
3346 vereq(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3347 vereq(NewClass.__doc__, 'object=None; type=NewClass')
3348 vereq(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3350 def string_exceptions():
3351 if verbose:
3352 print "Testing string exceptions ..."
3354 # Ensure builtin strings work OK as exceptions.
3355 astring = "An exception string."
3356 try:
3357 raise astring
3358 except astring:
3359 pass
3360 else:
3361 raise TestFailed, "builtin string not usable as exception"
3363 # Ensure string subclass instances do not.
3364 class MyStr(str):
3365 pass
3367 newstring = MyStr("oops -- shouldn't work")
3368 try:
3369 raise newstring
3370 except TypeError:
3371 pass
3372 except:
3373 raise TestFailed, "string subclass allowed as exception"
3375 def copy_setstate():
3376 if verbose:
3377 print "Testing that copy.*copy() correctly uses __setstate__..."
3378 import copy
3379 class C(object):
3380 def __init__(self, foo=None):
3381 self.foo = foo
3382 self.__foo = foo
3383 def setfoo(self, foo=None):
3384 self.foo = foo
3385 def getfoo(self):
3386 return self.__foo
3387 def __getstate__(self):
3388 return [self.foo]
3389 def __setstate__(self, lst):
3390 assert len(lst) == 1
3391 self.__foo = self.foo = lst[0]
3392 a = C(42)
3393 a.setfoo(24)
3394 vereq(a.foo, 24)
3395 vereq(a.getfoo(), 42)
3396 b = copy.copy(a)
3397 vereq(b.foo, 24)
3398 vereq(b.getfoo(), 24)
3399 b = copy.deepcopy(a)
3400 vereq(b.foo, 24)
3401 vereq(b.getfoo(), 24)
3403 def slices():
3404 if verbose:
3405 print "Testing cases with slices and overridden __getitem__ ..."
3406 # Strings
3407 vereq("hello"[:4], "hell")
3408 vereq("hello"[slice(4)], "hell")
3409 vereq(str.__getitem__("hello", slice(4)), "hell")
3410 class S(str):
3411 def __getitem__(self, x):
3412 return str.__getitem__(self, x)
3413 vereq(S("hello")[:4], "hell")
3414 vereq(S("hello")[slice(4)], "hell")
3415 vereq(S("hello").__getitem__(slice(4)), "hell")
3416 # Tuples
3417 vereq((1,2,3)[:2], (1,2))
3418 vereq((1,2,3)[slice(2)], (1,2))
3419 vereq(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3420 class T(tuple):
3421 def __getitem__(self, x):
3422 return tuple.__getitem__(self, x)
3423 vereq(T((1,2,3))[:2], (1,2))
3424 vereq(T((1,2,3))[slice(2)], (1,2))
3425 vereq(T((1,2,3)).__getitem__(slice(2)), (1,2))
3426 # Lists
3427 vereq([1,2,3][:2], [1,2])
3428 vereq([1,2,3][slice(2)], [1,2])
3429 vereq(list.__getitem__([1,2,3], slice(2)), [1,2])
3430 class L(list):
3431 def __getitem__(self, x):
3432 return list.__getitem__(self, x)
3433 vereq(L([1,2,3])[:2], [1,2])
3434 vereq(L([1,2,3])[slice(2)], [1,2])
3435 vereq(L([1,2,3]).__getitem__(slice(2)), [1,2])
3436 # Now do lists and __setitem__
3437 a = L([1,2,3])
3438 a[slice(1, 3)] = [3,2]
3439 vereq(a, [1,3,2])
3440 a[slice(0, 2, 1)] = [3,1]
3441 vereq(a, [3,1,2])
3442 a.__setitem__(slice(1, 3), [2,1])
3443 vereq(a, [3,2,1])
3444 a.__setitem__(slice(0, 2, 1), [2,3])
3445 vereq(a, [2,3,1])
3447 def subtype_resurrection():
3448 if verbose:
3449 print "Testing resurrection of new-style instance..."
3451 class C(object):
3452 container = []
3454 def __del__(self):
3455 # resurrect the instance
3456 C.container.append(self)
3458 c = C()
3459 c.attr = 42
3460 # The most interesting thing here is whether this blows up, due to flawed
3461 # GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 bug).
3462 del c
3464 # If that didn't blow up, it's also interesting to see whether clearing
3465 # the last container slot works: that will attempt to delete c again,
3466 # which will cause c to get appended back to the container again "during"
3467 # the del.
3468 del C.container[-1]
3469 vereq(len(C.container), 1)
3470 vereq(C.container[-1].attr, 42)
3472 # Make c mortal again, so that the test framework with -l doesn't report
3473 # it as a leak.
3474 del C.__del__
3476 def slottrash():
3477 # Deallocating deeply nested slotted trash caused stack overflows
3478 if verbose:
3479 print "Testing slot trash..."
3480 class trash(object):
3481 __slots__ = ['x']
3482 def __init__(self, x):
3483 self.x = x
3484 o = None
3485 for i in xrange(50000):
3486 o = trash(o)
3487 del o
3489 def slotmultipleinheritance():
3490 # SF bug 575229, multiple inheritance w/ slots dumps core
3491 class A(object):
3492 __slots__=()
3493 class B(object):
3494 pass
3495 class C(A,B) :
3496 __slots__=()
3497 vereq(C.__basicsize__, B.__basicsize__)
3498 verify(hasattr(C, '__dict__'))
3499 verify(hasattr(C, '__weakref__'))
3500 C().x = 2
3502 def testrmul():
3503 # SF patch 592646
3504 if verbose:
3505 print "Testing correct invocation of __rmul__..."
3506 class C(object):
3507 def __mul__(self, other):
3508 return "mul"
3509 def __rmul__(self, other):
3510 return "rmul"
3511 a = C()
3512 vereq(a*2, "mul")
3513 vereq(a*2.2, "mul")
3514 vereq(2*a, "rmul")
3515 vereq(2.2*a, "rmul")
3517 def testipow():
3518 # [SF bug 620179]
3519 if verbose:
3520 print "Testing correct invocation of __ipow__..."
3521 class C(object):
3522 def __ipow__(self, other):
3523 pass
3524 a = C()
3525 a **= 2
3527 def do_this_first():
3528 if verbose:
3529 print "Testing SF bug 551412 ..."
3530 # This dumps core when SF bug 551412 isn't fixed --
3531 # but only when test_descr.py is run separately.
3532 # (That can't be helped -- as soon as PyType_Ready()
3533 # is called for PyLong_Type, the bug is gone.)
3534 class UserLong(object):
3535 def __pow__(self, *args):
3536 pass
3537 try:
3538 pow(0L, UserLong(), 0L)
3539 except:
3540 pass
3542 if verbose:
3543 print "Testing SF bug 570483..."
3544 # Another segfault only when run early
3545 # (before PyType_Ready(tuple) is called)
3546 type.mro(tuple)
3548 def test_mutable_bases():
3549 if verbose:
3550 print "Testing mutable bases..."
3551 # stuff that should work:
3552 class C(object):
3553 pass
3554 class C2(object):
3555 def __getattribute__(self, attr):
3556 if attr == 'a':
3557 return 2
3558 else:
3559 return super(C2, self).__getattribute__(attr)
3560 def meth(self):
3561 return 1
3562 class D(C):
3563 pass
3564 class E(D):
3565 pass
3566 d = D()
3567 e = E()
3568 D.__bases__ = (C,)
3569 D.__bases__ = (C2,)
3570 vereq(d.meth(), 1)
3571 vereq(e.meth(), 1)
3572 vereq(d.a, 2)
3573 vereq(e.a, 2)
3574 vereq(C2.__subclasses__(), [D])
3576 # stuff that shouldn't:
3577 class L(list):
3578 pass
3580 try:
3581 L.__bases__ = (dict,)
3582 except TypeError:
3583 pass
3584 else:
3585 raise TestFailed, "shouldn't turn list subclass into dict subclass"
3587 try:
3588 list.__bases__ = (dict,)
3589 except TypeError:
3590 pass
3591 else:
3592 raise TestFailed, "shouldn't be able to assign to list.__bases__"
3594 try:
3595 del D.__bases__
3596 except TypeError:
3597 pass
3598 else:
3599 raise TestFailed, "shouldn't be able to delete .__bases__"
3601 try:
3602 D.__bases__ = ()
3603 except TypeError, msg:
3604 if str(msg) == "a new-style class can't have only classic bases":
3605 raise TestFailed, "wrong error message for .__bases__ = ()"
3606 else:
3607 raise TestFailed, "shouldn't be able to set .__bases__ to ()"
3609 try:
3610 D.__bases__ = (D,)
3611 except TypeError:
3612 pass
3613 else:
3614 # actually, we'll have crashed by here...
3615 raise TestFailed, "shouldn't be able to create inheritance cycles"
3617 try:
3618 D.__bases__ = (C, C)
3619 except TypeError:
3620 pass
3621 else:
3622 raise TestFailed, "didn't detect repeated base classes"
3624 try:
3625 D.__bases__ = (E,)
3626 except TypeError:
3627 pass
3628 else:
3629 raise TestFailed, "shouldn't be able to create inheritance cycles"
3631 # let's throw a classic class into the mix:
3632 class Classic:
3633 def meth2(self):
3634 return 3
3636 D.__bases__ = (C, Classic)
3638 vereq(d.meth2(), 3)
3639 vereq(e.meth2(), 3)
3640 try:
3642 except AttributeError:
3643 pass
3644 else:
3645 raise TestFailed, "attribute should have vanished"
3647 try:
3648 D.__bases__ = (Classic,)
3649 except TypeError:
3650 pass
3651 else:
3652 raise TestFailed, "new-style class must have a new-style base"
3654 def test_mutable_bases_with_failing_mro():
3655 if verbose:
3656 print "Testing mutable bases with failing mro..."
3657 class WorkOnce(type):
3658 def __new__(self, name, bases, ns):
3659 self.flag = 0
3660 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3661 def mro(self):
3662 if self.flag > 0:
3663 raise RuntimeError, "bozo"
3664 else:
3665 self.flag += 1
3666 return type.mro(self)
3668 class WorkAlways(type):
3669 def mro(self):
3670 # this is here to make sure that .mro()s aren't called
3671 # with an exception set (which was possible at one point).
3672 # An error message will be printed in a debug build.
3673 # What's a good way to test for this?
3674 return type.mro(self)
3676 class C(object):
3677 pass
3679 class C2(object):
3680 pass
3682 class D(C):
3683 pass
3685 class E(D):
3686 pass
3688 class F(D):
3689 __metaclass__ = WorkOnce
3691 class G(D):
3692 __metaclass__ = WorkAlways
3694 # Immediate subclasses have their mro's adjusted in alphabetical
3695 # order, so E's will get adjusted before adjusting F's fails. We
3696 # check here that E's gets restored.
3698 E_mro_before = E.__mro__
3699 D_mro_before = D.__mro__
3701 try:
3702 D.__bases__ = (C2,)
3703 except RuntimeError:
3704 vereq(E.__mro__, E_mro_before)
3705 vereq(D.__mro__, D_mro_before)
3706 else:
3707 raise TestFailed, "exception not propagated"
3709 def test_mutable_bases_catch_mro_conflict():
3710 if verbose:
3711 print "Testing mutable bases catch mro conflict..."
3712 class A(object):
3713 pass
3715 class B(object):
3716 pass
3718 class C(A, B):
3719 pass
3721 class D(A, B):
3722 pass
3724 class E(C, D):
3725 pass
3727 try:
3728 C.__bases__ = (B, A)
3729 except TypeError:
3730 pass
3731 else:
3732 raise TestFailed, "didn't catch MRO conflict"
3734 def mutable_names():
3735 if verbose:
3736 print "Testing mutable names..."
3737 class C(object):
3738 pass
3740 # C.__module__ could be 'test_descr' or '__main__'
3741 mod = C.__module__
3743 C.__name__ = 'D'
3744 vereq((C.__module__, C.__name__), (mod, 'D'))
3746 C.__name__ = 'D.E'
3747 vereq((C.__module__, C.__name__), (mod, 'D.E'))
3749 def subclass_right_op():
3750 if verbose:
3751 print "Testing correct dispatch of subclass overloading __r<op>__..."
3753 # This code tests various cases where right-dispatch of a subclass
3754 # should be preferred over left-dispatch of a base class.
3756 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3758 class B(int):
3759 def __floordiv__(self, other):
3760 return "B.__floordiv__"
3761 def __rfloordiv__(self, other):
3762 return "B.__rfloordiv__"
3764 vereq(B(1) // 1, "B.__floordiv__")
3765 vereq(1 // B(1), "B.__rfloordiv__")
3767 # Case 2: subclass of object; this is just the baseline for case 3
3769 class C(object):
3770 def __floordiv__(self, other):
3771 return "C.__floordiv__"
3772 def __rfloordiv__(self, other):
3773 return "C.__rfloordiv__"
3775 vereq(C() // 1, "C.__floordiv__")
3776 vereq(1 // C(), "C.__rfloordiv__")
3778 # Case 3: subclass of new-style class; here it gets interesting
3780 class D(C):
3781 def __floordiv__(self, other):
3782 return "D.__floordiv__"
3783 def __rfloordiv__(self, other):
3784 return "D.__rfloordiv__"
3786 vereq(D() // C(), "D.__floordiv__")
3787 vereq(C() // D(), "D.__rfloordiv__")
3789 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3791 class E(C):
3792 pass
3794 vereq(E.__rfloordiv__, C.__rfloordiv__)
3796 vereq(E() // 1, "C.__floordiv__")
3797 vereq(1 // E(), "C.__rfloordiv__")
3798 vereq(E() // C(), "C.__floordiv__")
3799 vereq(C() // E(), "C.__floordiv__") # This one would fail
3801 def dict_type_with_metaclass():
3802 if verbose:
3803 print "Testing type of __dict__ when __metaclass__ set..."
3805 class B(object):
3806 pass
3807 class M(type):
3808 pass
3809 class C:
3810 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
3811 __metaclass__ = M
3812 veris(type(C.__dict__), type(B.__dict__))
3814 def meth_class_get():
3815 # Full coverage of descrobject.c::classmethod_get()
3816 if verbose:
3817 print "Testing __get__ method of METH_CLASS C methods..."
3818 # Baseline
3819 arg = [1, 2, 3]
3820 res = {1: None, 2: None, 3: None}
3821 vereq(dict.fromkeys(arg), res)
3822 vereq({}.fromkeys(arg), res)
3823 # Now get the descriptor
3824 descr = dict.__dict__["fromkeys"]
3825 # More baseline using the descriptor directly
3826 vereq(descr.__get__(None, dict)(arg), res)
3827 vereq(descr.__get__({})(arg), res)
3828 # Now check various error cases
3829 try:
3830 descr.__get__(None, None)
3831 except TypeError:
3832 pass
3833 else:
3834 raise TestFailed, "shouldn't have allowed descr.__get__(None, None)"
3835 try:
3836 descr.__get__(42)
3837 except TypeError:
3838 pass
3839 else:
3840 raise TestFailed, "shouldn't have allowed descr.__get__(42)"
3841 try:
3842 descr.__get__(None, 42)
3843 except TypeError:
3844 pass
3845 else:
3846 raise TestFailed, "shouldn't have allowed descr.__get__(None, 42)"
3847 try:
3848 descr.__get__(None, int)
3849 except TypeError:
3850 pass
3851 else:
3852 raise TestFailed, "shouldn't have allowed descr.__get__(None, int)"
3854 def isinst_isclass():
3855 if verbose:
3856 print "Testing proxy isinstance() and isclass()..."
3857 class Proxy(object):
3858 def __init__(self, obj):
3859 self.__obj = obj
3860 def __getattribute__(self, name):
3861 if name.startswith("_Proxy__"):
3862 return object.__getattribute__(self, name)
3863 else:
3864 return getattr(self.__obj, name)
3865 # Test with a classic class
3866 class C:
3867 pass
3868 a = C()
3869 pa = Proxy(a)
3870 verify(isinstance(a, C)) # Baseline
3871 verify(isinstance(pa, C)) # Test
3872 # Test with a classic subclass
3873 class D(C):
3874 pass
3875 a = D()
3876 pa = Proxy(a)
3877 verify(isinstance(a, C)) # Baseline
3878 verify(isinstance(pa, C)) # Test
3879 # Test with a new-style class
3880 class C(object):
3881 pass
3882 a = C()
3883 pa = Proxy(a)
3884 verify(isinstance(a, C)) # Baseline
3885 verify(isinstance(pa, C)) # Test
3886 # Test with a new-style subclass
3887 class D(C):
3888 pass
3889 a = D()
3890 pa = Proxy(a)
3891 verify(isinstance(a, C)) # Baseline
3892 verify(isinstance(pa, C)) # Test
3894 def proxysuper():
3895 if verbose:
3896 print "Testing super() for a proxy object..."
3897 class Proxy(object):
3898 def __init__(self, obj):
3899 self.__obj = obj
3900 def __getattribute__(self, name):
3901 if name.startswith("_Proxy__"):
3902 return object.__getattribute__(self, name)
3903 else:
3904 return getattr(self.__obj, name)
3906 class B(object):
3907 def f(self):
3908 return "B.f"
3910 class C(B):
3911 def f(self):
3912 return super(C, self).f() + "->C.f"
3914 obj = C()
3915 p = Proxy(obj)
3916 vereq(C.__dict__["f"](p), "B.f->C.f")
3918 def carloverre():
3919 if verbose:
3920 print "Testing prohibition of Carlo Verre's hack..."
3921 try:
3922 object.__setattr__(str, "foo", 42)
3923 except TypeError:
3924 pass
3925 else:
3926 raise TestFailed, "Carlo Verre __setattr__ suceeded!"
3927 try:
3928 object.__delattr__(str, "lower")
3929 except TypeError:
3930 pass
3931 else:
3932 raise TestFailed, "Carlo Verre __delattr__ succeeded!"
3934 def weakref_segfault():
3935 # SF 742911
3936 if verbose:
3937 print "Testing weakref segfault..."
3939 import weakref
3941 class Provoker:
3942 def __init__(self, referrent):
3943 self.ref = weakref.ref(referrent)
3945 def __del__(self):
3946 x = self.ref()
3948 class Oops(object):
3949 pass
3951 o = Oops()
3952 o.whatever = Provoker(o)
3953 del o
3955 # Fix SF #762455, segfault when sys.stdout is changed in getattr
3956 def filefault():
3957 if verbose:
3958 print "Testing sys.stdout is changed in getattr..."
3959 import sys
3960 class StdoutGuard:
3961 def __getattr__(self, attr):
3962 sys.stdout = sys.__stdout__
3963 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
3964 sys.stdout = StdoutGuard()
3965 try:
3966 print "Oops!"
3967 except RuntimeError:
3968 pass
3970 def vicious_descriptor_nonsense():
3971 # A potential segfault spotted by Thomas Wouters in mail to
3972 # python-dev 2003-04-17, turned into an example & fixed by Michael
3973 # Hudson just less than four months later...
3974 if verbose:
3975 print "Testing vicious_descriptor_nonsense..."
3977 class Evil(object):
3978 def __hash__(self):
3979 return hash('attr')
3980 def __eq__(self, other):
3981 del C.attr
3982 return 0
3984 class Descr(object):
3985 def __get__(self, ob, type=None):
3986 return 1
3988 class C(object):
3989 attr = Descr()
3991 c = C()
3992 c.__dict__[Evil()] = 0
3994 vereq(c.attr, 1)
3995 # this makes a crash more likely:
3996 import gc; gc.collect()
3997 vereq(hasattr(c, 'attr'), False)
3999 def test_init():
4000 # SF 1155938
4001 class Foo(object):
4002 def __init__(self):
4003 return 10
4004 try:
4005 Foo()
4006 except TypeError:
4007 pass
4008 else:
4009 raise TestFailed, "did not test __init__() for None return"
4011 def methodwrapper():
4012 # <type 'method-wrapper'> did not support any reflection before 2.5
4013 if verbose:
4014 print "Testing method-wrapper objects..."
4016 l = []
4017 vereq(l.__add__, l.__add__)
4018 verify(l.__add__ != [].__add__)
4019 verify(l.__add__.__name__ == '__add__')
4020 verify(l.__add__.__self__ is l)
4021 verify(l.__add__.__objclass__ is list)
4022 vereq(l.__add__.__doc__, list.__add__.__doc__)
4024 def notimplemented():
4025 # all binary methods should be able to return a NotImplemented
4026 if verbose:
4027 print "Testing NotImplemented..."
4029 import sys
4030 import types
4031 import operator
4033 def specialmethod(self, other):
4034 return NotImplemented
4036 def check(expr, x, y):
4037 try:
4038 exec expr in {'x': x, 'y': y, 'operator': operator}
4039 except TypeError:
4040 pass
4041 else:
4042 raise TestFailed("no TypeError from %r" % (expr,))
4044 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of TypeErrors
4045 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4046 # ValueErrors instead of TypeErrors
4047 for metaclass in [type, types.ClassType]:
4048 for name, expr, iexpr in [
4049 ('__add__', 'x + y', 'x += y'),
4050 ('__sub__', 'x - y', 'x -= y'),
4051 ('__mul__', 'x * y', 'x *= y'),
4052 ('__truediv__', 'operator.truediv(x, y)', None),
4053 ('__floordiv__', 'operator.floordiv(x, y)', None),
4054 ('__div__', 'x / y', 'x /= y'),
4055 ('__mod__', 'x % y', 'x %= y'),
4056 ('__divmod__', 'divmod(x, y)', None),
4057 ('__pow__', 'x ** y', 'x **= y'),
4058 ('__lshift__', 'x << y', 'x <<= y'),
4059 ('__rshift__', 'x >> y', 'x >>= y'),
4060 ('__and__', 'x & y', 'x &= y'),
4061 ('__or__', 'x | y', 'x |= y'),
4062 ('__xor__', 'x ^ y', 'x ^= y'),
4063 ('__coerce__', 'coerce(x, y)', None)]:
4064 if name == '__coerce__':
4065 rname = name
4066 else:
4067 rname = '__r' + name[2:]
4068 A = metaclass('A', (), {name: specialmethod})
4069 B = metaclass('B', (), {rname: specialmethod})
4070 a = A()
4071 b = B()
4072 check(expr, a, a)
4073 check(expr, a, b)
4074 check(expr, b, a)
4075 check(expr, b, b)
4076 check(expr, a, N1)
4077 check(expr, a, N2)
4078 check(expr, N1, b)
4079 check(expr, N2, b)
4080 if iexpr:
4081 check(iexpr, a, a)
4082 check(iexpr, a, b)
4083 check(iexpr, b, a)
4084 check(iexpr, b, b)
4085 check(iexpr, a, N1)
4086 check(iexpr, a, N2)
4087 iname = '__i' + name[2:]
4088 C = metaclass('C', (), {iname: specialmethod})
4089 c = C()
4090 check(iexpr, c, a)
4091 check(iexpr, c, b)
4092 check(iexpr, c, N1)
4093 check(iexpr, c, N2)
4095 def test_main():
4096 weakref_segfault() # Must be first, somehow
4097 do_this_first()
4098 class_docstrings()
4099 lists()
4100 dicts()
4101 dict_constructor()
4102 test_dir()
4103 ints()
4104 longs()
4105 floats()
4106 complexes()
4107 spamlists()
4108 spamdicts()
4109 pydicts()
4110 pylists()
4111 metaclass()
4112 pymods()
4113 multi()
4114 mro_disagreement()
4115 diamond()
4116 ex5()
4117 monotonicity()
4118 consistency_with_epg()
4119 objects()
4120 slots()
4121 slotspecials()
4122 dynamics()
4123 errors()
4124 classmethods()
4125 classmethods_in_c()
4126 staticmethods()
4127 staticmethods_in_c()
4128 classic()
4129 compattr()
4130 newslot()
4131 altmro()
4132 overloading()
4133 methods()
4134 specials()
4135 weakrefs()
4136 properties()
4137 supers()
4138 inherits()
4139 keywords()
4140 restricted()
4141 str_subclass_as_dict_key()
4142 classic_comparisons()
4143 rich_comparisons()
4144 coercions()
4145 descrdoc()
4146 setclass()
4147 setdict()
4148 pickles()
4149 copies()
4150 binopoverride()
4151 subclasspropagation()
4152 buffer_inherit()
4153 str_of_str_subclass()
4154 kwdargs()
4155 delhook()
4156 hashinherit()
4157 strops()
4158 deepcopyrecursive()
4159 modules()
4160 dictproxyiterkeys()
4161 dictproxyitervalues()
4162 dictproxyiteritems()
4163 pickleslots()
4164 funnynew()
4165 imulbug()
4166 docdescriptor()
4167 string_exceptions()
4168 copy_setstate()
4169 slices()
4170 subtype_resurrection()
4171 slottrash()
4172 slotmultipleinheritance()
4173 testrmul()
4174 testipow()
4175 test_mutable_bases()
4176 test_mutable_bases_with_failing_mro()
4177 test_mutable_bases_catch_mro_conflict()
4178 mutable_names()
4179 subclass_right_op()
4180 dict_type_with_metaclass()
4181 meth_class_get()
4182 isinst_isclass()
4183 proxysuper()
4184 carloverre()
4185 filefault()
4186 vicious_descriptor_nonsense()
4187 test_init()
4188 methodwrapper()
4189 notimplemented()
4191 if verbose: print "All OK"
4193 if __name__ == "__main__":
4194 test_main()