Fix the availability statement for the spawn*() functions to reflect the
[python/dscho.git] / Lib / test / test_descr.py
blobea987f223c7198d1bc601b150ebf39c6ce10b9b8
1 # Test enhancements related to descriptors and new-style classes
3 from test_support import verify, vereq, verbose, TestFailed, TESTFN
4 from copy import deepcopy
6 def veris(a, b):
7 if a is not b:
8 raise TestFailed, "%r is %r" % (a, b)
10 def testunop(a, res, expr="len(a)", meth="__len__"):
11 if verbose: print "checking", expr
12 dict = {'a': a}
13 vereq(eval(expr, dict), res)
14 t = type(a)
15 m = getattr(t, meth)
16 while meth not in t.__dict__:
17 t = t.__bases__[0]
18 vereq(m, t.__dict__[meth])
19 vereq(m(a), res)
20 bm = getattr(a, meth)
21 vereq(bm(), res)
23 def testbinop(a, b, res, expr="a+b", meth="__add__"):
24 if verbose: print "checking", expr
25 dict = {'a': a, 'b': b}
27 # XXX Hack so this passes before 2.3 when -Qnew is specified.
28 if meth == "__div__" and 1/2 == 0.5:
29 meth = "__truediv__"
31 vereq(eval(expr, dict), res)
32 t = type(a)
33 m = getattr(t, meth)
34 while meth not in t.__dict__:
35 t = t.__bases__[0]
36 vereq(m, t.__dict__[meth])
37 vereq(m(a, b), res)
38 bm = getattr(a, meth)
39 vereq(bm(b), res)
41 def testternop(a, b, c, res, expr="a[b:c]", meth="__getslice__"):
42 if verbose: print "checking", expr
43 dict = {'a': a, 'b': b, 'c': c}
44 vereq(eval(expr, dict), res)
45 t = type(a)
46 m = getattr(t, meth)
47 while meth not in t.__dict__:
48 t = t.__bases__[0]
49 vereq(m, t.__dict__[meth])
50 vereq(m(a, b, c), res)
51 bm = getattr(a, meth)
52 vereq(bm(b, c), res)
54 def testsetop(a, b, res, stmt="a+=b", meth="__iadd__"):
55 if verbose: print "checking", stmt
56 dict = {'a': deepcopy(a), 'b': b}
57 exec stmt in dict
58 vereq(dict['a'], res)
59 t = type(a)
60 m = getattr(t, meth)
61 while meth not in t.__dict__:
62 t = t.__bases__[0]
63 vereq(m, t.__dict__[meth])
64 dict['a'] = deepcopy(a)
65 m(dict['a'], b)
66 vereq(dict['a'], res)
67 dict['a'] = deepcopy(a)
68 bm = getattr(dict['a'], meth)
69 bm(b)
70 vereq(dict['a'], res)
72 def testset2op(a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
73 if verbose: print "checking", stmt
74 dict = {'a': deepcopy(a), 'b': b, 'c': c}
75 exec stmt in dict
76 vereq(dict['a'], res)
77 t = type(a)
78 m = getattr(t, meth)
79 while meth not in t.__dict__:
80 t = t.__bases__[0]
81 vereq(m, t.__dict__[meth])
82 dict['a'] = deepcopy(a)
83 m(dict['a'], b, c)
84 vereq(dict['a'], res)
85 dict['a'] = deepcopy(a)
86 bm = getattr(dict['a'], meth)
87 bm(b, c)
88 vereq(dict['a'], res)
90 def testset3op(a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
91 if verbose: print "checking", stmt
92 dict = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
93 exec stmt in dict
94 vereq(dict['a'], res)
95 t = type(a)
96 while meth not in t.__dict__:
97 t = t.__bases__[0]
98 m = getattr(t, meth)
99 vereq(m, t.__dict__[meth])
100 dict['a'] = deepcopy(a)
101 m(dict['a'], b, c, d)
102 vereq(dict['a'], res)
103 dict['a'] = deepcopy(a)
104 bm = getattr(dict['a'], meth)
105 bm(b, c, d)
106 vereq(dict['a'], res)
108 def class_docstrings():
109 class Classic:
110 "A classic docstring."
111 vereq(Classic.__doc__, "A classic docstring.")
112 vereq(Classic.__dict__['__doc__'], "A classic docstring.")
114 class Classic2:
115 pass
116 verify(Classic2.__doc__ is None)
118 class NewStatic(object):
119 "Another docstring."
120 vereq(NewStatic.__doc__, "Another docstring.")
121 vereq(NewStatic.__dict__['__doc__'], "Another docstring.")
123 class NewStatic2(object):
124 pass
125 verify(NewStatic2.__doc__ is None)
127 class NewDynamic(object):
128 "Another docstring."
129 vereq(NewDynamic.__doc__, "Another docstring.")
130 vereq(NewDynamic.__dict__['__doc__'], "Another docstring.")
132 class NewDynamic2(object):
133 pass
134 verify(NewDynamic2.__doc__ is None)
136 def lists():
137 if verbose: print "Testing list operations..."
138 testbinop([1], [2], [1,2], "a+b", "__add__")
139 testbinop([1,2,3], 2, 1, "b in a", "__contains__")
140 testbinop([1,2,3], 4, 0, "b in a", "__contains__")
141 testbinop([1,2,3], 1, 2, "a[b]", "__getitem__")
142 testternop([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
143 testsetop([1], [2], [1,2], "a+=b", "__iadd__")
144 testsetop([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
145 testunop([1,2,3], 3, "len(a)", "__len__")
146 testbinop([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
147 testbinop([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
148 testset2op([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
149 testset3op([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d", "__setslice__")
151 def dicts():
152 if verbose: print "Testing dict operations..."
153 testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
154 testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__")
155 testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__")
156 testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
157 d = {1:2,3:4}
158 l1 = []
159 for i in d.keys(): l1.append(i)
160 l = []
161 for i in iter(d): l.append(i)
162 vereq(l, l1)
163 l = []
164 for i in d.__iter__(): l.append(i)
165 vereq(l, l1)
166 l = []
167 for i in dict.__iter__(d): l.append(i)
168 vereq(l, l1)
169 d = {1:2, 3:4}
170 testunop(d, 2, "len(a)", "__len__")
171 vereq(eval(repr(d), {}), d)
172 vereq(eval(d.__repr__(), {}), d)
173 testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__")
175 def dict_constructor():
176 if verbose:
177 print "Testing dict constructor ..."
178 d = dict()
179 vereq(d, {})
180 d = dict({})
181 vereq(d, {})
182 d = dict(items={})
183 vereq(d, {})
184 d = dict({1: 2, 'a': 'b'})
185 vereq(d, {1: 2, 'a': 'b'})
186 vereq(d, dict(d.items()))
187 vereq(d, dict(items=d.iteritems()))
188 for badarg in 0, 0L, 0j, "0", [0], (0,):
189 try:
190 dict(badarg)
191 except TypeError:
192 pass
193 except ValueError:
194 if badarg == "0":
195 # It's a sequence, and its elements are also sequences (gotta
196 # love strings <wink>), but they aren't of length 2, so this
197 # one seemed better as a ValueError than a TypeError.
198 pass
199 else:
200 raise TestFailed("no TypeError from dict(%r)" % badarg)
201 else:
202 raise TestFailed("no TypeError from dict(%r)" % badarg)
203 try:
204 dict(senseless={})
205 except TypeError:
206 pass
207 else:
208 raise TestFailed("no TypeError from dict(senseless={})")
210 try:
211 dict({}, {})
212 except TypeError:
213 pass
214 else:
215 raise TestFailed("no TypeError from dict({}, {})")
217 class Mapping:
218 # Lacks a .keys() method; will be added later.
219 dict = {1:2, 3:4, 'a':1j}
221 try:
222 dict(Mapping())
223 except TypeError:
224 pass
225 else:
226 raise TestFailed("no TypeError from dict(incomplete mapping)")
228 Mapping.keys = lambda self: self.dict.keys()
229 Mapping.__getitem__ = lambda self, i: self.dict[i]
230 d = dict(items=Mapping())
231 vereq(d, Mapping.dict)
233 # Init from sequence of iterable objects, each producing a 2-sequence.
234 class AddressBookEntry:
235 def __init__(self, first, last):
236 self.first = first
237 self.last = last
238 def __iter__(self):
239 return iter([self.first, self.last])
241 d = dict([AddressBookEntry('Tim', 'Warsaw'),
242 AddressBookEntry('Barry', 'Peters'),
243 AddressBookEntry('Tim', 'Peters'),
244 AddressBookEntry('Barry', 'Warsaw')])
245 vereq(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
247 d = dict(zip(range(4), range(1, 5)))
248 vereq(d, dict([(i, i+1) for i in range(4)]))
250 # Bad sequence lengths.
251 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
252 try:
253 dict(bad)
254 except ValueError:
255 pass
256 else:
257 raise TestFailed("no ValueError from dict(%r)" % bad)
259 def test_dir():
260 if verbose:
261 print "Testing dir() ..."
262 junk = 12
263 vereq(dir(), ['junk'])
264 del junk
266 # Just make sure these don't blow up!
267 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir:
268 dir(arg)
270 # Try classic classes.
271 class C:
272 Cdata = 1
273 def Cmethod(self): pass
275 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
276 vereq(dir(C), cstuff)
277 verify('im_self' in dir(C.Cmethod))
279 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
280 vereq(dir(c), cstuff)
282 c.cdata = 2
283 c.cmethod = lambda self: 0
284 vereq(dir(c), cstuff + ['cdata', 'cmethod'])
285 verify('im_self' in dir(c.Cmethod))
287 class A(C):
288 Adata = 1
289 def Amethod(self): pass
291 astuff = ['Adata', 'Amethod'] + cstuff
292 vereq(dir(A), astuff)
293 verify('im_self' in dir(A.Amethod))
294 a = A()
295 vereq(dir(a), astuff)
296 verify('im_self' in dir(a.Amethod))
297 a.adata = 42
298 a.amethod = lambda self: 3
299 vereq(dir(a), astuff + ['adata', 'amethod'])
301 # The same, but with new-style classes. Since these have object as a
302 # base class, a lot more gets sucked in.
303 def interesting(strings):
304 return [s for s in strings if not s.startswith('_')]
306 class C(object):
307 Cdata = 1
308 def Cmethod(self): pass
310 cstuff = ['Cdata', 'Cmethod']
311 vereq(interesting(dir(C)), cstuff)
313 c = C()
314 vereq(interesting(dir(c)), cstuff)
315 verify('im_self' in dir(C.Cmethod))
317 c.cdata = 2
318 c.cmethod = lambda self: 0
319 vereq(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
320 verify('im_self' in dir(c.Cmethod))
322 class A(C):
323 Adata = 1
324 def Amethod(self): pass
326 astuff = ['Adata', 'Amethod'] + cstuff
327 vereq(interesting(dir(A)), astuff)
328 verify('im_self' in dir(A.Amethod))
329 a = A()
330 vereq(interesting(dir(a)), astuff)
331 a.adata = 42
332 a.amethod = lambda self: 3
333 vereq(interesting(dir(a)), astuff + ['adata', 'amethod'])
334 verify('im_self' in dir(a.Amethod))
336 # Try a module subclass.
337 import sys
338 class M(type(sys)):
339 pass
340 minstance = M()
341 minstance.b = 2
342 minstance.a = 1
343 vereq(dir(minstance), ['a', 'b'])
345 class M2(M):
346 def getdict(self):
347 return "Not a dict!"
348 __dict__ = property(getdict)
350 m2instance = M2()
351 m2instance.b = 2
352 m2instance.a = 1
353 vereq(m2instance.__dict__, "Not a dict!")
354 try:
355 dir(m2instance)
356 except TypeError:
357 pass
359 # Two essentially featureless objects, just inheriting stuff from
360 # object.
361 vereq(dir(None), dir(Ellipsis))
363 binops = {
364 'add': '+',
365 'sub': '-',
366 'mul': '*',
367 'div': '/',
368 'mod': '%',
369 'divmod': 'divmod',
370 'pow': '**',
371 'lshift': '<<',
372 'rshift': '>>',
373 'and': '&',
374 'xor': '^',
375 'or': '|',
376 'cmp': 'cmp',
377 'lt': '<',
378 'le': '<=',
379 'eq': '==',
380 'ne': '!=',
381 'gt': '>',
382 'ge': '>=',
385 for name, expr in binops.items():
386 if expr.islower():
387 expr = expr + "(a, b)"
388 else:
389 expr = 'a %s b' % expr
390 binops[name] = expr
392 unops = {
393 'pos': '+',
394 'neg': '-',
395 'abs': 'abs',
396 'invert': '~',
397 'int': 'int',
398 'long': 'long',
399 'float': 'float',
400 'oct': 'oct',
401 'hex': 'hex',
404 for name, expr in unops.items():
405 if expr.islower():
406 expr = expr + "(a)"
407 else:
408 expr = '%s a' % expr
409 unops[name] = expr
411 def numops(a, b, skip=[]):
412 dict = {'a': a, 'b': b}
413 for name, expr in binops.items():
414 if name not in skip:
415 name = "__%s__" % name
416 if hasattr(a, name):
417 res = eval(expr, dict)
418 testbinop(a, b, res, expr, name)
419 for name, expr in unops.items():
420 if name not in skip:
421 name = "__%s__" % name
422 if hasattr(a, name):
423 res = eval(expr, dict)
424 testunop(a, res, expr, name)
426 def ints():
427 if verbose: print "Testing int operations..."
428 numops(100, 3)
430 def longs():
431 if verbose: print "Testing long operations..."
432 numops(100L, 3L)
434 def floats():
435 if verbose: print "Testing float operations..."
436 numops(100.0, 3.0)
438 def complexes():
439 if verbose: print "Testing complex operations..."
440 numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float'])
441 class Number(complex):
442 __slots__ = ['prec']
443 def __new__(cls, *args, **kwds):
444 result = complex.__new__(cls, *args)
445 result.prec = kwds.get('prec', 12)
446 return result
447 def __repr__(self):
448 prec = self.prec
449 if self.imag == 0.0:
450 return "%.*g" % (prec, self.real)
451 if self.real == 0.0:
452 return "%.*gj" % (prec, self.imag)
453 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
454 __str__ = __repr__
456 a = Number(3.14, prec=6)
457 vereq(`a`, "3.14")
458 vereq(a.prec, 6)
460 a = Number(a, prec=2)
461 vereq(`a`, "3.1")
462 vereq(a.prec, 2)
464 a = Number(234.5)
465 vereq(`a`, "234.5")
466 vereq(a.prec, 12)
468 def spamlists():
469 if verbose: print "Testing spamlist operations..."
470 import copy, xxsubtype as spam
471 def spamlist(l, memo=None):
472 import xxsubtype as spam
473 return spam.spamlist(l)
474 # This is an ugly hack:
475 copy._deepcopy_dispatch[spam.spamlist] = spamlist
477 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
478 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
479 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
480 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
481 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
482 "a[b:c]", "__getslice__")
483 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
484 "a+=b", "__iadd__")
485 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
486 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
487 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
488 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
489 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
490 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
491 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
492 # Test subclassing
493 class C(spam.spamlist):
494 def foo(self): return 1
495 a = C()
496 vereq(a, [])
497 vereq(a.foo(), 1)
498 a.append(100)
499 vereq(a, [100])
500 vereq(a.getstate(), 0)
501 a.setstate(42)
502 vereq(a.getstate(), 42)
504 def spamdicts():
505 if verbose: print "Testing spamdict operations..."
506 import copy, xxsubtype as spam
507 def spamdict(d, memo=None):
508 import xxsubtype as spam
509 sd = spam.spamdict()
510 for k, v in d.items(): sd[k] = v
511 return sd
512 # This is an ugly hack:
513 copy._deepcopy_dispatch[spam.spamdict] = spamdict
515 testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
516 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
517 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
518 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
519 d = spamdict({1:2,3:4})
520 l1 = []
521 for i in d.keys(): l1.append(i)
522 l = []
523 for i in iter(d): l.append(i)
524 vereq(l, l1)
525 l = []
526 for i in d.__iter__(): l.append(i)
527 vereq(l, l1)
528 l = []
529 for i in type(spamdict({})).__iter__(d): l.append(i)
530 vereq(l, l1)
531 straightd = {1:2, 3:4}
532 spamd = spamdict(straightd)
533 testunop(spamd, 2, "len(a)", "__len__")
534 testunop(spamd, repr(straightd), "repr(a)", "__repr__")
535 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
536 "a[b]=c", "__setitem__")
537 # Test subclassing
538 class C(spam.spamdict):
539 def foo(self): return 1
540 a = C()
541 vereq(a.items(), [])
542 vereq(a.foo(), 1)
543 a['foo'] = 'bar'
544 vereq(a.items(), [('foo', 'bar')])
545 vereq(a.getstate(), 0)
546 a.setstate(100)
547 vereq(a.getstate(), 100)
549 def pydicts():
550 if verbose: print "Testing Python subclass of dict..."
551 verify(issubclass(dict, dict))
552 verify(isinstance({}, dict))
553 d = dict()
554 vereq(d, {})
555 verify(d.__class__ is dict)
556 verify(isinstance(d, dict))
557 class C(dict):
558 state = -1
559 def __init__(self, *a, **kw):
560 if a:
561 vereq(len(a), 1)
562 self.state = a[0]
563 if kw:
564 for k, v in kw.items(): self[v] = k
565 def __getitem__(self, key):
566 return self.get(key, 0)
567 def __setitem__(self, key, value):
568 verify(isinstance(key, type(0)))
569 dict.__setitem__(self, key, value)
570 def setstate(self, state):
571 self.state = state
572 def getstate(self):
573 return self.state
574 verify(issubclass(C, dict))
575 a1 = C(12)
576 vereq(a1.state, 12)
577 a2 = C(foo=1, bar=2)
578 vereq(a2[1] == 'foo' and a2[2], 'bar')
579 a = C()
580 vereq(a.state, -1)
581 vereq(a.getstate(), -1)
582 a.setstate(0)
583 vereq(a.state, 0)
584 vereq(a.getstate(), 0)
585 a.setstate(10)
586 vereq(a.state, 10)
587 vereq(a.getstate(), 10)
588 vereq(a[42], 0)
589 a[42] = 24
590 vereq(a[42], 24)
591 if verbose: print "pydict stress test ..."
592 N = 50
593 for i in range(N):
594 a[i] = C()
595 for j in range(N):
596 a[i][j] = i*j
597 for i in range(N):
598 for j in range(N):
599 vereq(a[i][j], i*j)
601 def pylists():
602 if verbose: print "Testing Python subclass of list..."
603 class C(list):
604 def __getitem__(self, i):
605 return list.__getitem__(self, i) + 100
606 def __getslice__(self, i, j):
607 return (i, j)
608 a = C()
609 a.extend([0,1,2])
610 vereq(a[0], 100)
611 vereq(a[1], 101)
612 vereq(a[2], 102)
613 vereq(a[100:200], (100,200))
615 def metaclass():
616 if verbose: print "Testing __metaclass__..."
617 class C:
618 __metaclass__ = type
619 def __init__(self):
620 self.__state = 0
621 def getstate(self):
622 return self.__state
623 def setstate(self, state):
624 self.__state = state
625 a = C()
626 vereq(a.getstate(), 0)
627 a.setstate(10)
628 vereq(a.getstate(), 10)
629 class D:
630 class __metaclass__(type):
631 def myself(cls): return cls
632 vereq(D.myself(), D)
633 d = D()
634 verify(d.__class__ is D)
635 class M1(type):
636 def __new__(cls, name, bases, dict):
637 dict['__spam__'] = 1
638 return type.__new__(cls, name, bases, dict)
639 class C:
640 __metaclass__ = M1
641 vereq(C.__spam__, 1)
642 c = C()
643 vereq(c.__spam__, 1)
645 class _instance(object):
646 pass
647 class M2(object):
648 def __new__(cls, name, bases, dict):
649 self = object.__new__(cls)
650 self.name = name
651 self.bases = bases
652 self.dict = dict
653 return self
654 __new__ = staticmethod(__new__)
655 def __call__(self):
656 it = _instance()
657 # Early binding of methods
658 for key in self.dict:
659 if key.startswith("__"):
660 continue
661 setattr(it, key, self.dict[key].__get__(it, self))
662 return it
663 class C:
664 __metaclass__ = M2
665 def spam(self):
666 return 42
667 vereq(C.name, 'C')
668 vereq(C.bases, ())
669 verify('spam' in C.dict)
670 c = C()
671 vereq(c.spam(), 42)
673 # More metaclass examples
675 class autosuper(type):
676 # Automatically add __super to the class
677 # This trick only works for dynamic classes
678 def __new__(metaclass, name, bases, dict):
679 cls = super(autosuper, metaclass).__new__(metaclass,
680 name, bases, dict)
681 # Name mangling for __super removes leading underscores
682 while name[:1] == "_":
683 name = name[1:]
684 if name:
685 name = "_%s__super" % name
686 else:
687 name = "__super"
688 setattr(cls, name, super(cls))
689 return cls
690 class A:
691 __metaclass__ = autosuper
692 def meth(self):
693 return "A"
694 class B(A):
695 def meth(self):
696 return "B" + self.__super.meth()
697 class C(A):
698 def meth(self):
699 return "C" + self.__super.meth()
700 class D(C, B):
701 def meth(self):
702 return "D" + self.__super.meth()
703 vereq(D().meth(), "DCBA")
704 class E(B, C):
705 def meth(self):
706 return "E" + self.__super.meth()
707 vereq(E().meth(), "EBCA")
709 class autoproperty(type):
710 # Automatically create property attributes when methods
711 # named _get_x and/or _set_x are found
712 def __new__(metaclass, name, bases, dict):
713 hits = {}
714 for key, val in dict.iteritems():
715 if key.startswith("_get_"):
716 key = key[5:]
717 get, set = hits.get(key, (None, None))
718 get = val
719 hits[key] = get, set
720 elif key.startswith("_set_"):
721 key = key[5:]
722 get, set = hits.get(key, (None, None))
723 set = val
724 hits[key] = get, set
725 for key, (get, set) in hits.iteritems():
726 dict[key] = property(get, set)
727 return super(autoproperty, metaclass).__new__(metaclass,
728 name, bases, dict)
729 class A:
730 __metaclass__ = autoproperty
731 def _get_x(self):
732 return -self.__x
733 def _set_x(self, x):
734 self.__x = -x
735 a = A()
736 verify(not hasattr(a, "x"))
737 a.x = 12
738 vereq(a.x, 12)
739 vereq(a._A__x, -12)
741 class multimetaclass(autoproperty, autosuper):
742 # Merge of multiple cooperating metaclasses
743 pass
744 class A:
745 __metaclass__ = multimetaclass
746 def _get_x(self):
747 return "A"
748 class B(A):
749 def _get_x(self):
750 return "B" + self.__super._get_x()
751 class C(A):
752 def _get_x(self):
753 return "C" + self.__super._get_x()
754 class D(C, B):
755 def _get_x(self):
756 return "D" + self.__super._get_x()
757 vereq(D().x, "DCBA")
759 # Make sure type(x) doesn't call x.__class__.__init__
760 class T(type):
761 counter = 0
762 def __init__(self, *args):
763 T.counter += 1
764 class C:
765 __metaclass__ = T
766 vereq(T.counter, 1)
767 a = C()
768 vereq(type(a), C)
769 vereq(T.counter, 1)
771 class C(object): pass
772 c = C()
773 try: c()
774 except TypeError: pass
775 else: raise TestError, "calling object w/o call method should raise TypeError"
777 def pymods():
778 if verbose: print "Testing Python subclass of module..."
779 log = []
780 import sys
781 MT = type(sys)
782 class MM(MT):
783 def __init__(self):
784 MT.__init__(self)
785 def __getattribute__(self, name):
786 log.append(("getattr", name))
787 return MT.__getattribute__(self, name)
788 def __setattr__(self, name, value):
789 log.append(("setattr", name, value))
790 MT.__setattr__(self, name, value)
791 def __delattr__(self, name):
792 log.append(("delattr", name))
793 MT.__delattr__(self, name)
794 a = MM()
795 a.foo = 12
796 x = a.foo
797 del a.foo
798 vereq(log, [("setattr", "foo", 12),
799 ("getattr", "foo"),
800 ("delattr", "foo")])
802 def multi():
803 if verbose: print "Testing multiple inheritance..."
804 class C(object):
805 def __init__(self):
806 self.__state = 0
807 def getstate(self):
808 return self.__state
809 def setstate(self, state):
810 self.__state = state
811 a = C()
812 vereq(a.getstate(), 0)
813 a.setstate(10)
814 vereq(a.getstate(), 10)
815 class D(dict, C):
816 def __init__(self):
817 type({}).__init__(self)
818 C.__init__(self)
819 d = D()
820 vereq(d.keys(), [])
821 d["hello"] = "world"
822 vereq(d.items(), [("hello", "world")])
823 vereq(d["hello"], "world")
824 vereq(d.getstate(), 0)
825 d.setstate(10)
826 vereq(d.getstate(), 10)
827 vereq(D.__mro__, (D, dict, C, object))
829 # SF bug #442833
830 class Node(object):
831 def __int__(self):
832 return int(self.foo())
833 def foo(self):
834 return "23"
835 class Frag(Node, list):
836 def foo(self):
837 return "42"
838 vereq(Node().__int__(), 23)
839 vereq(int(Node()), 23)
840 vereq(Frag().__int__(), 42)
841 vereq(int(Frag()), 42)
843 # MI mixing classic and new-style classes.
845 class A:
846 x = 1
848 class B(A):
849 pass
851 class C(A):
852 x = 2
854 class D(B, C):
855 pass
856 vereq(D.x, 1)
858 # Classic MRO is preserved for a classic base class.
859 class E(D, object):
860 pass
861 vereq(E.__mro__, (E, D, B, A, C, object))
862 vereq(E.x, 1)
864 # But with a mix of classic bases, their MROs are combined using
865 # new-style MRO.
866 class F(B, C, object):
867 pass
868 vereq(F.__mro__, (F, B, C, A, object))
869 vereq(F.x, 2)
871 # Try something else.
872 class C:
873 def cmethod(self):
874 return "C a"
875 def all_method(self):
876 return "C b"
878 class M1(C, object):
879 def m1method(self):
880 return "M1 a"
881 def all_method(self):
882 return "M1 b"
884 vereq(M1.__mro__, (M1, C, object))
885 m = M1()
886 vereq(m.cmethod(), "C a")
887 vereq(m.m1method(), "M1 a")
888 vereq(m.all_method(), "M1 b")
890 class D(C):
891 def dmethod(self):
892 return "D a"
893 def all_method(self):
894 return "D b"
896 class M2(object, D):
897 def m2method(self):
898 return "M2 a"
899 def all_method(self):
900 return "M2 b"
902 vereq(M2.__mro__, (M2, object, D, C))
903 m = M2()
904 vereq(m.cmethod(), "C a")
905 vereq(m.dmethod(), "D a")
906 vereq(m.m2method(), "M2 a")
907 vereq(m.all_method(), "M2 b")
909 class M3(M1, object, M2):
910 def m3method(self):
911 return "M3 a"
912 def all_method(self):
913 return "M3 b"
914 # XXX Expected this (the commented-out result):
915 # vereq(M3.__mro__, (M3, M1, M2, object, D, C))
916 vereq(M3.__mro__, (M3, M1, M2, D, C, object)) # XXX ?
917 m = M3()
918 vereq(m.cmethod(), "C a")
919 vereq(m.dmethod(), "D a")
920 vereq(m.m1method(), "M1 a")
921 vereq(m.m2method(), "M2 a")
922 vereq(m.m3method(), "M3 a")
923 vereq(m.all_method(), "M3 b")
925 class Classic:
926 pass
927 try:
928 class New(Classic):
929 __metaclass__ = type
930 except TypeError:
931 pass
932 else:
933 raise TestFailed, "new class with only classic bases - shouldn't be"
935 def diamond():
936 if verbose: print "Testing multiple inheritance special cases..."
937 class A(object):
938 def spam(self): return "A"
939 vereq(A().spam(), "A")
940 class B(A):
941 def boo(self): return "B"
942 def spam(self): return "B"
943 vereq(B().spam(), "B")
944 vereq(B().boo(), "B")
945 class C(A):
946 def boo(self): return "C"
947 vereq(C().spam(), "A")
948 vereq(C().boo(), "C")
949 class D(B, C): pass
950 vereq(D().spam(), "B")
951 vereq(D().boo(), "B")
952 vereq(D.__mro__, (D, B, C, A, object))
953 class E(C, B): pass
954 vereq(E().spam(), "B")
955 vereq(E().boo(), "C")
956 vereq(E.__mro__, (E, C, B, A, object))
957 class F(D, E): pass
958 vereq(F().spam(), "B")
959 vereq(F().boo(), "B")
960 vereq(F.__mro__, (F, D, E, B, C, A, object))
961 class G(E, D): pass
962 vereq(G().spam(), "B")
963 vereq(G().boo(), "C")
964 vereq(G.__mro__, (G, E, D, C, B, A, object))
966 def objects():
967 if verbose: print "Testing object class..."
968 a = object()
969 vereq(a.__class__, object)
970 vereq(type(a), object)
971 b = object()
972 verify(a is not b)
973 verify(not hasattr(a, "foo"))
974 try:
975 a.foo = 12
976 except (AttributeError, TypeError):
977 pass
978 else:
979 verify(0, "object() should not allow setting a foo attribute")
980 verify(not hasattr(object(), "__dict__"))
982 class Cdict(object):
983 pass
984 x = Cdict()
985 vereq(x.__dict__, {})
986 x.foo = 1
987 vereq(x.foo, 1)
988 vereq(x.__dict__, {'foo': 1})
990 def slots():
991 if verbose: print "Testing __slots__..."
992 class C0(object):
993 __slots__ = []
994 x = C0()
995 verify(not hasattr(x, "__dict__"))
996 verify(not hasattr(x, "foo"))
998 class C1(object):
999 __slots__ = ['a']
1000 x = C1()
1001 verify(not hasattr(x, "__dict__"))
1002 verify(not hasattr(x, "a"))
1003 x.a = 1
1004 vereq(x.a, 1)
1005 x.a = None
1006 veris(x.a, None)
1007 del x.a
1008 verify(not hasattr(x, "a"))
1010 class C3(object):
1011 __slots__ = ['a', 'b', 'c']
1012 x = C3()
1013 verify(not hasattr(x, "__dict__"))
1014 verify(not hasattr(x, 'a'))
1015 verify(not hasattr(x, 'b'))
1016 verify(not hasattr(x, 'c'))
1017 x.a = 1
1018 x.b = 2
1019 x.c = 3
1020 vereq(x.a, 1)
1021 vereq(x.b, 2)
1022 vereq(x.c, 3)
1024 # Test leaks
1025 class Counted(object):
1026 counter = 0 # counts the number of instances alive
1027 def __init__(self):
1028 Counted.counter += 1
1029 def __del__(self):
1030 Counted.counter -= 1
1031 class C(object):
1032 __slots__ = ['a', 'b', 'c']
1033 x = C()
1034 x.a = Counted()
1035 x.b = Counted()
1036 x.c = Counted()
1037 vereq(Counted.counter, 3)
1038 del x
1039 vereq(Counted.counter, 0)
1040 class D(C):
1041 pass
1042 x = D()
1043 x.a = Counted()
1044 x.z = Counted()
1045 vereq(Counted.counter, 2)
1046 del x
1047 vereq(Counted.counter, 0)
1048 class E(D):
1049 __slots__ = ['e']
1050 x = E()
1051 x.a = Counted()
1052 x.z = Counted()
1053 x.e = Counted()
1054 vereq(Counted.counter, 3)
1055 del x
1056 vereq(Counted.counter, 0)
1058 def dynamics():
1059 if verbose: print "Testing class attribute propagation..."
1060 class D(object):
1061 pass
1062 class E(D):
1063 pass
1064 class F(D):
1065 pass
1066 D.foo = 1
1067 vereq(D.foo, 1)
1068 # Test that dynamic attributes are inherited
1069 vereq(E.foo, 1)
1070 vereq(F.foo, 1)
1071 # Test dynamic instances
1072 class C(object):
1073 pass
1074 a = C()
1075 verify(not hasattr(a, "foobar"))
1076 C.foobar = 2
1077 vereq(a.foobar, 2)
1078 C.method = lambda self: 42
1079 vereq(a.method(), 42)
1080 C.__repr__ = lambda self: "C()"
1081 vereq(repr(a), "C()")
1082 C.__int__ = lambda self: 100
1083 vereq(int(a), 100)
1084 vereq(a.foobar, 2)
1085 verify(not hasattr(a, "spam"))
1086 def mygetattr(self, name):
1087 if name == "spam":
1088 return "spam"
1089 raise AttributeError
1090 C.__getattr__ = mygetattr
1091 vereq(a.spam, "spam")
1092 a.new = 12
1093 vereq(a.new, 12)
1094 def mysetattr(self, name, value):
1095 if name == "spam":
1096 raise AttributeError
1097 return object.__setattr__(self, name, value)
1098 C.__setattr__ = mysetattr
1099 try:
1100 a.spam = "not spam"
1101 except AttributeError:
1102 pass
1103 else:
1104 verify(0, "expected AttributeError")
1105 vereq(a.spam, "spam")
1106 class D(C):
1107 pass
1108 d = D()
1109 d.foo = 1
1110 vereq(d.foo, 1)
1112 # Test handling of int*seq and seq*int
1113 class I(int):
1114 pass
1115 vereq("a"*I(2), "aa")
1116 vereq(I(2)*"a", "aa")
1117 vereq(2*I(3), 6)
1118 vereq(I(3)*2, 6)
1119 vereq(I(3)*I(2), 6)
1121 # Test handling of long*seq and seq*long
1122 class L(long):
1123 pass
1124 vereq("a"*L(2L), "aa")
1125 vereq(L(2L)*"a", "aa")
1126 vereq(2*L(3), 6)
1127 vereq(L(3)*2, 6)
1128 vereq(L(3)*L(2), 6)
1130 # Test comparison of classes with dynamic metaclasses
1131 class dynamicmetaclass(type):
1132 pass
1133 class someclass:
1134 __metaclass__ = dynamicmetaclass
1135 verify(someclass != object)
1137 def errors():
1138 if verbose: print "Testing errors..."
1140 try:
1141 class C(list, dict):
1142 pass
1143 except TypeError:
1144 pass
1145 else:
1146 verify(0, "inheritance from both list and dict should be illegal")
1148 try:
1149 class C(object, None):
1150 pass
1151 except TypeError:
1152 pass
1153 else:
1154 verify(0, "inheritance from non-type should be illegal")
1155 class Classic:
1156 pass
1158 try:
1159 class C(type(len)):
1160 pass
1161 except TypeError:
1162 pass
1163 else:
1164 verify(0, "inheritance from CFunction should be illegal")
1166 try:
1167 class C(object):
1168 __slots__ = 1
1169 except TypeError:
1170 pass
1171 else:
1172 verify(0, "__slots__ = 1 should be illegal")
1174 try:
1175 class C(object):
1176 __slots__ = [1]
1177 except TypeError:
1178 pass
1179 else:
1180 verify(0, "__slots__ = [1] should be illegal")
1182 def classmethods():
1183 if verbose: print "Testing class methods..."
1184 class C(object):
1185 def foo(*a): return a
1186 goo = classmethod(foo)
1187 c = C()
1188 vereq(C.goo(1), (C, 1))
1189 vereq(c.goo(1), (C, 1))
1190 vereq(c.foo(1), (c, 1))
1191 class D(C):
1192 pass
1193 d = D()
1194 vereq(D.goo(1), (D, 1))
1195 vereq(d.goo(1), (D, 1))
1196 vereq(d.foo(1), (d, 1))
1197 vereq(D.foo(d, 1), (d, 1))
1199 def staticmethods():
1200 if verbose: print "Testing static methods..."
1201 class C(object):
1202 def foo(*a): return a
1203 goo = staticmethod(foo)
1204 c = C()
1205 vereq(C.goo(1), (1,))
1206 vereq(c.goo(1), (1,))
1207 vereq(c.foo(1), (c, 1,))
1208 class D(C):
1209 pass
1210 d = D()
1211 vereq(D.goo(1), (1,))
1212 vereq(d.goo(1), (1,))
1213 vereq(d.foo(1), (d, 1))
1214 vereq(D.foo(d, 1), (d, 1))
1216 def classic():
1217 if verbose: print "Testing classic classes..."
1218 class C:
1219 def foo(*a): return a
1220 goo = classmethod(foo)
1221 c = C()
1222 vereq(C.goo(1), (C, 1))
1223 vereq(c.goo(1), (C, 1))
1224 vereq(c.foo(1), (c, 1))
1225 class D(C):
1226 pass
1227 d = D()
1228 vereq(D.goo(1), (D, 1))
1229 vereq(d.goo(1), (D, 1))
1230 vereq(d.foo(1), (d, 1))
1231 vereq(D.foo(d, 1), (d, 1))
1232 class E: # *not* subclassing from C
1233 foo = C.foo
1234 vereq(E().foo, C.foo) # i.e., unbound
1235 verify(repr(C.foo.__get__(C())).startswith("<bound method "))
1237 def compattr():
1238 if verbose: print "Testing computed attributes..."
1239 class C(object):
1240 class computed_attribute(object):
1241 def __init__(self, get, set=None):
1242 self.__get = get
1243 self.__set = set
1244 def __get__(self, obj, type=None):
1245 return self.__get(obj)
1246 def __set__(self, obj, value):
1247 return self.__set(obj, value)
1248 def __init__(self):
1249 self.__x = 0
1250 def __get_x(self):
1251 x = self.__x
1252 self.__x = x+1
1253 return x
1254 def __set_x(self, x):
1255 self.__x = x
1256 x = computed_attribute(__get_x, __set_x)
1257 a = C()
1258 vereq(a.x, 0)
1259 vereq(a.x, 1)
1260 a.x = 10
1261 vereq(a.x, 10)
1262 vereq(a.x, 11)
1264 def newslot():
1265 if verbose: print "Testing __new__ slot override..."
1266 class C(list):
1267 def __new__(cls):
1268 self = list.__new__(cls)
1269 self.foo = 1
1270 return self
1271 def __init__(self):
1272 self.foo = self.foo + 2
1273 a = C()
1274 vereq(a.foo, 3)
1275 verify(a.__class__ is C)
1276 class D(C):
1277 pass
1278 b = D()
1279 vereq(b.foo, 3)
1280 verify(b.__class__ is D)
1282 def altmro():
1283 if verbose: print "Testing mro() and overriding it..."
1284 class A(object):
1285 def f(self): return "A"
1286 class B(A):
1287 pass
1288 class C(A):
1289 def f(self): return "C"
1290 class D(B, C):
1291 pass
1292 vereq(D.mro(), [D, B, C, A, object])
1293 vereq(D.__mro__, (D, B, C, A, object))
1294 vereq(D().f(), "C")
1295 class PerverseMetaType(type):
1296 def mro(cls):
1297 L = type.mro(cls)
1298 L.reverse()
1299 return L
1300 class X(A,B,C,D):
1301 __metaclass__ = PerverseMetaType
1302 vereq(X.__mro__, (object, A, C, B, D, X))
1303 vereq(X().f(), "A")
1305 def overloading():
1306 if verbose: print "Testing operator overloading..."
1308 class B(object):
1309 "Intermediate class because object doesn't have a __setattr__"
1311 class C(B):
1313 def __getattr__(self, name):
1314 if name == "foo":
1315 return ("getattr", name)
1316 else:
1317 raise AttributeError
1318 def __setattr__(self, name, value):
1319 if name == "foo":
1320 self.setattr = (name, value)
1321 else:
1322 return B.__setattr__(self, name, value)
1323 def __delattr__(self, name):
1324 if name == "foo":
1325 self.delattr = name
1326 else:
1327 return B.__delattr__(self, name)
1329 def __getitem__(self, key):
1330 return ("getitem", key)
1331 def __setitem__(self, key, value):
1332 self.setitem = (key, value)
1333 def __delitem__(self, key):
1334 self.delitem = key
1336 def __getslice__(self, i, j):
1337 return ("getslice", i, j)
1338 def __setslice__(self, i, j, value):
1339 self.setslice = (i, j, value)
1340 def __delslice__(self, i, j):
1341 self.delslice = (i, j)
1343 a = C()
1344 vereq(a.foo, ("getattr", "foo"))
1345 a.foo = 12
1346 vereq(a.setattr, ("foo", 12))
1347 del a.foo
1348 vereq(a.delattr, "foo")
1350 vereq(a[12], ("getitem", 12))
1351 a[12] = 21
1352 vereq(a.setitem, (12, 21))
1353 del a[12]
1354 vereq(a.delitem, 12)
1356 vereq(a[0:10], ("getslice", 0, 10))
1357 a[0:10] = "foo"
1358 vereq(a.setslice, (0, 10, "foo"))
1359 del a[0:10]
1360 vereq(a.delslice, (0, 10))
1362 def methods():
1363 if verbose: print "Testing methods..."
1364 class C(object):
1365 def __init__(self, x):
1366 self.x = x
1367 def foo(self):
1368 return self.x
1369 c1 = C(1)
1370 vereq(c1.foo(), 1)
1371 class D(C):
1372 boo = C.foo
1373 goo = c1.foo
1374 d2 = D(2)
1375 vereq(d2.foo(), 2)
1376 vereq(d2.boo(), 2)
1377 vereq(d2.goo(), 1)
1378 class E(object):
1379 foo = C.foo
1380 vereq(E().foo, C.foo) # i.e., unbound
1381 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
1383 def specials():
1384 # Test operators like __hash__ for which a built-in default exists
1385 if verbose: print "Testing special operators..."
1386 # Test the default behavior for static classes
1387 class C(object):
1388 def __getitem__(self, i):
1389 if 0 <= i < 10: return i
1390 raise IndexError
1391 c1 = C()
1392 c2 = C()
1393 verify(not not c1)
1394 vereq(hash(c1), id(c1))
1395 vereq(cmp(c1, c2), cmp(id(c1), id(c2)))
1396 vereq(c1, c1)
1397 verify(c1 != c2)
1398 verify(not c1 != c1)
1399 verify(not c1 == c2)
1400 # Note that the module name appears in str/repr, and that varies
1401 # depending on whether this test is run standalone or from a framework.
1402 verify(str(c1).find('C object at ') >= 0)
1403 vereq(str(c1), repr(c1))
1404 verify(-1 not in c1)
1405 for i in range(10):
1406 verify(i in c1)
1407 verify(10 not in c1)
1408 # Test the default behavior for dynamic classes
1409 class D(object):
1410 def __getitem__(self, i):
1411 if 0 <= i < 10: return i
1412 raise IndexError
1413 d1 = D()
1414 d2 = D()
1415 verify(not not d1)
1416 vereq(hash(d1), id(d1))
1417 vereq(cmp(d1, d2), cmp(id(d1), id(d2)))
1418 vereq(d1, d1)
1419 verify(d1 != d2)
1420 verify(not d1 != d1)
1421 verify(not d1 == d2)
1422 # Note that the module name appears in str/repr, and that varies
1423 # depending on whether this test is run standalone or from a framework.
1424 verify(str(d1).find('D object at ') >= 0)
1425 vereq(str(d1), repr(d1))
1426 verify(-1 not in d1)
1427 for i in range(10):
1428 verify(i in d1)
1429 verify(10 not in d1)
1430 # Test overridden behavior for static classes
1431 class Proxy(object):
1432 def __init__(self, x):
1433 self.x = x
1434 def __nonzero__(self):
1435 return not not self.x
1436 def __hash__(self):
1437 return hash(self.x)
1438 def __eq__(self, other):
1439 return self.x == other
1440 def __ne__(self, other):
1441 return self.x != other
1442 def __cmp__(self, other):
1443 return cmp(self.x, other.x)
1444 def __str__(self):
1445 return "Proxy:%s" % self.x
1446 def __repr__(self):
1447 return "Proxy(%r)" % self.x
1448 def __contains__(self, value):
1449 return value in self.x
1450 p0 = Proxy(0)
1451 p1 = Proxy(1)
1452 p_1 = Proxy(-1)
1453 verify(not p0)
1454 verify(not not p1)
1455 vereq(hash(p0), hash(0))
1456 vereq(p0, p0)
1457 verify(p0 != p1)
1458 verify(not p0 != p0)
1459 vereq(not p0, p1)
1460 vereq(cmp(p0, p1), -1)
1461 vereq(cmp(p0, p0), 0)
1462 vereq(cmp(p0, p_1), 1)
1463 vereq(str(p0), "Proxy:0")
1464 vereq(repr(p0), "Proxy(0)")
1465 p10 = Proxy(range(10))
1466 verify(-1 not in p10)
1467 for i in range(10):
1468 verify(i in p10)
1469 verify(10 not in p10)
1470 # Test overridden behavior for dynamic classes
1471 class DProxy(object):
1472 def __init__(self, x):
1473 self.x = x
1474 def __nonzero__(self):
1475 return not not self.x
1476 def __hash__(self):
1477 return hash(self.x)
1478 def __eq__(self, other):
1479 return self.x == other
1480 def __ne__(self, other):
1481 return self.x != other
1482 def __cmp__(self, other):
1483 return cmp(self.x, other.x)
1484 def __str__(self):
1485 return "DProxy:%s" % self.x
1486 def __repr__(self):
1487 return "DProxy(%r)" % self.x
1488 def __contains__(self, value):
1489 return value in self.x
1490 p0 = DProxy(0)
1491 p1 = DProxy(1)
1492 p_1 = DProxy(-1)
1493 verify(not p0)
1494 verify(not not p1)
1495 vereq(hash(p0), hash(0))
1496 vereq(p0, p0)
1497 verify(p0 != p1)
1498 verify(not p0 != p0)
1499 vereq(not p0, p1)
1500 vereq(cmp(p0, p1), -1)
1501 vereq(cmp(p0, p0), 0)
1502 vereq(cmp(p0, p_1), 1)
1503 vereq(str(p0), "DProxy:0")
1504 vereq(repr(p0), "DProxy(0)")
1505 p10 = DProxy(range(10))
1506 verify(-1 not in p10)
1507 for i in range(10):
1508 verify(i in p10)
1509 verify(10 not in p10)
1510 # Safety test for __cmp__
1511 def unsafecmp(a, b):
1512 try:
1513 a.__class__.__cmp__(a, b)
1514 except TypeError:
1515 pass
1516 else:
1517 raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
1518 a.__class__, a, b)
1519 unsafecmp(u"123", "123")
1520 unsafecmp("123", u"123")
1521 unsafecmp(1, 1.0)
1522 unsafecmp(1.0, 1)
1523 unsafecmp(1, 1L)
1524 unsafecmp(1L, 1)
1526 def weakrefs():
1527 if verbose: print "Testing weak references..."
1528 import weakref
1529 class C(object):
1530 pass
1531 c = C()
1532 r = weakref.ref(c)
1533 verify(r() is c)
1534 del c
1535 verify(r() is None)
1536 del r
1537 class NoWeak(object):
1538 __slots__ = ['foo']
1539 no = NoWeak()
1540 try:
1541 weakref.ref(no)
1542 except TypeError, msg:
1543 verify(str(msg).find("weak reference") >= 0)
1544 else:
1545 verify(0, "weakref.ref(no) should be illegal")
1546 class Weak(object):
1547 __slots__ = ['foo', '__weakref__']
1548 yes = Weak()
1549 r = weakref.ref(yes)
1550 verify(r() is yes)
1551 del yes
1552 verify(r() is None)
1553 del r
1555 def properties():
1556 if verbose: print "Testing property..."
1557 class C(object):
1558 def getx(self):
1559 return self.__x
1560 def setx(self, value):
1561 self.__x = value
1562 def delx(self):
1563 del self.__x
1564 x = property(getx, setx, delx, doc="I'm the x property.")
1565 a = C()
1566 verify(not hasattr(a, "x"))
1567 a.x = 42
1568 vereq(a._C__x, 42)
1569 vereq(a.x, 42)
1570 del a.x
1571 verify(not hasattr(a, "x"))
1572 verify(not hasattr(a, "_C__x"))
1573 C.x.__set__(a, 100)
1574 vereq(C.x.__get__(a), 100)
1575 ## C.x.__set__(a)
1576 ## verify(not hasattr(a, "x"))
1578 raw = C.__dict__['x']
1579 verify(isinstance(raw, property))
1581 attrs = dir(raw)
1582 verify("__doc__" in attrs)
1583 verify("fget" in attrs)
1584 verify("fset" in attrs)
1585 verify("fdel" in attrs)
1587 vereq(raw.__doc__, "I'm the x property.")
1588 verify(raw.fget is C.__dict__['getx'])
1589 verify(raw.fset is C.__dict__['setx'])
1590 verify(raw.fdel is C.__dict__['delx'])
1592 for attr in "__doc__", "fget", "fset", "fdel":
1593 try:
1594 setattr(raw, attr, 42)
1595 except TypeError, msg:
1596 if str(msg).find('readonly') < 0:
1597 raise TestFailed("when setting readonly attr %r on a "
1598 "property, got unexpected TypeError "
1599 "msg %r" % (attr, str(msg)))
1600 else:
1601 raise TestFailed("expected TypeError from trying to set "
1602 "readonly %r attr on a property" % attr)
1604 def supers():
1605 if verbose: print "Testing super..."
1607 class A(object):
1608 def meth(self, a):
1609 return "A(%r)" % a
1611 vereq(A().meth(1), "A(1)")
1613 class B(A):
1614 def __init__(self):
1615 self.__super = super(B, self)
1616 def meth(self, a):
1617 return "B(%r)" % a + self.__super.meth(a)
1619 vereq(B().meth(2), "B(2)A(2)")
1621 class C(A):
1622 def meth(self, a):
1623 return "C(%r)" % a + self.__super.meth(a)
1624 C._C__super = super(C)
1626 vereq(C().meth(3), "C(3)A(3)")
1628 class D(C, B):
1629 def meth(self, a):
1630 return "D(%r)" % a + super(D, self).meth(a)
1632 vereq(D().meth(4), "D(4)C(4)B(4)A(4)")
1634 # Test for subclassing super
1636 class mysuper(super):
1637 def __init__(self, *args):
1638 return super(mysuper, self).__init__(*args)
1640 class E(D):
1641 def meth(self, a):
1642 return "E(%r)" % a + mysuper(E, self).meth(a)
1644 vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
1646 class F(E):
1647 def meth(self, a):
1648 s = self.__super
1649 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
1650 F._F__super = mysuper(F)
1652 vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
1654 # Make sure certain errors are raised
1656 try:
1657 super(D, 42)
1658 except TypeError:
1659 pass
1660 else:
1661 raise TestFailed, "shouldn't allow super(D, 42)"
1663 try:
1664 super(D, C())
1665 except TypeError:
1666 pass
1667 else:
1668 raise TestFailed, "shouldn't allow super(D, C())"
1670 try:
1671 super(D).__get__(12)
1672 except TypeError:
1673 pass
1674 else:
1675 raise TestFailed, "shouldn't allow super(D).__get__(12)"
1677 try:
1678 super(D).__get__(C())
1679 except TypeError:
1680 pass
1681 else:
1682 raise TestFailed, "shouldn't allow super(D).__get__(C())"
1684 def inherits():
1685 if verbose: print "Testing inheritance from basic types..."
1687 class hexint(int):
1688 def __repr__(self):
1689 return hex(self)
1690 def __add__(self, other):
1691 return hexint(int.__add__(self, other))
1692 # (Note that overriding __radd__ doesn't work,
1693 # because the int type gets first dibs.)
1694 vereq(repr(hexint(7) + 9), "0x10")
1695 vereq(repr(hexint(1000) + 7), "0x3ef")
1696 a = hexint(12345)
1697 vereq(a, 12345)
1698 vereq(int(a), 12345)
1699 verify(int(a).__class__ is int)
1700 vereq(hash(a), hash(12345))
1701 verify((+a).__class__ is int)
1702 verify((a >> 0).__class__ is int)
1703 verify((a << 0).__class__ is int)
1704 verify((hexint(0) << 12).__class__ is int)
1705 verify((hexint(0) >> 12).__class__ is int)
1707 class octlong(long):
1708 __slots__ = []
1709 def __str__(self):
1710 s = oct(self)
1711 if s[-1] == 'L':
1712 s = s[:-1]
1713 return s
1714 def __add__(self, other):
1715 return self.__class__(super(octlong, self).__add__(other))
1716 __radd__ = __add__
1717 vereq(str(octlong(3) + 5), "010")
1718 # (Note that overriding __radd__ here only seems to work
1719 # because the example uses a short int left argument.)
1720 vereq(str(5 + octlong(3000)), "05675")
1721 a = octlong(12345)
1722 vereq(a, 12345L)
1723 vereq(long(a), 12345L)
1724 vereq(hash(a), hash(12345L))
1725 verify(long(a).__class__ is long)
1726 verify((+a).__class__ is long)
1727 verify((-a).__class__ is long)
1728 verify((-octlong(0)).__class__ is long)
1729 verify((a >> 0).__class__ is long)
1730 verify((a << 0).__class__ is long)
1731 verify((a - 0).__class__ is long)
1732 verify((a * 1).__class__ is long)
1733 verify((a ** 1).__class__ is long)
1734 verify((a // 1).__class__ is long)
1735 verify((1 * a).__class__ is long)
1736 verify((a | 0).__class__ is long)
1737 verify((a ^ 0).__class__ is long)
1738 verify((a & -1L).__class__ is long)
1739 verify((octlong(0) << 12).__class__ is long)
1740 verify((octlong(0) >> 12).__class__ is long)
1741 verify(abs(octlong(0)).__class__ is long)
1743 # Because octlong overrides __add__, we can't check the absence of +0
1744 # optimizations using octlong.
1745 class longclone(long):
1746 pass
1747 a = longclone(1)
1748 verify((a + 0).__class__ is long)
1749 verify((0 + a).__class__ is long)
1751 class precfloat(float):
1752 __slots__ = ['prec']
1753 def __init__(self, value=0.0, prec=12):
1754 self.prec = int(prec)
1755 float.__init__(value)
1756 def __repr__(self):
1757 return "%.*g" % (self.prec, self)
1758 vereq(repr(precfloat(1.1)), "1.1")
1759 a = precfloat(12345)
1760 vereq(a, 12345.0)
1761 vereq(float(a), 12345.0)
1762 verify(float(a).__class__ is float)
1763 vereq(hash(a), hash(12345.0))
1764 verify((+a).__class__ is float)
1766 class madcomplex(complex):
1767 def __repr__(self):
1768 return "%.17gj%+.17g" % (self.imag, self.real)
1769 a = madcomplex(-3, 4)
1770 vereq(repr(a), "4j-3")
1771 base = complex(-3, 4)
1772 veris(base.__class__, complex)
1773 vereq(a, base)
1774 vereq(complex(a), base)
1775 veris(complex(a).__class__, complex)
1776 a = madcomplex(a) # just trying another form of the constructor
1777 vereq(repr(a), "4j-3")
1778 vereq(a, base)
1779 vereq(complex(a), base)
1780 veris(complex(a).__class__, complex)
1781 vereq(hash(a), hash(base))
1782 veris((+a).__class__, complex)
1783 veris((a + 0).__class__, complex)
1784 vereq(a + 0, base)
1785 veris((a - 0).__class__, complex)
1786 vereq(a - 0, base)
1787 veris((a * 1).__class__, complex)
1788 vereq(a * 1, base)
1789 veris((a / 1).__class__, complex)
1790 vereq(a / 1, base)
1792 class madtuple(tuple):
1793 _rev = None
1794 def rev(self):
1795 if self._rev is not None:
1796 return self._rev
1797 L = list(self)
1798 L.reverse()
1799 self._rev = self.__class__(L)
1800 return self._rev
1801 a = madtuple((1,2,3,4,5,6,7,8,9,0))
1802 vereq(a, (1,2,3,4,5,6,7,8,9,0))
1803 vereq(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
1804 vereq(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
1805 for i in range(512):
1806 t = madtuple(range(i))
1807 u = t.rev()
1808 v = u.rev()
1809 vereq(v, t)
1810 a = madtuple((1,2,3,4,5))
1811 vereq(tuple(a), (1,2,3,4,5))
1812 verify(tuple(a).__class__ is tuple)
1813 vereq(hash(a), hash((1,2,3,4,5)))
1814 verify(a[:].__class__ is tuple)
1815 verify((a * 1).__class__ is tuple)
1816 verify((a * 0).__class__ is tuple)
1817 verify((a + ()).__class__ is tuple)
1818 a = madtuple(())
1819 vereq(tuple(a), ())
1820 verify(tuple(a).__class__ is tuple)
1821 verify((a + a).__class__ is tuple)
1822 verify((a * 0).__class__ is tuple)
1823 verify((a * 1).__class__ is tuple)
1824 verify((a * 2).__class__ is tuple)
1825 verify(a[:].__class__ is tuple)
1827 class madstring(str):
1828 _rev = None
1829 def rev(self):
1830 if self._rev is not None:
1831 return self._rev
1832 L = list(self)
1833 L.reverse()
1834 self._rev = self.__class__("".join(L))
1835 return self._rev
1836 s = madstring("abcdefghijklmnopqrstuvwxyz")
1837 vereq(s, "abcdefghijklmnopqrstuvwxyz")
1838 vereq(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
1839 vereq(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
1840 for i in range(256):
1841 s = madstring("".join(map(chr, range(i))))
1842 t = s.rev()
1843 u = t.rev()
1844 vereq(u, s)
1845 s = madstring("12345")
1846 vereq(str(s), "12345")
1847 verify(str(s).__class__ is str)
1849 base = "\x00" * 5
1850 s = madstring(base)
1851 vereq(s, base)
1852 vereq(str(s), base)
1853 verify(str(s).__class__ is str)
1854 vereq(hash(s), hash(base))
1855 vereq({s: 1}[base], 1)
1856 vereq({base: 1}[s], 1)
1857 verify((s + "").__class__ is str)
1858 vereq(s + "", base)
1859 verify(("" + s).__class__ is str)
1860 vereq("" + s, base)
1861 verify((s * 0).__class__ is str)
1862 vereq(s * 0, "")
1863 verify((s * 1).__class__ is str)
1864 vereq(s * 1, base)
1865 verify((s * 2).__class__ is str)
1866 vereq(s * 2, base + base)
1867 verify(s[:].__class__ is str)
1868 vereq(s[:], base)
1869 verify(s[0:0].__class__ is str)
1870 vereq(s[0:0], "")
1871 verify(s.strip().__class__ is str)
1872 vereq(s.strip(), base)
1873 verify(s.lstrip().__class__ is str)
1874 vereq(s.lstrip(), base)
1875 verify(s.rstrip().__class__ is str)
1876 vereq(s.rstrip(), base)
1877 identitytab = ''.join([chr(i) for i in range(256)])
1878 verify(s.translate(identitytab).__class__ is str)
1879 vereq(s.translate(identitytab), base)
1880 verify(s.translate(identitytab, "x").__class__ is str)
1881 vereq(s.translate(identitytab, "x"), base)
1882 vereq(s.translate(identitytab, "\x00"), "")
1883 verify(s.replace("x", "x").__class__ is str)
1884 vereq(s.replace("x", "x"), base)
1885 verify(s.ljust(len(s)).__class__ is str)
1886 vereq(s.ljust(len(s)), base)
1887 verify(s.rjust(len(s)).__class__ is str)
1888 vereq(s.rjust(len(s)), base)
1889 verify(s.center(len(s)).__class__ is str)
1890 vereq(s.center(len(s)), base)
1891 verify(s.lower().__class__ is str)
1892 vereq(s.lower(), base)
1894 s = madstring("x y")
1895 vereq(s, "x y")
1896 verify(intern(s).__class__ is str)
1897 verify(intern(s) is intern("x y"))
1898 vereq(intern(s), "x y")
1900 i = intern("y x")
1901 s = madstring("y x")
1902 vereq(s, i)
1903 verify(intern(s).__class__ is str)
1904 verify(intern(s) is i)
1906 s = madstring(i)
1907 verify(intern(s).__class__ is str)
1908 verify(intern(s) is i)
1910 class madunicode(unicode):
1911 _rev = None
1912 def rev(self):
1913 if self._rev is not None:
1914 return self._rev
1915 L = list(self)
1916 L.reverse()
1917 self._rev = self.__class__(u"".join(L))
1918 return self._rev
1919 u = madunicode("ABCDEF")
1920 vereq(u, u"ABCDEF")
1921 vereq(u.rev(), madunicode(u"FEDCBA"))
1922 vereq(u.rev().rev(), madunicode(u"ABCDEF"))
1923 base = u"12345"
1924 u = madunicode(base)
1925 vereq(unicode(u), base)
1926 verify(unicode(u).__class__ is unicode)
1927 vereq(hash(u), hash(base))
1928 vereq({u: 1}[base], 1)
1929 vereq({base: 1}[u], 1)
1930 verify(u.strip().__class__ is unicode)
1931 vereq(u.strip(), base)
1932 verify(u.lstrip().__class__ is unicode)
1933 vereq(u.lstrip(), base)
1934 verify(u.rstrip().__class__ is unicode)
1935 vereq(u.rstrip(), base)
1936 verify(u.replace(u"x", u"x").__class__ is unicode)
1937 vereq(u.replace(u"x", u"x"), base)
1938 verify(u.replace(u"xy", u"xy").__class__ is unicode)
1939 vereq(u.replace(u"xy", u"xy"), base)
1940 verify(u.center(len(u)).__class__ is unicode)
1941 vereq(u.center(len(u)), base)
1942 verify(u.ljust(len(u)).__class__ is unicode)
1943 vereq(u.ljust(len(u)), base)
1944 verify(u.rjust(len(u)).__class__ is unicode)
1945 vereq(u.rjust(len(u)), base)
1946 verify(u.lower().__class__ is unicode)
1947 vereq(u.lower(), base)
1948 verify(u.upper().__class__ is unicode)
1949 vereq(u.upper(), base)
1950 verify(u.capitalize().__class__ is unicode)
1951 vereq(u.capitalize(), base)
1952 verify(u.title().__class__ is unicode)
1953 vereq(u.title(), base)
1954 verify((u + u"").__class__ is unicode)
1955 vereq(u + u"", base)
1956 verify((u"" + u).__class__ is unicode)
1957 vereq(u"" + u, base)
1958 verify((u * 0).__class__ is unicode)
1959 vereq(u * 0, u"")
1960 verify((u * 1).__class__ is unicode)
1961 vereq(u * 1, base)
1962 verify((u * 2).__class__ is unicode)
1963 vereq(u * 2, base + base)
1964 verify(u[:].__class__ is unicode)
1965 vereq(u[:], base)
1966 verify(u[0:0].__class__ is unicode)
1967 vereq(u[0:0], u"")
1969 class sublist(list):
1970 pass
1971 a = sublist(range(5))
1972 vereq(a, range(5))
1973 a.append("hello")
1974 vereq(a, range(5) + ["hello"])
1975 a[5] = 5
1976 vereq(a, range(6))
1977 a.extend(range(6, 20))
1978 vereq(a, range(20))
1979 a[-5:] = []
1980 vereq(a, range(15))
1981 del a[10:15]
1982 vereq(len(a), 10)
1983 vereq(a, range(10))
1984 vereq(list(a), range(10))
1985 vereq(a[0], 0)
1986 vereq(a[9], 9)
1987 vereq(a[-10], 0)
1988 vereq(a[-1], 9)
1989 vereq(a[:5], range(5))
1991 class CountedInput(file):
1992 """Counts lines read by self.readline().
1994 self.lineno is the 0-based ordinal of the last line read, up to
1995 a maximum of one greater than the number of lines in the file.
1997 self.ateof is true if and only if the final "" line has been read,
1998 at which point self.lineno stops incrementing, and further calls
1999 to readline() continue to return "".
2002 lineno = 0
2003 ateof = 0
2004 def readline(self):
2005 if self.ateof:
2006 return ""
2007 s = file.readline(self)
2008 # Next line works too.
2009 # s = super(CountedInput, self).readline()
2010 self.lineno += 1
2011 if s == "":
2012 self.ateof = 1
2013 return s
2015 f = file(name=TESTFN, mode='w')
2016 lines = ['a\n', 'b\n', 'c\n']
2017 try:
2018 f.writelines(lines)
2019 f.close()
2020 f = CountedInput(TESTFN)
2021 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2022 got = f.readline()
2023 vereq(expected, got)
2024 vereq(f.lineno, i)
2025 vereq(f.ateof, (i > len(lines)))
2026 f.close()
2027 finally:
2028 try:
2029 f.close()
2030 except:
2031 pass
2032 try:
2033 import os
2034 os.unlink(TESTFN)
2035 except:
2036 pass
2038 def keywords():
2039 if verbose:
2040 print "Testing keyword args to basic type constructors ..."
2041 vereq(int(x=1), 1)
2042 vereq(float(x=2), 2.0)
2043 vereq(long(x=3), 3L)
2044 vereq(complex(imag=42, real=666), complex(666, 42))
2045 vereq(str(object=500), '500')
2046 vereq(unicode(string='abc', errors='strict'), u'abc')
2047 vereq(tuple(sequence=range(3)), (0, 1, 2))
2048 vereq(list(sequence=(0, 1, 2)), range(3))
2049 vereq(dict(items={1: 2}), {1: 2})
2051 for constructor in (int, float, long, complex, str, unicode,
2052 tuple, list, dict, file):
2053 try:
2054 constructor(bogus_keyword_arg=1)
2055 except TypeError:
2056 pass
2057 else:
2058 raise TestFailed("expected TypeError from bogus keyword "
2059 "argument to %r" % constructor)
2061 def restricted():
2062 import rexec
2063 if verbose:
2064 print "Testing interaction with restricted execution ..."
2066 sandbox = rexec.RExec()
2068 code1 = """f = open(%r, 'w')""" % TESTFN
2069 code2 = """f = file(%r, 'w')""" % TESTFN
2070 code3 = """\
2071 f = open(%r)
2072 t = type(f) # a sneaky way to get the file() constructor
2073 f.close()
2074 f = t(%r, 'w') # rexec can't catch this by itself
2075 """ % (TESTFN, TESTFN)
2077 f = open(TESTFN, 'w') # Create the file so code3 can find it.
2078 f.close()
2080 try:
2081 for code in code1, code2, code3:
2082 try:
2083 sandbox.r_exec(code)
2084 except IOError, msg:
2085 if str(msg).find("restricted") >= 0:
2086 outcome = "OK"
2087 else:
2088 outcome = "got an exception, but not an expected one"
2089 else:
2090 outcome = "expected a restricted-execution exception"
2092 if outcome != "OK":
2093 raise TestFailed("%s, in %r" % (outcome, code))
2095 finally:
2096 try:
2097 import os
2098 os.unlink(TESTFN)
2099 except:
2100 pass
2102 def str_subclass_as_dict_key():
2103 if verbose:
2104 print "Testing a str subclass used as dict key .."
2106 class cistr(str):
2107 """Sublcass of str that computes __eq__ case-insensitively.
2109 Also computes a hash code of the string in canonical form.
2112 def __init__(self, value):
2113 self.canonical = value.lower()
2114 self.hashcode = hash(self.canonical)
2116 def __eq__(self, other):
2117 if not isinstance(other, cistr):
2118 other = cistr(other)
2119 return self.canonical == other.canonical
2121 def __hash__(self):
2122 return self.hashcode
2124 vereq(cistr('ABC'), 'abc')
2125 vereq('aBc', cistr('ABC'))
2126 vereq(str(cistr('ABC')), 'ABC')
2128 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2129 vereq(d[cistr('one')], 1)
2130 vereq(d[cistr('tWo')], 2)
2131 vereq(d[cistr('THrEE')], 3)
2132 verify(cistr('ONe') in d)
2133 vereq(d.get(cistr('thrEE')), 3)
2135 def classic_comparisons():
2136 if verbose: print "Testing classic comparisons..."
2137 class classic:
2138 pass
2139 for base in (classic, int, object):
2140 if verbose: print " (base = %s)" % base
2141 class C(base):
2142 def __init__(self, value):
2143 self.value = int(value)
2144 def __cmp__(self, other):
2145 if isinstance(other, C):
2146 return cmp(self.value, other.value)
2147 if isinstance(other, int) or isinstance(other, long):
2148 return cmp(self.value, other)
2149 return NotImplemented
2150 c1 = C(1)
2151 c2 = C(2)
2152 c3 = C(3)
2153 vereq(c1, 1)
2154 c = {1: c1, 2: c2, 3: c3}
2155 for x in 1, 2, 3:
2156 for y in 1, 2, 3:
2157 verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2158 for op in "<", "<=", "==", "!=", ">", ">=":
2159 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2160 "x=%d, y=%d" % (x, y))
2161 verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2162 verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2164 def rich_comparisons():
2165 if verbose:
2166 print "Testing rich comparisons..."
2167 class Z(complex):
2168 pass
2169 z = Z(1)
2170 vereq(z, 1+0j)
2171 vereq(1+0j, z)
2172 class ZZ(complex):
2173 def __eq__(self, other):
2174 try:
2175 return abs(self - other) <= 1e-6
2176 except:
2177 return NotImplemented
2178 zz = ZZ(1.0000003)
2179 vereq(zz, 1+0j)
2180 vereq(1+0j, zz)
2182 class classic:
2183 pass
2184 for base in (classic, int, object, list):
2185 if verbose: print " (base = %s)" % base
2186 class C(base):
2187 def __init__(self, value):
2188 self.value = int(value)
2189 def __cmp__(self, other):
2190 raise TestFailed, "shouldn't call __cmp__"
2191 def __eq__(self, other):
2192 if isinstance(other, C):
2193 return self.value == other.value
2194 if isinstance(other, int) or isinstance(other, long):
2195 return self.value == other
2196 return NotImplemented
2197 def __ne__(self, other):
2198 if isinstance(other, C):
2199 return self.value != other.value
2200 if isinstance(other, int) or isinstance(other, long):
2201 return self.value != other
2202 return NotImplemented
2203 def __lt__(self, other):
2204 if isinstance(other, C):
2205 return self.value < other.value
2206 if isinstance(other, int) or isinstance(other, long):
2207 return self.value < other
2208 return NotImplemented
2209 def __le__(self, other):
2210 if isinstance(other, C):
2211 return self.value <= other.value
2212 if isinstance(other, int) or isinstance(other, long):
2213 return self.value <= other
2214 return NotImplemented
2215 def __gt__(self, other):
2216 if isinstance(other, C):
2217 return self.value > other.value
2218 if isinstance(other, int) or isinstance(other, long):
2219 return self.value > other
2220 return NotImplemented
2221 def __ge__(self, other):
2222 if isinstance(other, C):
2223 return self.value >= other.value
2224 if isinstance(other, int) or isinstance(other, long):
2225 return self.value >= other
2226 return NotImplemented
2227 c1 = C(1)
2228 c2 = C(2)
2229 c3 = C(3)
2230 vereq(c1, 1)
2231 c = {1: c1, 2: c2, 3: c3}
2232 for x in 1, 2, 3:
2233 for y in 1, 2, 3:
2234 for op in "<", "<=", "==", "!=", ">", ">=":
2235 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2236 "x=%d, y=%d" % (x, y))
2237 verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
2238 "x=%d, y=%d" % (x, y))
2239 verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
2240 "x=%d, y=%d" % (x, y))
2242 def coercions():
2243 if verbose: print "Testing coercions..."
2244 class I(int): pass
2245 coerce(I(0), 0)
2246 coerce(0, I(0))
2247 class L(long): pass
2248 coerce(L(0), 0)
2249 coerce(L(0), 0L)
2250 coerce(0, L(0))
2251 coerce(0L, L(0))
2252 class F(float): pass
2253 coerce(F(0), 0)
2254 coerce(F(0), 0L)
2255 coerce(F(0), 0.)
2256 coerce(0, F(0))
2257 coerce(0L, F(0))
2258 coerce(0., F(0))
2259 class C(complex): pass
2260 coerce(C(0), 0)
2261 coerce(C(0), 0L)
2262 coerce(C(0), 0.)
2263 coerce(C(0), 0j)
2264 coerce(0, C(0))
2265 coerce(0L, C(0))
2266 coerce(0., C(0))
2267 coerce(0j, C(0))
2269 def descrdoc():
2270 if verbose: print "Testing descriptor doc strings..."
2271 def check(descr, what):
2272 vereq(descr.__doc__, what)
2273 check(file.closed, "flag set if the file is closed") # getset descriptor
2274 check(file.name, "file name") # member descriptor
2276 def setclass():
2277 if verbose: print "Testing __class__ assignment..."
2278 class C(object): pass
2279 class D(object): pass
2280 class E(object): pass
2281 class F(D, E): pass
2282 for cls in C, D, E, F:
2283 for cls2 in C, D, E, F:
2284 x = cls()
2285 x.__class__ = cls2
2286 verify(x.__class__ is cls2)
2287 x.__class__ = cls
2288 verify(x.__class__ is cls)
2289 def cant(x, C):
2290 try:
2291 x.__class__ = C
2292 except TypeError:
2293 pass
2294 else:
2295 raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
2296 cant(C(), list)
2297 cant(list(), C)
2298 cant(C(), 1)
2299 cant(C(), object)
2300 cant(object(), list)
2301 cant(list(), object)
2303 def setdict():
2304 if verbose: print "Testing __dict__ assignment..."
2305 class C(object): pass
2306 a = C()
2307 a.__dict__ = {'b': 1}
2308 vereq(a.b, 1)
2309 def cant(x, dict):
2310 try:
2311 x.__dict__ = dict
2312 except TypeError:
2313 pass
2314 else:
2315 raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict)
2316 cant(a, None)
2317 cant(a, [])
2318 cant(a, 1)
2319 del a.__dict__ # Deleting __dict__ is allowed
2320 # Classes don't allow __dict__ assignment
2321 cant(C, {})
2323 def pickles():
2324 if verbose:
2325 print "Testing pickling and copying new-style classes and objects..."
2326 import pickle, cPickle
2328 def sorteditems(d):
2329 L = d.items()
2330 L.sort()
2331 return L
2333 global C
2334 class C(object):
2335 def __init__(self, a, b):
2336 super(C, self).__init__()
2337 self.a = a
2338 self.b = b
2339 def __repr__(self):
2340 return "C(%r, %r)" % (self.a, self.b)
2342 global C1
2343 class C1(list):
2344 def __new__(cls, a, b):
2345 return super(C1, cls).__new__(cls)
2346 def __init__(self, a, b):
2347 self.a = a
2348 self.b = b
2349 def __repr__(self):
2350 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2352 global C2
2353 class C2(int):
2354 def __new__(cls, a, b, val=0):
2355 return super(C2, cls).__new__(cls, val)
2356 def __init__(self, a, b, val=0):
2357 self.a = a
2358 self.b = b
2359 def __repr__(self):
2360 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2362 global C3
2363 class C3(object):
2364 def __init__(self, foo):
2365 self.foo = foo
2366 def __getstate__(self):
2367 return self.foo
2368 def __setstate__(self, foo):
2369 self.foo = foo
2371 global C4classic, C4
2372 class C4classic: # classic
2373 pass
2374 class C4(C4classic, object): # mixed inheritance
2375 pass
2377 for p in pickle, cPickle:
2378 for bin in 0, 1:
2379 if verbose:
2380 print p.__name__, ["text", "binary"][bin]
2382 for cls in C, C1, C2:
2383 s = p.dumps(cls, bin)
2384 cls2 = p.loads(s)
2385 verify(cls2 is cls)
2387 a = C1(1, 2); a.append(42); a.append(24)
2388 b = C2("hello", "world", 42)
2389 s = p.dumps((a, b), bin)
2390 x, y = p.loads(s)
2391 vereq(x.__class__, a.__class__)
2392 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2393 vereq(y.__class__, b.__class__)
2394 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
2395 vereq(`x`, `a`)
2396 vereq(`y`, `b`)
2397 if verbose:
2398 print "a = x =", a
2399 print "b = y =", b
2400 # Test for __getstate__ and __setstate__ on new style class
2401 u = C3(42)
2402 s = p.dumps(u, bin)
2403 v = p.loads(s)
2404 veris(u.__class__, v.__class__)
2405 vereq(u.foo, v.foo)
2406 # Test for picklability of hybrid class
2407 u = C4()
2408 u.foo = 42
2409 s = p.dumps(u, bin)
2410 v = p.loads(s)
2411 veris(u.__class__, v.__class__)
2412 vereq(u.foo, v.foo)
2414 # Testing copy.deepcopy()
2415 if verbose:
2416 print "deepcopy"
2417 import copy
2418 for cls in C, C1, C2:
2419 cls2 = copy.deepcopy(cls)
2420 verify(cls2 is cls)
2422 a = C1(1, 2); a.append(42); a.append(24)
2423 b = C2("hello", "world", 42)
2424 x, y = copy.deepcopy((a, b))
2425 vereq(x.__class__, a.__class__)
2426 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2427 vereq(y.__class__, b.__class__)
2428 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
2429 vereq(`x`, `a`)
2430 vereq(`y`, `b`)
2431 if verbose:
2432 print "a = x =", a
2433 print "b = y =", b
2435 def copies():
2436 if verbose: print "Testing copy.copy() and copy.deepcopy()..."
2437 import copy
2438 class C(object):
2439 pass
2441 a = C()
2442 a.foo = 12
2443 b = copy.copy(a)
2444 vereq(b.__dict__, a.__dict__)
2446 a.bar = [1,2,3]
2447 c = copy.copy(a)
2448 vereq(c.bar, a.bar)
2449 verify(c.bar is a.bar)
2451 d = copy.deepcopy(a)
2452 vereq(d.__dict__, a.__dict__)
2453 a.bar.append(4)
2454 vereq(d.bar, [1,2,3])
2456 def binopoverride():
2457 if verbose: print "Testing overrides of binary operations..."
2458 class I(int):
2459 def __repr__(self):
2460 return "I(%r)" % int(self)
2461 def __add__(self, other):
2462 return I(int(self) + int(other))
2463 __radd__ = __add__
2464 def __pow__(self, other, mod=None):
2465 if mod is None:
2466 return I(pow(int(self), int(other)))
2467 else:
2468 return I(pow(int(self), int(other), int(mod)))
2469 def __rpow__(self, other, mod=None):
2470 if mod is None:
2471 return I(pow(int(other), int(self), mod))
2472 else:
2473 return I(pow(int(other), int(self), int(mod)))
2475 vereq(`I(1) + I(2)`, "I(3)")
2476 vereq(`I(1) + 2`, "I(3)")
2477 vereq(`1 + I(2)`, "I(3)")
2478 vereq(`I(2) ** I(3)`, "I(8)")
2479 vereq(`2 ** I(3)`, "I(8)")
2480 vereq(`I(2) ** 3`, "I(8)")
2481 vereq(`pow(I(2), I(3), I(5))`, "I(3)")
2482 class S(str):
2483 def __eq__(self, other):
2484 return self.lower() == other.lower()
2486 def subclasspropagation():
2487 if verbose: print "Testing propagation of slot functions to subclasses..."
2488 class A(object):
2489 pass
2490 class B(A):
2491 pass
2492 class C(A):
2493 pass
2494 class D(B, C):
2495 pass
2496 d = D()
2497 vereq(hash(d), id(d))
2498 A.__hash__ = lambda self: 42
2499 vereq(hash(d), 42)
2500 C.__hash__ = lambda self: 314
2501 vereq(hash(d), 314)
2502 B.__hash__ = lambda self: 144
2503 vereq(hash(d), 144)
2504 D.__hash__ = lambda self: 100
2505 vereq(hash(d), 100)
2506 del D.__hash__
2507 vereq(hash(d), 144)
2508 del B.__hash__
2509 vereq(hash(d), 314)
2510 del C.__hash__
2511 vereq(hash(d), 42)
2512 del A.__hash__
2513 vereq(hash(d), id(d))
2514 d.foo = 42
2515 d.bar = 42
2516 vereq(d.foo, 42)
2517 vereq(d.bar, 42)
2518 def __getattribute__(self, name):
2519 if name == "foo":
2520 return 24
2521 return object.__getattribute__(self, name)
2522 A.__getattribute__ = __getattribute__
2523 vereq(d.foo, 24)
2524 vereq(d.bar, 42)
2525 def __getattr__(self, name):
2526 if name in ("spam", "foo", "bar"):
2527 return "hello"
2528 raise AttributeError, name
2529 B.__getattr__ = __getattr__
2530 vereq(d.spam, "hello")
2531 vereq(d.foo, 24)
2532 vereq(d.bar, 42)
2533 del A.__getattribute__
2534 vereq(d.foo, 42)
2535 del d.foo
2536 vereq(d.foo, "hello")
2537 vereq(d.bar, 42)
2538 del B.__getattr__
2539 try:
2540 d.foo
2541 except AttributeError:
2542 pass
2543 else:
2544 raise TestFailed, "d.foo should be undefined now"
2546 def buffer_inherit():
2547 import binascii
2548 # SF bug [#470040] ParseTuple t# vs subclasses.
2549 if verbose:
2550 print "Testing that buffer interface is inherited ..."
2552 class MyStr(str):
2553 pass
2554 base = 'abc'
2555 m = MyStr(base)
2556 # b2a_hex uses the buffer interface to get its argument's value, via
2557 # PyArg_ParseTuple 't#' code.
2558 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
2560 # It's not clear that unicode will continue to support the character
2561 # buffer interface, and this test will fail if that's taken away.
2562 class MyUni(unicode):
2563 pass
2564 base = u'abc'
2565 m = MyUni(base)
2566 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
2568 class MyInt(int):
2569 pass
2570 m = MyInt(42)
2571 try:
2572 binascii.b2a_hex(m)
2573 raise TestFailed('subclass of int should not have a buffer interface')
2574 except TypeError:
2575 pass
2577 def str_of_str_subclass():
2578 import binascii
2579 import cStringIO
2581 if verbose:
2582 print "Testing __str__ defined in subclass of str ..."
2584 class octetstring(str):
2585 def __str__(self):
2586 return binascii.b2a_hex(self)
2587 def __repr__(self):
2588 return self + " repr"
2590 o = octetstring('A')
2591 vereq(type(o), octetstring)
2592 vereq(type(str(o)), str)
2593 vereq(type(repr(o)), str)
2594 vereq(ord(o), 0x41)
2595 vereq(str(o), '41')
2596 vereq(repr(o), 'A repr')
2597 vereq(o.__str__(), '41')
2598 vereq(o.__repr__(), 'A repr')
2600 capture = cStringIO.StringIO()
2601 # Calling str() or not exercises different internal paths.
2602 print >> capture, o
2603 print >> capture, str(o)
2604 vereq(capture.getvalue(), '41\n41\n')
2605 capture.close()
2607 def kwdargs():
2608 if verbose: print "Testing keyword arguments to __init__, __call__..."
2609 def f(a): return a
2610 vereq(f.__call__(a=42), 42)
2611 a = []
2612 list.__init__(a, sequence=[0, 1, 2])
2613 vereq(a, [0, 1, 2])
2615 def delhook():
2616 if verbose: print "Testing __del__ hook..."
2617 log = []
2618 class C(object):
2619 def __del__(self):
2620 log.append(1)
2621 c = C()
2622 vereq(log, [])
2623 del c
2624 vereq(log, [1])
2626 class D(object): pass
2627 d = D()
2628 try: del d[0]
2629 except TypeError: pass
2630 else: raise TestFailed, "invalid del() didn't raise TypeError"
2632 def hashinherit():
2633 if verbose: print "Testing hash of mutable subclasses..."
2635 class mydict(dict):
2636 pass
2637 d = mydict()
2638 try:
2639 hash(d)
2640 except TypeError:
2641 pass
2642 else:
2643 raise TestFailed, "hash() of dict subclass should fail"
2645 class mylist(list):
2646 pass
2647 d = mylist()
2648 try:
2649 hash(d)
2650 except TypeError:
2651 pass
2652 else:
2653 raise TestFailed, "hash() of list subclass should fail"
2655 def strops():
2656 try: 'a' + 5
2657 except TypeError: pass
2658 else: raise TestFailed, "'' + 5 doesn't raise TypeError"
2660 try: ''.split('')
2661 except ValueError: pass
2662 else: raise TestFailed, "''.split('') doesn't raise ValueError"
2664 try: ''.join([0])
2665 except TypeError: pass
2666 else: raise TestFailed, "''.join([0]) doesn't raise TypeError"
2668 try: ''.rindex('5')
2669 except ValueError: pass
2670 else: raise TestFailed, "''.rindex('5') doesn't raise ValueError"
2672 try: ''.replace('', '')
2673 except ValueError: pass
2674 else: raise TestFailed, "''.replace('', '') doesn't raise ValueError"
2676 try: '%(n)s' % None
2677 except TypeError: pass
2678 else: raise TestFailed, "'%(n)s' % None doesn't raise TypeError"
2680 try: '%(n' % {}
2681 except ValueError: pass
2682 else: raise TestFailed, "'%(n' % {} '' doesn't raise ValueError"
2684 try: '%*s' % ('abc')
2685 except TypeError: pass
2686 else: raise TestFailed, "'%*s' % ('abc') doesn't raise TypeError"
2688 try: '%*.*s' % ('abc', 5)
2689 except TypeError: pass
2690 else: raise TestFailed, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
2692 try: '%s' % (1, 2)
2693 except TypeError: pass
2694 else: raise TestFailed, "'%s' % (1, 2) doesn't raise TypeError"
2696 try: '%' % None
2697 except ValueError: pass
2698 else: raise TestFailed, "'%' % None doesn't raise ValueError"
2700 vereq('534253'.isdigit(), 1)
2701 vereq('534253x'.isdigit(), 0)
2702 vereq('%c' % 5, '\x05')
2703 vereq('%c' % '5', '5')
2708 def test_main():
2709 class_docstrings()
2710 lists()
2711 dicts()
2712 dict_constructor()
2713 test_dir()
2714 ints()
2715 longs()
2716 floats()
2717 complexes()
2718 spamlists()
2719 spamdicts()
2720 pydicts()
2721 pylists()
2722 metaclass()
2723 pymods()
2724 multi()
2725 diamond()
2726 objects()
2727 slots()
2728 dynamics()
2729 errors()
2730 classmethods()
2731 staticmethods()
2732 classic()
2733 compattr()
2734 newslot()
2735 altmro()
2736 overloading()
2737 methods()
2738 specials()
2739 weakrefs()
2740 properties()
2741 supers()
2742 inherits()
2743 keywords()
2744 restricted()
2745 str_subclass_as_dict_key()
2746 classic_comparisons()
2747 rich_comparisons()
2748 coercions()
2749 descrdoc()
2750 setclass()
2751 setdict()
2752 pickles()
2753 copies()
2754 binopoverride()
2755 subclasspropagation()
2756 buffer_inherit()
2757 str_of_str_subclass()
2758 kwdargs()
2759 delhook()
2760 hashinherit()
2761 strops()
2762 if verbose: print "All OK"
2764 if __name__ == "__main__":
2765 test_main()