- Got rid of newmodule.c
[python/dscho.git] / Lib / test / test_descr.py
blobdca8ea1760e7a3bdf4682bea2ddaa2ee5f1cff78
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
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(items={})
188 vereq(d, {})
189 d = dict({1: 2, 'a': 'b'})
190 vereq(d, {1: 2, 'a': 'b'})
191 vereq(d, dict(d.items()))
192 vereq(d, dict(items=d.iteritems()))
193 for badarg in 0, 0L, 0j, "0", [0], (0,):
194 try:
195 dict(badarg)
196 except TypeError:
197 pass
198 except ValueError:
199 if badarg == "0":
200 # It's a sequence, and its elements are also sequences (gotta
201 # love strings <wink>), but they aren't of length 2, so this
202 # one seemed better as a ValueError than a TypeError.
203 pass
204 else:
205 raise TestFailed("no TypeError from dict(%r)" % badarg)
206 else:
207 raise TestFailed("no TypeError from dict(%r)" % badarg)
208 try:
209 dict(senseless={})
210 except TypeError:
211 pass
212 else:
213 raise TestFailed("no TypeError from dict(senseless={})")
215 try:
216 dict({}, {})
217 except TypeError:
218 pass
219 else:
220 raise TestFailed("no TypeError from dict({}, {})")
222 class Mapping:
223 # Lacks a .keys() method; will be added later.
224 dict = {1:2, 3:4, 'a':1j}
226 try:
227 dict(Mapping())
228 except TypeError:
229 pass
230 else:
231 raise TestFailed("no TypeError from dict(incomplete mapping)")
233 Mapping.keys = lambda self: self.dict.keys()
234 Mapping.__getitem__ = lambda self, i: self.dict[i]
235 d = dict(items=Mapping())
236 vereq(d, Mapping.dict)
238 # Init from sequence of iterable objects, each producing a 2-sequence.
239 class AddressBookEntry:
240 def __init__(self, first, last):
241 self.first = first
242 self.last = last
243 def __iter__(self):
244 return iter([self.first, self.last])
246 d = dict([AddressBookEntry('Tim', 'Warsaw'),
247 AddressBookEntry('Barry', 'Peters'),
248 AddressBookEntry('Tim', 'Peters'),
249 AddressBookEntry('Barry', 'Warsaw')])
250 vereq(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
252 d = dict(zip(range(4), range(1, 5)))
253 vereq(d, dict([(i, i+1) for i in range(4)]))
255 # Bad sequence lengths.
256 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
257 try:
258 dict(bad)
259 except ValueError:
260 pass
261 else:
262 raise TestFailed("no ValueError from dict(%r)" % bad)
264 def test_dir():
265 if verbose:
266 print "Testing dir() ..."
267 junk = 12
268 vereq(dir(), ['junk'])
269 del junk
271 # Just make sure these don't blow up!
272 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, test_dir:
273 dir(arg)
275 # Try classic classes.
276 class C:
277 Cdata = 1
278 def Cmethod(self): pass
280 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
281 vereq(dir(C), cstuff)
282 verify('im_self' in dir(C.Cmethod))
284 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
285 vereq(dir(c), cstuff)
287 c.cdata = 2
288 c.cmethod = lambda self: 0
289 vereq(dir(c), cstuff + ['cdata', 'cmethod'])
290 verify('im_self' in dir(c.Cmethod))
292 class A(C):
293 Adata = 1
294 def Amethod(self): pass
296 astuff = ['Adata', 'Amethod'] + cstuff
297 vereq(dir(A), astuff)
298 verify('im_self' in dir(A.Amethod))
299 a = A()
300 vereq(dir(a), astuff)
301 verify('im_self' in dir(a.Amethod))
302 a.adata = 42
303 a.amethod = lambda self: 3
304 vereq(dir(a), astuff + ['adata', 'amethod'])
306 # The same, but with new-style classes. Since these have object as a
307 # base class, a lot more gets sucked in.
308 def interesting(strings):
309 return [s for s in strings if not s.startswith('_')]
311 class C(object):
312 Cdata = 1
313 def Cmethod(self): pass
315 cstuff = ['Cdata', 'Cmethod']
316 vereq(interesting(dir(C)), cstuff)
318 c = C()
319 vereq(interesting(dir(c)), cstuff)
320 verify('im_self' in dir(C.Cmethod))
322 c.cdata = 2
323 c.cmethod = lambda self: 0
324 vereq(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
325 verify('im_self' in dir(c.Cmethod))
327 class A(C):
328 Adata = 1
329 def Amethod(self): pass
331 astuff = ['Adata', 'Amethod'] + cstuff
332 vereq(interesting(dir(A)), astuff)
333 verify('im_self' in dir(A.Amethod))
334 a = A()
335 vereq(interesting(dir(a)), astuff)
336 a.adata = 42
337 a.amethod = lambda self: 3
338 vereq(interesting(dir(a)), astuff + ['adata', 'amethod'])
339 verify('im_self' in dir(a.Amethod))
341 # Try a module subclass.
342 import sys
343 class M(type(sys)):
344 pass
345 minstance = M("m")
346 minstance.b = 2
347 minstance.a = 1
348 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
349 vereq(names, ['a', 'b'])
351 class M2(M):
352 def getdict(self):
353 return "Not a dict!"
354 __dict__ = property(getdict)
356 m2instance = M2("m2")
357 m2instance.b = 2
358 m2instance.a = 1
359 vereq(m2instance.__dict__, "Not a dict!")
360 try:
361 dir(m2instance)
362 except TypeError:
363 pass
365 # Two essentially featureless objects, just inheriting stuff from
366 # object.
367 vereq(dir(None), dir(Ellipsis))
369 # Nasty test case for proxied objects
370 class Wrapper(object):
371 def __init__(self, obj):
372 self.__obj = obj
373 def __repr__(self):
374 return "Wrapper(%s)" % repr(self.__obj)
375 def __getitem__(self, key):
376 return Wrapper(self.__obj[key])
377 def __len__(self):
378 return len(self.__obj)
379 def __getattr__(self, name):
380 return Wrapper(getattr(self.__obj, name))
382 class C(object):
383 def __getclass(self):
384 return Wrapper(type(self))
385 __class__ = property(__getclass)
387 dir(C()) # This used to segfault
389 binops = {
390 'add': '+',
391 'sub': '-',
392 'mul': '*',
393 'div': '/',
394 'mod': '%',
395 'divmod': 'divmod',
396 'pow': '**',
397 'lshift': '<<',
398 'rshift': '>>',
399 'and': '&',
400 'xor': '^',
401 'or': '|',
402 'cmp': 'cmp',
403 'lt': '<',
404 'le': '<=',
405 'eq': '==',
406 'ne': '!=',
407 'gt': '>',
408 'ge': '>=',
411 for name, expr in binops.items():
412 if expr.islower():
413 expr = expr + "(a, b)"
414 else:
415 expr = 'a %s b' % expr
416 binops[name] = expr
418 unops = {
419 'pos': '+',
420 'neg': '-',
421 'abs': 'abs',
422 'invert': '~',
423 'int': 'int',
424 'long': 'long',
425 'float': 'float',
426 'oct': 'oct',
427 'hex': 'hex',
430 for name, expr in unops.items():
431 if expr.islower():
432 expr = expr + "(a)"
433 else:
434 expr = '%s a' % expr
435 unops[name] = expr
437 def numops(a, b, skip=[]):
438 dict = {'a': a, 'b': b}
439 for name, expr in binops.items():
440 if name not in skip:
441 name = "__%s__" % name
442 if hasattr(a, name):
443 res = eval(expr, dict)
444 testbinop(a, b, res, expr, name)
445 for name, expr in unops.items():
446 if name not in skip:
447 name = "__%s__" % name
448 if hasattr(a, name):
449 res = eval(expr, dict)
450 testunop(a, res, expr, name)
452 def ints():
453 if verbose: print "Testing int operations..."
454 numops(100, 3)
455 # The following crashes in Python 2.2
456 vereq((1).__nonzero__(), 1)
457 vereq((0).__nonzero__(), 0)
458 # This returns 'NotImplemented' in Python 2.2
459 class C(int):
460 def __add__(self, other):
461 return NotImplemented
462 try:
463 C() + ""
464 except TypeError:
465 pass
466 else:
467 raise TestFailed, "NotImplemented should have caused TypeError"
469 def longs():
470 if verbose: print "Testing long operations..."
471 numops(100L, 3L)
473 def floats():
474 if verbose: print "Testing float operations..."
475 numops(100.0, 3.0)
477 def complexes():
478 if verbose: print "Testing complex operations..."
479 numops(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge', 'int', 'long', 'float'])
480 class Number(complex):
481 __slots__ = ['prec']
482 def __new__(cls, *args, **kwds):
483 result = complex.__new__(cls, *args)
484 result.prec = kwds.get('prec', 12)
485 return result
486 def __repr__(self):
487 prec = self.prec
488 if self.imag == 0.0:
489 return "%.*g" % (prec, self.real)
490 if self.real == 0.0:
491 return "%.*gj" % (prec, self.imag)
492 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
493 __str__ = __repr__
495 a = Number(3.14, prec=6)
496 vereq(`a`, "3.14")
497 vereq(a.prec, 6)
499 a = Number(a, prec=2)
500 vereq(`a`, "3.1")
501 vereq(a.prec, 2)
503 a = Number(234.5)
504 vereq(`a`, "234.5")
505 vereq(a.prec, 12)
507 def spamlists():
508 if verbose: print "Testing spamlist operations..."
509 import copy, xxsubtype as spam
510 def spamlist(l, memo=None):
511 import xxsubtype as spam
512 return spam.spamlist(l)
513 # This is an ugly hack:
514 copy._deepcopy_dispatch[spam.spamlist] = spamlist
516 testbinop(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b", "__add__")
517 testbinop(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
518 testbinop(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
519 testbinop(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
520 testternop(spamlist([1,2,3]), 0, 2, spamlist([1,2]),
521 "a[b:c]", "__getslice__")
522 testsetop(spamlist([1]), spamlist([2]), spamlist([1,2]),
523 "a+=b", "__iadd__")
524 testsetop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b", "__imul__")
525 testunop(spamlist([1,2,3]), 3, "len(a)", "__len__")
526 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b", "__mul__")
527 testbinop(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a", "__rmul__")
528 testset2op(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c", "__setitem__")
529 testset3op(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
530 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
531 # Test subclassing
532 class C(spam.spamlist):
533 def foo(self): return 1
534 a = C()
535 vereq(a, [])
536 vereq(a.foo(), 1)
537 a.append(100)
538 vereq(a, [100])
539 vereq(a.getstate(), 0)
540 a.setstate(42)
541 vereq(a.getstate(), 42)
543 def spamdicts():
544 if verbose: print "Testing spamdict operations..."
545 import copy, xxsubtype as spam
546 def spamdict(d, memo=None):
547 import xxsubtype as spam
548 sd = spam.spamdict()
549 for k, v in d.items(): sd[k] = v
550 return sd
551 # This is an ugly hack:
552 copy._deepcopy_dispatch[spam.spamdict] = spamdict
554 testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__")
555 testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
556 testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
557 testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
558 d = spamdict({1:2,3:4})
559 l1 = []
560 for i in d.keys(): l1.append(i)
561 l = []
562 for i in iter(d): l.append(i)
563 vereq(l, l1)
564 l = []
565 for i in d.__iter__(): l.append(i)
566 vereq(l, l1)
567 l = []
568 for i in type(spamdict({})).__iter__(d): l.append(i)
569 vereq(l, l1)
570 straightd = {1:2, 3:4}
571 spamd = spamdict(straightd)
572 testunop(spamd, 2, "len(a)", "__len__")
573 testunop(spamd, repr(straightd), "repr(a)", "__repr__")
574 testset2op(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
575 "a[b]=c", "__setitem__")
576 # Test subclassing
577 class C(spam.spamdict):
578 def foo(self): return 1
579 a = C()
580 vereq(a.items(), [])
581 vereq(a.foo(), 1)
582 a['foo'] = 'bar'
583 vereq(a.items(), [('foo', 'bar')])
584 vereq(a.getstate(), 0)
585 a.setstate(100)
586 vereq(a.getstate(), 100)
588 def pydicts():
589 if verbose: print "Testing Python subclass of dict..."
590 verify(issubclass(dict, dict))
591 verify(isinstance({}, dict))
592 d = dict()
593 vereq(d, {})
594 verify(d.__class__ is dict)
595 verify(isinstance(d, dict))
596 class C(dict):
597 state = -1
598 def __init__(self, *a, **kw):
599 if a:
600 vereq(len(a), 1)
601 self.state = a[0]
602 if kw:
603 for k, v in kw.items(): self[v] = k
604 def __getitem__(self, key):
605 return self.get(key, 0)
606 def __setitem__(self, key, value):
607 verify(isinstance(key, type(0)))
608 dict.__setitem__(self, key, value)
609 def setstate(self, state):
610 self.state = state
611 def getstate(self):
612 return self.state
613 verify(issubclass(C, dict))
614 a1 = C(12)
615 vereq(a1.state, 12)
616 a2 = C(foo=1, bar=2)
617 vereq(a2[1] == 'foo' and a2[2], 'bar')
618 a = C()
619 vereq(a.state, -1)
620 vereq(a.getstate(), -1)
621 a.setstate(0)
622 vereq(a.state, 0)
623 vereq(a.getstate(), 0)
624 a.setstate(10)
625 vereq(a.state, 10)
626 vereq(a.getstate(), 10)
627 vereq(a[42], 0)
628 a[42] = 24
629 vereq(a[42], 24)
630 if verbose: print "pydict stress test ..."
631 N = 50
632 for i in range(N):
633 a[i] = C()
634 for j in range(N):
635 a[i][j] = i*j
636 for i in range(N):
637 for j in range(N):
638 vereq(a[i][j], i*j)
640 def pylists():
641 if verbose: print "Testing Python subclass of list..."
642 class C(list):
643 def __getitem__(self, i):
644 return list.__getitem__(self, i) + 100
645 def __getslice__(self, i, j):
646 return (i, j)
647 a = C()
648 a.extend([0,1,2])
649 vereq(a[0], 100)
650 vereq(a[1], 101)
651 vereq(a[2], 102)
652 vereq(a[100:200], (100,200))
654 def metaclass():
655 if verbose: print "Testing __metaclass__..."
656 class C:
657 __metaclass__ = type
658 def __init__(self):
659 self.__state = 0
660 def getstate(self):
661 return self.__state
662 def setstate(self, state):
663 self.__state = state
664 a = C()
665 vereq(a.getstate(), 0)
666 a.setstate(10)
667 vereq(a.getstate(), 10)
668 class D:
669 class __metaclass__(type):
670 def myself(cls): return cls
671 vereq(D.myself(), D)
672 d = D()
673 verify(d.__class__ is D)
674 class M1(type):
675 def __new__(cls, name, bases, dict):
676 dict['__spam__'] = 1
677 return type.__new__(cls, name, bases, dict)
678 class C:
679 __metaclass__ = M1
680 vereq(C.__spam__, 1)
681 c = C()
682 vereq(c.__spam__, 1)
684 class _instance(object):
685 pass
686 class M2(object):
687 def __new__(cls, name, bases, dict):
688 self = object.__new__(cls)
689 self.name = name
690 self.bases = bases
691 self.dict = dict
692 return self
693 __new__ = staticmethod(__new__)
694 def __call__(self):
695 it = _instance()
696 # Early binding of methods
697 for key in self.dict:
698 if key.startswith("__"):
699 continue
700 setattr(it, key, self.dict[key].__get__(it, self))
701 return it
702 class C:
703 __metaclass__ = M2
704 def spam(self):
705 return 42
706 vereq(C.name, 'C')
707 vereq(C.bases, ())
708 verify('spam' in C.dict)
709 c = C()
710 vereq(c.spam(), 42)
712 # More metaclass examples
714 class autosuper(type):
715 # Automatically add __super to the class
716 # This trick only works for dynamic classes
717 def __new__(metaclass, name, bases, dict):
718 cls = super(autosuper, metaclass).__new__(metaclass,
719 name, bases, dict)
720 # Name mangling for __super removes leading underscores
721 while name[:1] == "_":
722 name = name[1:]
723 if name:
724 name = "_%s__super" % name
725 else:
726 name = "__super"
727 setattr(cls, name, super(cls))
728 return cls
729 class A:
730 __metaclass__ = autosuper
731 def meth(self):
732 return "A"
733 class B(A):
734 def meth(self):
735 return "B" + self.__super.meth()
736 class C(A):
737 def meth(self):
738 return "C" + self.__super.meth()
739 class D(C, B):
740 def meth(self):
741 return "D" + self.__super.meth()
742 vereq(D().meth(), "DCBA")
743 class E(B, C):
744 def meth(self):
745 return "E" + self.__super.meth()
746 vereq(E().meth(), "EBCA")
748 class autoproperty(type):
749 # Automatically create property attributes when methods
750 # named _get_x and/or _set_x are found
751 def __new__(metaclass, name, bases, dict):
752 hits = {}
753 for key, val in dict.iteritems():
754 if key.startswith("_get_"):
755 key = key[5:]
756 get, set = hits.get(key, (None, None))
757 get = val
758 hits[key] = get, set
759 elif key.startswith("_set_"):
760 key = key[5:]
761 get, set = hits.get(key, (None, None))
762 set = val
763 hits[key] = get, set
764 for key, (get, set) in hits.iteritems():
765 dict[key] = property(get, set)
766 return super(autoproperty, metaclass).__new__(metaclass,
767 name, bases, dict)
768 class A:
769 __metaclass__ = autoproperty
770 def _get_x(self):
771 return -self.__x
772 def _set_x(self, x):
773 self.__x = -x
774 a = A()
775 verify(not hasattr(a, "x"))
776 a.x = 12
777 vereq(a.x, 12)
778 vereq(a._A__x, -12)
780 class multimetaclass(autoproperty, autosuper):
781 # Merge of multiple cooperating metaclasses
782 pass
783 class A:
784 __metaclass__ = multimetaclass
785 def _get_x(self):
786 return "A"
787 class B(A):
788 def _get_x(self):
789 return "B" + self.__super._get_x()
790 class C(A):
791 def _get_x(self):
792 return "C" + self.__super._get_x()
793 class D(C, B):
794 def _get_x(self):
795 return "D" + self.__super._get_x()
796 vereq(D().x, "DCBA")
798 # Make sure type(x) doesn't call x.__class__.__init__
799 class T(type):
800 counter = 0
801 def __init__(self, *args):
802 T.counter += 1
803 class C:
804 __metaclass__ = T
805 vereq(T.counter, 1)
806 a = C()
807 vereq(type(a), C)
808 vereq(T.counter, 1)
810 class C(object): pass
811 c = C()
812 try: c()
813 except TypeError: pass
814 else: raise TestFailed, "calling object w/o call method should raise TypeError"
816 def pymods():
817 if verbose: print "Testing Python subclass of module..."
818 log = []
819 import sys
820 MT = type(sys)
821 class MM(MT):
822 def __init__(self, name):
823 MT.__init__(self, name)
824 def __getattribute__(self, name):
825 log.append(("getattr", name))
826 return MT.__getattribute__(self, name)
827 def __setattr__(self, name, value):
828 log.append(("setattr", name, value))
829 MT.__setattr__(self, name, value)
830 def __delattr__(self, name):
831 log.append(("delattr", name))
832 MT.__delattr__(self, name)
833 a = MM("a")
834 a.foo = 12
835 x = a.foo
836 del a.foo
837 vereq(log, [("setattr", "foo", 12),
838 ("getattr", "foo"),
839 ("delattr", "foo")])
841 def multi():
842 if verbose: print "Testing multiple inheritance..."
843 class C(object):
844 def __init__(self):
845 self.__state = 0
846 def getstate(self):
847 return self.__state
848 def setstate(self, state):
849 self.__state = state
850 a = C()
851 vereq(a.getstate(), 0)
852 a.setstate(10)
853 vereq(a.getstate(), 10)
854 class D(dict, C):
855 def __init__(self):
856 type({}).__init__(self)
857 C.__init__(self)
858 d = D()
859 vereq(d.keys(), [])
860 d["hello"] = "world"
861 vereq(d.items(), [("hello", "world")])
862 vereq(d["hello"], "world")
863 vereq(d.getstate(), 0)
864 d.setstate(10)
865 vereq(d.getstate(), 10)
866 vereq(D.__mro__, (D, dict, C, object))
868 # SF bug #442833
869 class Node(object):
870 def __int__(self):
871 return int(self.foo())
872 def foo(self):
873 return "23"
874 class Frag(Node, list):
875 def foo(self):
876 return "42"
877 vereq(Node().__int__(), 23)
878 vereq(int(Node()), 23)
879 vereq(Frag().__int__(), 42)
880 vereq(int(Frag()), 42)
882 # MI mixing classic and new-style classes.
884 class A:
885 x = 1
887 class B(A):
888 pass
890 class C(A):
891 x = 2
893 class D(B, C):
894 pass
895 vereq(D.x, 1)
897 # Classic MRO is preserved for a classic base class.
898 class E(D, object):
899 pass
900 vereq(E.__mro__, (E, D, B, A, C, object))
901 vereq(E.x, 1)
903 # But with a mix of classic bases, their MROs are combined using
904 # new-style MRO.
905 class F(B, C, object):
906 pass
907 vereq(F.__mro__, (F, B, C, A, object))
908 vereq(F.x, 2)
910 # Try something else.
911 class C:
912 def cmethod(self):
913 return "C a"
914 def all_method(self):
915 return "C b"
917 class M1(C, object):
918 def m1method(self):
919 return "M1 a"
920 def all_method(self):
921 return "M1 b"
923 vereq(M1.__mro__, (M1, C, object))
924 m = M1()
925 vereq(m.cmethod(), "C a")
926 vereq(m.m1method(), "M1 a")
927 vereq(m.all_method(), "M1 b")
929 class D(C):
930 def dmethod(self):
931 return "D a"
932 def all_method(self):
933 return "D b"
935 class M2(object, D):
936 def m2method(self):
937 return "M2 a"
938 def all_method(self):
939 return "M2 b"
941 vereq(M2.__mro__, (M2, object, D, C))
942 m = M2()
943 vereq(m.cmethod(), "C a")
944 vereq(m.dmethod(), "D a")
945 vereq(m.m2method(), "M2 a")
946 vereq(m.all_method(), "M2 b")
948 class M3(M1, object, M2):
949 def m3method(self):
950 return "M3 a"
951 def all_method(self):
952 return "M3 b"
953 # XXX Expected this (the commented-out result):
954 # vereq(M3.__mro__, (M3, M1, M2, object, D, C))
955 vereq(M3.__mro__, (M3, M1, M2, D, C, object)) # XXX ?
956 m = M3()
957 vereq(m.cmethod(), "C a")
958 vereq(m.dmethod(), "D a")
959 vereq(m.m1method(), "M1 a")
960 vereq(m.m2method(), "M2 a")
961 vereq(m.m3method(), "M3 a")
962 vereq(m.all_method(), "M3 b")
964 class Classic:
965 pass
966 try:
967 class New(Classic):
968 __metaclass__ = type
969 except TypeError:
970 pass
971 else:
972 raise TestFailed, "new class with only classic bases - shouldn't be"
974 def diamond():
975 if verbose: print "Testing multiple inheritance special cases..."
976 class A(object):
977 def spam(self): return "A"
978 vereq(A().spam(), "A")
979 class B(A):
980 def boo(self): return "B"
981 def spam(self): return "B"
982 vereq(B().spam(), "B")
983 vereq(B().boo(), "B")
984 class C(A):
985 def boo(self): return "C"
986 vereq(C().spam(), "A")
987 vereq(C().boo(), "C")
988 class D(B, C): pass
989 vereq(D().spam(), "B")
990 vereq(D().boo(), "B")
991 vereq(D.__mro__, (D, B, C, A, object))
992 class E(C, B): pass
993 vereq(E().spam(), "B")
994 vereq(E().boo(), "C")
995 vereq(E.__mro__, (E, C, B, A, object))
996 class F(D, E): pass
997 vereq(F().spam(), "B")
998 vereq(F().boo(), "B")
999 vereq(F.__mro__, (F, D, E, B, C, A, object))
1000 class G(E, D): pass
1001 vereq(G().spam(), "B")
1002 vereq(G().boo(), "C")
1003 vereq(G.__mro__, (G, E, D, C, B, A, object))
1005 def objects():
1006 if verbose: print "Testing object class..."
1007 a = object()
1008 vereq(a.__class__, object)
1009 vereq(type(a), object)
1010 b = object()
1011 verify(a is not b)
1012 verify(not hasattr(a, "foo"))
1013 try:
1014 a.foo = 12
1015 except (AttributeError, TypeError):
1016 pass
1017 else:
1018 verify(0, "object() should not allow setting a foo attribute")
1019 verify(not hasattr(object(), "__dict__"))
1021 class Cdict(object):
1022 pass
1023 x = Cdict()
1024 vereq(x.__dict__, {})
1025 x.foo = 1
1026 vereq(x.foo, 1)
1027 vereq(x.__dict__, {'foo': 1})
1029 def slots():
1030 if verbose: print "Testing __slots__..."
1031 class C0(object):
1032 __slots__ = []
1033 x = C0()
1034 verify(not hasattr(x, "__dict__"))
1035 verify(not hasattr(x, "foo"))
1037 class C1(object):
1038 __slots__ = ['a']
1039 x = C1()
1040 verify(not hasattr(x, "__dict__"))
1041 verify(not hasattr(x, "a"))
1042 x.a = 1
1043 vereq(x.a, 1)
1044 x.a = None
1045 veris(x.a, None)
1046 del x.a
1047 verify(not hasattr(x, "a"))
1049 class C3(object):
1050 __slots__ = ['a', 'b', 'c']
1051 x = C3()
1052 verify(not hasattr(x, "__dict__"))
1053 verify(not hasattr(x, 'a'))
1054 verify(not hasattr(x, 'b'))
1055 verify(not hasattr(x, 'c'))
1056 x.a = 1
1057 x.b = 2
1058 x.c = 3
1059 vereq(x.a, 1)
1060 vereq(x.b, 2)
1061 vereq(x.c, 3)
1063 class C4(object):
1064 """Validate name mangling"""
1065 __slots__ = ['__a']
1066 def __init__(self, value):
1067 self.__a = value
1068 def get(self):
1069 return self.__a
1070 x = C4(5)
1071 verify(not hasattr(x, '__dict__'))
1072 verify(not hasattr(x, '__a'))
1073 vereq(x.get(), 5)
1074 try:
1075 x.__a = 6
1076 except AttributeError:
1077 pass
1078 else:
1079 raise TestFailed, "Double underscored names not mangled"
1081 # Make sure slot names are proper identifiers
1082 try:
1083 class C(object):
1084 __slots__ = [None]
1085 except TypeError:
1086 pass
1087 else:
1088 raise TestFailed, "[None] slots not caught"
1089 try:
1090 class C(object):
1091 __slots__ = ["foo bar"]
1092 except TypeError:
1093 pass
1094 else:
1095 raise TestFailed, "['foo bar'] slots not caught"
1096 try:
1097 class C(object):
1098 __slots__ = ["foo\0bar"]
1099 except TypeError:
1100 pass
1101 else:
1102 raise TestFailed, "['foo\\0bar'] slots not caught"
1103 try:
1104 class C(object):
1105 __slots__ = ["1"]
1106 except TypeError:
1107 pass
1108 else:
1109 raise TestFailed, "['1'] slots not caught"
1110 try:
1111 class C(object):
1112 __slots__ = [""]
1113 except TypeError:
1114 pass
1115 else:
1116 raise TestFailed, "[''] slots not caught"
1117 class C(object):
1118 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1120 # Test leaks
1121 class Counted(object):
1122 counter = 0 # counts the number of instances alive
1123 def __init__(self):
1124 Counted.counter += 1
1125 def __del__(self):
1126 Counted.counter -= 1
1127 class C(object):
1128 __slots__ = ['a', 'b', 'c']
1129 x = C()
1130 x.a = Counted()
1131 x.b = Counted()
1132 x.c = Counted()
1133 vereq(Counted.counter, 3)
1134 del x
1135 vereq(Counted.counter, 0)
1136 class D(C):
1137 pass
1138 x = D()
1139 x.a = Counted()
1140 x.z = Counted()
1141 vereq(Counted.counter, 2)
1142 del x
1143 vereq(Counted.counter, 0)
1144 class E(D):
1145 __slots__ = ['e']
1146 x = E()
1147 x.a = Counted()
1148 x.z = Counted()
1149 x.e = Counted()
1150 vereq(Counted.counter, 3)
1151 del x
1152 vereq(Counted.counter, 0)
1154 # Test cyclical leaks [SF bug 519621]
1155 class F(object):
1156 __slots__ = ['a', 'b']
1157 log = []
1158 s = F()
1159 s.a = [Counted(), s]
1160 vereq(Counted.counter, 1)
1161 s = None
1162 import gc
1163 gc.collect()
1164 vereq(Counted.counter, 0)
1166 def dynamics():
1167 if verbose: print "Testing class attribute propagation..."
1168 class D(object):
1169 pass
1170 class E(D):
1171 pass
1172 class F(D):
1173 pass
1174 D.foo = 1
1175 vereq(D.foo, 1)
1176 # Test that dynamic attributes are inherited
1177 vereq(E.foo, 1)
1178 vereq(F.foo, 1)
1179 # Test dynamic instances
1180 class C(object):
1181 pass
1182 a = C()
1183 verify(not hasattr(a, "foobar"))
1184 C.foobar = 2
1185 vereq(a.foobar, 2)
1186 C.method = lambda self: 42
1187 vereq(a.method(), 42)
1188 C.__repr__ = lambda self: "C()"
1189 vereq(repr(a), "C()")
1190 C.__int__ = lambda self: 100
1191 vereq(int(a), 100)
1192 vereq(a.foobar, 2)
1193 verify(not hasattr(a, "spam"))
1194 def mygetattr(self, name):
1195 if name == "spam":
1196 return "spam"
1197 raise AttributeError
1198 C.__getattr__ = mygetattr
1199 vereq(a.spam, "spam")
1200 a.new = 12
1201 vereq(a.new, 12)
1202 def mysetattr(self, name, value):
1203 if name == "spam":
1204 raise AttributeError
1205 return object.__setattr__(self, name, value)
1206 C.__setattr__ = mysetattr
1207 try:
1208 a.spam = "not spam"
1209 except AttributeError:
1210 pass
1211 else:
1212 verify(0, "expected AttributeError")
1213 vereq(a.spam, "spam")
1214 class D(C):
1215 pass
1216 d = D()
1217 d.foo = 1
1218 vereq(d.foo, 1)
1220 # Test handling of int*seq and seq*int
1221 class I(int):
1222 pass
1223 vereq("a"*I(2), "aa")
1224 vereq(I(2)*"a", "aa")
1225 vereq(2*I(3), 6)
1226 vereq(I(3)*2, 6)
1227 vereq(I(3)*I(2), 6)
1229 # Test handling of long*seq and seq*long
1230 class L(long):
1231 pass
1232 vereq("a"*L(2L), "aa")
1233 vereq(L(2L)*"a", "aa")
1234 vereq(2*L(3), 6)
1235 vereq(L(3)*2, 6)
1236 vereq(L(3)*L(2), 6)
1238 # Test comparison of classes with dynamic metaclasses
1239 class dynamicmetaclass(type):
1240 pass
1241 class someclass:
1242 __metaclass__ = dynamicmetaclass
1243 verify(someclass != object)
1245 def errors():
1246 if verbose: print "Testing errors..."
1248 try:
1249 class C(list, dict):
1250 pass
1251 except TypeError:
1252 pass
1253 else:
1254 verify(0, "inheritance from both list and dict should be illegal")
1256 try:
1257 class C(object, None):
1258 pass
1259 except TypeError:
1260 pass
1261 else:
1262 verify(0, "inheritance from non-type should be illegal")
1263 class Classic:
1264 pass
1266 try:
1267 class C(type(len)):
1268 pass
1269 except TypeError:
1270 pass
1271 else:
1272 verify(0, "inheritance from CFunction should be illegal")
1274 try:
1275 class C(object):
1276 __slots__ = 1
1277 except TypeError:
1278 pass
1279 else:
1280 verify(0, "__slots__ = 1 should be illegal")
1282 try:
1283 class C(object):
1284 __slots__ = [1]
1285 except TypeError:
1286 pass
1287 else:
1288 verify(0, "__slots__ = [1] should be illegal")
1290 def classmethods():
1291 if verbose: print "Testing class methods..."
1292 class C(object):
1293 def foo(*a): return a
1294 goo = classmethod(foo)
1295 c = C()
1296 vereq(C.goo(1), (C, 1))
1297 vereq(c.goo(1), (C, 1))
1298 vereq(c.foo(1), (c, 1))
1299 class D(C):
1300 pass
1301 d = D()
1302 vereq(D.goo(1), (D, 1))
1303 vereq(d.goo(1), (D, 1))
1304 vereq(d.foo(1), (d, 1))
1305 vereq(D.foo(d, 1), (d, 1))
1306 # Test for a specific crash (SF bug 528132)
1307 def f(cls, arg): return (cls, arg)
1308 ff = classmethod(f)
1309 vereq(ff.__get__(0, int)(42), (int, 42))
1310 vereq(ff.__get__(0)(42), (int, 42))
1312 # Test super() with classmethods (SF bug 535444)
1313 veris(C.goo.im_self, C)
1314 veris(D.goo.im_self, D)
1315 veris(super(D,D).goo.im_self, D)
1316 veris(super(D,d).goo.im_self, D)
1317 vereq(super(D,D).goo(), (D,))
1318 vereq(super(D,d).goo(), (D,))
1320 def classmethods_in_c():
1321 if verbose: print "Testing C-based class methods..."
1322 import xxsubtype as spam
1323 a = (1, 2, 3)
1324 d = {'abc': 123}
1325 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1326 veris(x, None)
1327 vereq((spam.spamlist,) + a, a1)
1328 vereq(d, d1)
1329 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1330 veris(x, None)
1331 vereq((spam.spamlist,) + a, a1)
1332 vereq(d, d1)
1334 def staticmethods():
1335 if verbose: print "Testing static methods..."
1336 class C(object):
1337 def foo(*a): return a
1338 goo = staticmethod(foo)
1339 c = C()
1340 vereq(C.goo(1), (1,))
1341 vereq(c.goo(1), (1,))
1342 vereq(c.foo(1), (c, 1,))
1343 class D(C):
1344 pass
1345 d = D()
1346 vereq(D.goo(1), (1,))
1347 vereq(d.goo(1), (1,))
1348 vereq(d.foo(1), (d, 1))
1349 vereq(D.foo(d, 1), (d, 1))
1351 def staticmethods_in_c():
1352 if verbose: print "Testing C-based static methods..."
1353 import xxsubtype as spam
1354 a = (1, 2, 3)
1355 d = {"abc": 123}
1356 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1357 veris(x, None)
1358 vereq(a, a1)
1359 vereq(d, d1)
1360 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1361 veris(x, None)
1362 vereq(a, a1)
1363 vereq(d, d1)
1365 def classic():
1366 if verbose: print "Testing classic classes..."
1367 class C:
1368 def foo(*a): return a
1369 goo = classmethod(foo)
1370 c = C()
1371 vereq(C.goo(1), (C, 1))
1372 vereq(c.goo(1), (C, 1))
1373 vereq(c.foo(1), (c, 1))
1374 class D(C):
1375 pass
1376 d = D()
1377 vereq(D.goo(1), (D, 1))
1378 vereq(d.goo(1), (D, 1))
1379 vereq(d.foo(1), (d, 1))
1380 vereq(D.foo(d, 1), (d, 1))
1381 class E: # *not* subclassing from C
1382 foo = C.foo
1383 vereq(E().foo, C.foo) # i.e., unbound
1384 verify(repr(C.foo.__get__(C())).startswith("<bound method "))
1386 def compattr():
1387 if verbose: print "Testing computed attributes..."
1388 class C(object):
1389 class computed_attribute(object):
1390 def __init__(self, get, set=None):
1391 self.__get = get
1392 self.__set = set
1393 def __get__(self, obj, type=None):
1394 return self.__get(obj)
1395 def __set__(self, obj, value):
1396 return self.__set(obj, value)
1397 def __init__(self):
1398 self.__x = 0
1399 def __get_x(self):
1400 x = self.__x
1401 self.__x = x+1
1402 return x
1403 def __set_x(self, x):
1404 self.__x = x
1405 x = computed_attribute(__get_x, __set_x)
1406 a = C()
1407 vereq(a.x, 0)
1408 vereq(a.x, 1)
1409 a.x = 10
1410 vereq(a.x, 10)
1411 vereq(a.x, 11)
1413 def newslot():
1414 if verbose: print "Testing __new__ slot override..."
1415 class C(list):
1416 def __new__(cls):
1417 self = list.__new__(cls)
1418 self.foo = 1
1419 return self
1420 def __init__(self):
1421 self.foo = self.foo + 2
1422 a = C()
1423 vereq(a.foo, 3)
1424 verify(a.__class__ is C)
1425 class D(C):
1426 pass
1427 b = D()
1428 vereq(b.foo, 3)
1429 verify(b.__class__ is D)
1431 def altmro():
1432 if verbose: print "Testing mro() and overriding it..."
1433 class A(object):
1434 def f(self): return "A"
1435 class B(A):
1436 pass
1437 class C(A):
1438 def f(self): return "C"
1439 class D(B, C):
1440 pass
1441 vereq(D.mro(), [D, B, C, A, object])
1442 vereq(D.__mro__, (D, B, C, A, object))
1443 vereq(D().f(), "C")
1444 class PerverseMetaType(type):
1445 def mro(cls):
1446 L = type.mro(cls)
1447 L.reverse()
1448 return L
1449 class X(A,B,C,D):
1450 __metaclass__ = PerverseMetaType
1451 vereq(X.__mro__, (object, A, C, B, D, X))
1452 vereq(X().f(), "A")
1454 def overloading():
1455 if verbose: print "Testing operator overloading..."
1457 class B(object):
1458 "Intermediate class because object doesn't have a __setattr__"
1460 class C(B):
1462 def __getattr__(self, name):
1463 if name == "foo":
1464 return ("getattr", name)
1465 else:
1466 raise AttributeError
1467 def __setattr__(self, name, value):
1468 if name == "foo":
1469 self.setattr = (name, value)
1470 else:
1471 return B.__setattr__(self, name, value)
1472 def __delattr__(self, name):
1473 if name == "foo":
1474 self.delattr = name
1475 else:
1476 return B.__delattr__(self, name)
1478 def __getitem__(self, key):
1479 return ("getitem", key)
1480 def __setitem__(self, key, value):
1481 self.setitem = (key, value)
1482 def __delitem__(self, key):
1483 self.delitem = key
1485 def __getslice__(self, i, j):
1486 return ("getslice", i, j)
1487 def __setslice__(self, i, j, value):
1488 self.setslice = (i, j, value)
1489 def __delslice__(self, i, j):
1490 self.delslice = (i, j)
1492 a = C()
1493 vereq(a.foo, ("getattr", "foo"))
1494 a.foo = 12
1495 vereq(a.setattr, ("foo", 12))
1496 del a.foo
1497 vereq(a.delattr, "foo")
1499 vereq(a[12], ("getitem", 12))
1500 a[12] = 21
1501 vereq(a.setitem, (12, 21))
1502 del a[12]
1503 vereq(a.delitem, 12)
1505 vereq(a[0:10], ("getslice", 0, 10))
1506 a[0:10] = "foo"
1507 vereq(a.setslice, (0, 10, "foo"))
1508 del a[0:10]
1509 vereq(a.delslice, (0, 10))
1511 def methods():
1512 if verbose: print "Testing methods..."
1513 class C(object):
1514 def __init__(self, x):
1515 self.x = x
1516 def foo(self):
1517 return self.x
1518 c1 = C(1)
1519 vereq(c1.foo(), 1)
1520 class D(C):
1521 boo = C.foo
1522 goo = c1.foo
1523 d2 = D(2)
1524 vereq(d2.foo(), 2)
1525 vereq(d2.boo(), 2)
1526 vereq(d2.goo(), 1)
1527 class E(object):
1528 foo = C.foo
1529 vereq(E().foo, C.foo) # i.e., unbound
1530 verify(repr(C.foo.__get__(C(1))).startswith("<bound method "))
1532 def specials():
1533 # Test operators like __hash__ for which a built-in default exists
1534 if verbose: print "Testing special operators..."
1535 # Test the default behavior for static classes
1536 class C(object):
1537 def __getitem__(self, i):
1538 if 0 <= i < 10: return i
1539 raise IndexError
1540 c1 = C()
1541 c2 = C()
1542 verify(not not c1)
1543 vereq(hash(c1), id(c1))
1544 vereq(cmp(c1, c2), cmp(id(c1), id(c2)))
1545 vereq(c1, c1)
1546 verify(c1 != c2)
1547 verify(not c1 != c1)
1548 verify(not c1 == c2)
1549 # Note that the module name appears in str/repr, and that varies
1550 # depending on whether this test is run standalone or from a framework.
1551 verify(str(c1).find('C object at ') >= 0)
1552 vereq(str(c1), repr(c1))
1553 verify(-1 not in c1)
1554 for i in range(10):
1555 verify(i in c1)
1556 verify(10 not in c1)
1557 # Test the default behavior for dynamic classes
1558 class D(object):
1559 def __getitem__(self, i):
1560 if 0 <= i < 10: return i
1561 raise IndexError
1562 d1 = D()
1563 d2 = D()
1564 verify(not not d1)
1565 vereq(hash(d1), id(d1))
1566 vereq(cmp(d1, d2), cmp(id(d1), id(d2)))
1567 vereq(d1, d1)
1568 verify(d1 != d2)
1569 verify(not d1 != d1)
1570 verify(not d1 == d2)
1571 # Note that the module name appears in str/repr, and that varies
1572 # depending on whether this test is run standalone or from a framework.
1573 verify(str(d1).find('D object at ') >= 0)
1574 vereq(str(d1), repr(d1))
1575 verify(-1 not in d1)
1576 for i in range(10):
1577 verify(i in d1)
1578 verify(10 not in d1)
1579 # Test overridden behavior for static classes
1580 class Proxy(object):
1581 def __init__(self, x):
1582 self.x = x
1583 def __nonzero__(self):
1584 return not not self.x
1585 def __hash__(self):
1586 return hash(self.x)
1587 def __eq__(self, other):
1588 return self.x == other
1589 def __ne__(self, other):
1590 return self.x != other
1591 def __cmp__(self, other):
1592 return cmp(self.x, other.x)
1593 def __str__(self):
1594 return "Proxy:%s" % self.x
1595 def __repr__(self):
1596 return "Proxy(%r)" % self.x
1597 def __contains__(self, value):
1598 return value in self.x
1599 p0 = Proxy(0)
1600 p1 = Proxy(1)
1601 p_1 = Proxy(-1)
1602 verify(not p0)
1603 verify(not not p1)
1604 vereq(hash(p0), hash(0))
1605 vereq(p0, p0)
1606 verify(p0 != p1)
1607 verify(not p0 != p0)
1608 vereq(not p0, p1)
1609 vereq(cmp(p0, p1), -1)
1610 vereq(cmp(p0, p0), 0)
1611 vereq(cmp(p0, p_1), 1)
1612 vereq(str(p0), "Proxy:0")
1613 vereq(repr(p0), "Proxy(0)")
1614 p10 = Proxy(range(10))
1615 verify(-1 not in p10)
1616 for i in range(10):
1617 verify(i in p10)
1618 verify(10 not in p10)
1619 # Test overridden behavior for dynamic classes
1620 class DProxy(object):
1621 def __init__(self, x):
1622 self.x = x
1623 def __nonzero__(self):
1624 return not not self.x
1625 def __hash__(self):
1626 return hash(self.x)
1627 def __eq__(self, other):
1628 return self.x == other
1629 def __ne__(self, other):
1630 return self.x != other
1631 def __cmp__(self, other):
1632 return cmp(self.x, other.x)
1633 def __str__(self):
1634 return "DProxy:%s" % self.x
1635 def __repr__(self):
1636 return "DProxy(%r)" % self.x
1637 def __contains__(self, value):
1638 return value in self.x
1639 p0 = DProxy(0)
1640 p1 = DProxy(1)
1641 p_1 = DProxy(-1)
1642 verify(not p0)
1643 verify(not not p1)
1644 vereq(hash(p0), hash(0))
1645 vereq(p0, p0)
1646 verify(p0 != p1)
1647 verify(not p0 != p0)
1648 vereq(not p0, p1)
1649 vereq(cmp(p0, p1), -1)
1650 vereq(cmp(p0, p0), 0)
1651 vereq(cmp(p0, p_1), 1)
1652 vereq(str(p0), "DProxy:0")
1653 vereq(repr(p0), "DProxy(0)")
1654 p10 = DProxy(range(10))
1655 verify(-1 not in p10)
1656 for i in range(10):
1657 verify(i in p10)
1658 verify(10 not in p10)
1659 # Safety test for __cmp__
1660 def unsafecmp(a, b):
1661 try:
1662 a.__class__.__cmp__(a, b)
1663 except TypeError:
1664 pass
1665 else:
1666 raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % (
1667 a.__class__, a, b)
1668 unsafecmp(u"123", "123")
1669 unsafecmp("123", u"123")
1670 unsafecmp(1, 1.0)
1671 unsafecmp(1.0, 1)
1672 unsafecmp(1, 1L)
1673 unsafecmp(1L, 1)
1675 def weakrefs():
1676 if verbose: print "Testing weak references..."
1677 import weakref
1678 class C(object):
1679 pass
1680 c = C()
1681 r = weakref.ref(c)
1682 verify(r() is c)
1683 del c
1684 verify(r() is None)
1685 del r
1686 class NoWeak(object):
1687 __slots__ = ['foo']
1688 no = NoWeak()
1689 try:
1690 weakref.ref(no)
1691 except TypeError, msg:
1692 verify(str(msg).find("weak reference") >= 0)
1693 else:
1694 verify(0, "weakref.ref(no) should be illegal")
1695 class Weak(object):
1696 __slots__ = ['foo', '__weakref__']
1697 yes = Weak()
1698 r = weakref.ref(yes)
1699 verify(r() is yes)
1700 del yes
1701 verify(r() is None)
1702 del r
1704 def properties():
1705 if verbose: print "Testing property..."
1706 class C(object):
1707 def getx(self):
1708 return self.__x
1709 def setx(self, value):
1710 self.__x = value
1711 def delx(self):
1712 del self.__x
1713 x = property(getx, setx, delx, doc="I'm the x property.")
1714 a = C()
1715 verify(not hasattr(a, "x"))
1716 a.x = 42
1717 vereq(a._C__x, 42)
1718 vereq(a.x, 42)
1719 del a.x
1720 verify(not hasattr(a, "x"))
1721 verify(not hasattr(a, "_C__x"))
1722 C.x.__set__(a, 100)
1723 vereq(C.x.__get__(a), 100)
1724 ## C.x.__set__(a)
1725 ## verify(not hasattr(a, "x"))
1727 raw = C.__dict__['x']
1728 verify(isinstance(raw, property))
1730 attrs = dir(raw)
1731 verify("__doc__" in attrs)
1732 verify("fget" in attrs)
1733 verify("fset" in attrs)
1734 verify("fdel" in attrs)
1736 vereq(raw.__doc__, "I'm the x property.")
1737 verify(raw.fget is C.__dict__['getx'])
1738 verify(raw.fset is C.__dict__['setx'])
1739 verify(raw.fdel is C.__dict__['delx'])
1741 for attr in "__doc__", "fget", "fset", "fdel":
1742 try:
1743 setattr(raw, attr, 42)
1744 except TypeError, msg:
1745 if str(msg).find('readonly') < 0:
1746 raise TestFailed("when setting readonly attr %r on a "
1747 "property, got unexpected TypeError "
1748 "msg %r" % (attr, str(msg)))
1749 else:
1750 raise TestFailed("expected TypeError from trying to set "
1751 "readonly %r attr on a property" % attr)
1753 def supers():
1754 if verbose: print "Testing super..."
1756 class A(object):
1757 def meth(self, a):
1758 return "A(%r)" % a
1760 vereq(A().meth(1), "A(1)")
1762 class B(A):
1763 def __init__(self):
1764 self.__super = super(B, self)
1765 def meth(self, a):
1766 return "B(%r)" % a + self.__super.meth(a)
1768 vereq(B().meth(2), "B(2)A(2)")
1770 class C(A):
1771 def meth(self, a):
1772 return "C(%r)" % a + self.__super.meth(a)
1773 C._C__super = super(C)
1775 vereq(C().meth(3), "C(3)A(3)")
1777 class D(C, B):
1778 def meth(self, a):
1779 return "D(%r)" % a + super(D, self).meth(a)
1781 vereq(D().meth(4), "D(4)C(4)B(4)A(4)")
1783 # Test for subclassing super
1785 class mysuper(super):
1786 def __init__(self, *args):
1787 return super(mysuper, self).__init__(*args)
1789 class E(D):
1790 def meth(self, a):
1791 return "E(%r)" % a + mysuper(E, self).meth(a)
1793 vereq(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
1795 class F(E):
1796 def meth(self, a):
1797 s = self.__super
1798 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
1799 F._F__super = mysuper(F)
1801 vereq(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
1803 # Make sure certain errors are raised
1805 try:
1806 super(D, 42)
1807 except TypeError:
1808 pass
1809 else:
1810 raise TestFailed, "shouldn't allow super(D, 42)"
1812 try:
1813 super(D, C())
1814 except TypeError:
1815 pass
1816 else:
1817 raise TestFailed, "shouldn't allow super(D, C())"
1819 try:
1820 super(D).__get__(12)
1821 except TypeError:
1822 pass
1823 else:
1824 raise TestFailed, "shouldn't allow super(D).__get__(12)"
1826 try:
1827 super(D).__get__(C())
1828 except TypeError:
1829 pass
1830 else:
1831 raise TestFailed, "shouldn't allow super(D).__get__(C())"
1833 def inherits():
1834 if verbose: print "Testing inheritance from basic types..."
1836 class hexint(int):
1837 def __repr__(self):
1838 return hex(self)
1839 def __add__(self, other):
1840 return hexint(int.__add__(self, other))
1841 # (Note that overriding __radd__ doesn't work,
1842 # because the int type gets first dibs.)
1843 vereq(repr(hexint(7) + 9), "0x10")
1844 vereq(repr(hexint(1000) + 7), "0x3ef")
1845 a = hexint(12345)
1846 vereq(a, 12345)
1847 vereq(int(a), 12345)
1848 verify(int(a).__class__ is int)
1849 vereq(hash(a), hash(12345))
1850 verify((+a).__class__ is int)
1851 verify((a >> 0).__class__ is int)
1852 verify((a << 0).__class__ is int)
1853 verify((hexint(0) << 12).__class__ is int)
1854 verify((hexint(0) >> 12).__class__ is int)
1856 class octlong(long):
1857 __slots__ = []
1858 def __str__(self):
1859 s = oct(self)
1860 if s[-1] == 'L':
1861 s = s[:-1]
1862 return s
1863 def __add__(self, other):
1864 return self.__class__(super(octlong, self).__add__(other))
1865 __radd__ = __add__
1866 vereq(str(octlong(3) + 5), "010")
1867 # (Note that overriding __radd__ here only seems to work
1868 # because the example uses a short int left argument.)
1869 vereq(str(5 + octlong(3000)), "05675")
1870 a = octlong(12345)
1871 vereq(a, 12345L)
1872 vereq(long(a), 12345L)
1873 vereq(hash(a), hash(12345L))
1874 verify(long(a).__class__ is long)
1875 verify((+a).__class__ is long)
1876 verify((-a).__class__ is long)
1877 verify((-octlong(0)).__class__ is long)
1878 verify((a >> 0).__class__ is long)
1879 verify((a << 0).__class__ is long)
1880 verify((a - 0).__class__ is long)
1881 verify((a * 1).__class__ is long)
1882 verify((a ** 1).__class__ is long)
1883 verify((a // 1).__class__ is long)
1884 verify((1 * a).__class__ is long)
1885 verify((a | 0).__class__ is long)
1886 verify((a ^ 0).__class__ is long)
1887 verify((a & -1L).__class__ is long)
1888 verify((octlong(0) << 12).__class__ is long)
1889 verify((octlong(0) >> 12).__class__ is long)
1890 verify(abs(octlong(0)).__class__ is long)
1892 # Because octlong overrides __add__, we can't check the absence of +0
1893 # optimizations using octlong.
1894 class longclone(long):
1895 pass
1896 a = longclone(1)
1897 verify((a + 0).__class__ is long)
1898 verify((0 + a).__class__ is long)
1900 # Check that negative clones don't segfault
1901 a = longclone(-1)
1902 vereq(a.__dict__, {})
1903 vereq(long(a), -1) # verify PyNumber_Long() copies the sign bit
1905 class precfloat(float):
1906 __slots__ = ['prec']
1907 def __init__(self, value=0.0, prec=12):
1908 self.prec = int(prec)
1909 float.__init__(value)
1910 def __repr__(self):
1911 return "%.*g" % (self.prec, self)
1912 vereq(repr(precfloat(1.1)), "1.1")
1913 a = precfloat(12345)
1914 vereq(a, 12345.0)
1915 vereq(float(a), 12345.0)
1916 verify(float(a).__class__ is float)
1917 vereq(hash(a), hash(12345.0))
1918 verify((+a).__class__ is float)
1920 class madcomplex(complex):
1921 def __repr__(self):
1922 return "%.17gj%+.17g" % (self.imag, self.real)
1923 a = madcomplex(-3, 4)
1924 vereq(repr(a), "4j-3")
1925 base = complex(-3, 4)
1926 veris(base.__class__, complex)
1927 vereq(a, base)
1928 vereq(complex(a), base)
1929 veris(complex(a).__class__, complex)
1930 a = madcomplex(a) # just trying another form of the constructor
1931 vereq(repr(a), "4j-3")
1932 vereq(a, base)
1933 vereq(complex(a), base)
1934 veris(complex(a).__class__, complex)
1935 vereq(hash(a), hash(base))
1936 veris((+a).__class__, complex)
1937 veris((a + 0).__class__, complex)
1938 vereq(a + 0, base)
1939 veris((a - 0).__class__, complex)
1940 vereq(a - 0, base)
1941 veris((a * 1).__class__, complex)
1942 vereq(a * 1, base)
1943 veris((a / 1).__class__, complex)
1944 vereq(a / 1, base)
1946 class madtuple(tuple):
1947 _rev = None
1948 def rev(self):
1949 if self._rev is not None:
1950 return self._rev
1951 L = list(self)
1952 L.reverse()
1953 self._rev = self.__class__(L)
1954 return self._rev
1955 a = madtuple((1,2,3,4,5,6,7,8,9,0))
1956 vereq(a, (1,2,3,4,5,6,7,8,9,0))
1957 vereq(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
1958 vereq(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
1959 for i in range(512):
1960 t = madtuple(range(i))
1961 u = t.rev()
1962 v = u.rev()
1963 vereq(v, t)
1964 a = madtuple((1,2,3,4,5))
1965 vereq(tuple(a), (1,2,3,4,5))
1966 verify(tuple(a).__class__ is tuple)
1967 vereq(hash(a), hash((1,2,3,4,5)))
1968 verify(a[:].__class__ is tuple)
1969 verify((a * 1).__class__ is tuple)
1970 verify((a * 0).__class__ is tuple)
1971 verify((a + ()).__class__ is tuple)
1972 a = madtuple(())
1973 vereq(tuple(a), ())
1974 verify(tuple(a).__class__ is tuple)
1975 verify((a + a).__class__ is tuple)
1976 verify((a * 0).__class__ is tuple)
1977 verify((a * 1).__class__ is tuple)
1978 verify((a * 2).__class__ is tuple)
1979 verify(a[:].__class__ is tuple)
1981 class madstring(str):
1982 _rev = None
1983 def rev(self):
1984 if self._rev is not None:
1985 return self._rev
1986 L = list(self)
1987 L.reverse()
1988 self._rev = self.__class__("".join(L))
1989 return self._rev
1990 s = madstring("abcdefghijklmnopqrstuvwxyz")
1991 vereq(s, "abcdefghijklmnopqrstuvwxyz")
1992 vereq(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
1993 vereq(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
1994 for i in range(256):
1995 s = madstring("".join(map(chr, range(i))))
1996 t = s.rev()
1997 u = t.rev()
1998 vereq(u, s)
1999 s = madstring("12345")
2000 vereq(str(s), "12345")
2001 verify(str(s).__class__ is str)
2003 base = "\x00" * 5
2004 s = madstring(base)
2005 vereq(s, base)
2006 vereq(str(s), base)
2007 verify(str(s).__class__ is str)
2008 vereq(hash(s), hash(base))
2009 vereq({s: 1}[base], 1)
2010 vereq({base: 1}[s], 1)
2011 verify((s + "").__class__ is str)
2012 vereq(s + "", base)
2013 verify(("" + s).__class__ is str)
2014 vereq("" + s, base)
2015 verify((s * 0).__class__ is str)
2016 vereq(s * 0, "")
2017 verify((s * 1).__class__ is str)
2018 vereq(s * 1, base)
2019 verify((s * 2).__class__ is str)
2020 vereq(s * 2, base + base)
2021 verify(s[:].__class__ is str)
2022 vereq(s[:], base)
2023 verify(s[0:0].__class__ is str)
2024 vereq(s[0:0], "")
2025 verify(s.strip().__class__ is str)
2026 vereq(s.strip(), base)
2027 verify(s.lstrip().__class__ is str)
2028 vereq(s.lstrip(), base)
2029 verify(s.rstrip().__class__ is str)
2030 vereq(s.rstrip(), base)
2031 identitytab = ''.join([chr(i) for i in range(256)])
2032 verify(s.translate(identitytab).__class__ is str)
2033 vereq(s.translate(identitytab), base)
2034 verify(s.translate(identitytab, "x").__class__ is str)
2035 vereq(s.translate(identitytab, "x"), base)
2036 vereq(s.translate(identitytab, "\x00"), "")
2037 verify(s.replace("x", "x").__class__ is str)
2038 vereq(s.replace("x", "x"), base)
2039 verify(s.ljust(len(s)).__class__ is str)
2040 vereq(s.ljust(len(s)), base)
2041 verify(s.rjust(len(s)).__class__ is str)
2042 vereq(s.rjust(len(s)), base)
2043 verify(s.center(len(s)).__class__ is str)
2044 vereq(s.center(len(s)), base)
2045 verify(s.lower().__class__ is str)
2046 vereq(s.lower(), base)
2048 s = madstring("x y")
2049 vereq(s, "x y")
2050 verify(intern(s).__class__ is str)
2051 verify(intern(s) is intern("x y"))
2052 vereq(intern(s), "x y")
2054 i = intern("y x")
2055 s = madstring("y x")
2056 vereq(s, i)
2057 verify(intern(s).__class__ is str)
2058 verify(intern(s) is i)
2060 s = madstring(i)
2061 verify(intern(s).__class__ is str)
2062 verify(intern(s) is i)
2064 class madunicode(unicode):
2065 _rev = None
2066 def rev(self):
2067 if self._rev is not None:
2068 return self._rev
2069 L = list(self)
2070 L.reverse()
2071 self._rev = self.__class__(u"".join(L))
2072 return self._rev
2073 u = madunicode("ABCDEF")
2074 vereq(u, u"ABCDEF")
2075 vereq(u.rev(), madunicode(u"FEDCBA"))
2076 vereq(u.rev().rev(), madunicode(u"ABCDEF"))
2077 base = u"12345"
2078 u = madunicode(base)
2079 vereq(unicode(u), base)
2080 verify(unicode(u).__class__ is unicode)
2081 vereq(hash(u), hash(base))
2082 vereq({u: 1}[base], 1)
2083 vereq({base: 1}[u], 1)
2084 verify(u.strip().__class__ is unicode)
2085 vereq(u.strip(), base)
2086 verify(u.lstrip().__class__ is unicode)
2087 vereq(u.lstrip(), base)
2088 verify(u.rstrip().__class__ is unicode)
2089 vereq(u.rstrip(), base)
2090 verify(u.replace(u"x", u"x").__class__ is unicode)
2091 vereq(u.replace(u"x", u"x"), base)
2092 verify(u.replace(u"xy", u"xy").__class__ is unicode)
2093 vereq(u.replace(u"xy", u"xy"), base)
2094 verify(u.center(len(u)).__class__ is unicode)
2095 vereq(u.center(len(u)), base)
2096 verify(u.ljust(len(u)).__class__ is unicode)
2097 vereq(u.ljust(len(u)), base)
2098 verify(u.rjust(len(u)).__class__ is unicode)
2099 vereq(u.rjust(len(u)), base)
2100 verify(u.lower().__class__ is unicode)
2101 vereq(u.lower(), base)
2102 verify(u.upper().__class__ is unicode)
2103 vereq(u.upper(), base)
2104 verify(u.capitalize().__class__ is unicode)
2105 vereq(u.capitalize(), base)
2106 verify(u.title().__class__ is unicode)
2107 vereq(u.title(), base)
2108 verify((u + u"").__class__ is unicode)
2109 vereq(u + u"", base)
2110 verify((u"" + u).__class__ is unicode)
2111 vereq(u"" + u, base)
2112 verify((u * 0).__class__ is unicode)
2113 vereq(u * 0, u"")
2114 verify((u * 1).__class__ is unicode)
2115 vereq(u * 1, base)
2116 verify((u * 2).__class__ is unicode)
2117 vereq(u * 2, base + base)
2118 verify(u[:].__class__ is unicode)
2119 vereq(u[:], base)
2120 verify(u[0:0].__class__ is unicode)
2121 vereq(u[0:0], u"")
2123 class sublist(list):
2124 pass
2125 a = sublist(range(5))
2126 vereq(a, range(5))
2127 a.append("hello")
2128 vereq(a, range(5) + ["hello"])
2129 a[5] = 5
2130 vereq(a, range(6))
2131 a.extend(range(6, 20))
2132 vereq(a, range(20))
2133 a[-5:] = []
2134 vereq(a, range(15))
2135 del a[10:15]
2136 vereq(len(a), 10)
2137 vereq(a, range(10))
2138 vereq(list(a), range(10))
2139 vereq(a[0], 0)
2140 vereq(a[9], 9)
2141 vereq(a[-10], 0)
2142 vereq(a[-1], 9)
2143 vereq(a[:5], range(5))
2145 class CountedInput(file):
2146 """Counts lines read by self.readline().
2148 self.lineno is the 0-based ordinal of the last line read, up to
2149 a maximum of one greater than the number of lines in the file.
2151 self.ateof is true if and only if the final "" line has been read,
2152 at which point self.lineno stops incrementing, and further calls
2153 to readline() continue to return "".
2156 lineno = 0
2157 ateof = 0
2158 def readline(self):
2159 if self.ateof:
2160 return ""
2161 s = file.readline(self)
2162 # Next line works too.
2163 # s = super(CountedInput, self).readline()
2164 self.lineno += 1
2165 if s == "":
2166 self.ateof = 1
2167 return s
2169 f = file(name=TESTFN, mode='w')
2170 lines = ['a\n', 'b\n', 'c\n']
2171 try:
2172 f.writelines(lines)
2173 f.close()
2174 f = CountedInput(TESTFN)
2175 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2176 got = f.readline()
2177 vereq(expected, got)
2178 vereq(f.lineno, i)
2179 vereq(f.ateof, (i > len(lines)))
2180 f.close()
2181 finally:
2182 try:
2183 f.close()
2184 except:
2185 pass
2186 try:
2187 import os
2188 os.unlink(TESTFN)
2189 except:
2190 pass
2192 def keywords():
2193 if verbose:
2194 print "Testing keyword args to basic type constructors ..."
2195 vereq(int(x=1), 1)
2196 vereq(float(x=2), 2.0)
2197 vereq(long(x=3), 3L)
2198 vereq(complex(imag=42, real=666), complex(666, 42))
2199 vereq(str(object=500), '500')
2200 vereq(unicode(string='abc', errors='strict'), u'abc')
2201 vereq(tuple(sequence=range(3)), (0, 1, 2))
2202 vereq(list(sequence=(0, 1, 2)), range(3))
2203 vereq(dict(items={1: 2}), {1: 2})
2205 for constructor in (int, float, long, complex, str, unicode,
2206 tuple, list, dict, file):
2207 try:
2208 constructor(bogus_keyword_arg=1)
2209 except TypeError:
2210 pass
2211 else:
2212 raise TestFailed("expected TypeError from bogus keyword "
2213 "argument to %r" % constructor)
2215 def restricted():
2216 import rexec
2217 if verbose:
2218 print "Testing interaction with restricted execution ..."
2220 sandbox = rexec.RExec()
2222 code1 = """f = open(%r, 'w')""" % TESTFN
2223 code2 = """f = file(%r, 'w')""" % TESTFN
2224 code3 = """\
2225 f = open(%r)
2226 t = type(f) # a sneaky way to get the file() constructor
2227 f.close()
2228 f = t(%r, 'w') # rexec can't catch this by itself
2229 """ % (TESTFN, TESTFN)
2231 f = open(TESTFN, 'w') # Create the file so code3 can find it.
2232 f.close()
2234 try:
2235 for code in code1, code2, code3:
2236 try:
2237 sandbox.r_exec(code)
2238 except IOError, msg:
2239 if str(msg).find("restricted") >= 0:
2240 outcome = "OK"
2241 else:
2242 outcome = "got an exception, but not an expected one"
2243 else:
2244 outcome = "expected a restricted-execution exception"
2246 if outcome != "OK":
2247 raise TestFailed("%s, in %r" % (outcome, code))
2249 finally:
2250 try:
2251 import os
2252 os.unlink(TESTFN)
2253 except:
2254 pass
2256 def str_subclass_as_dict_key():
2257 if verbose:
2258 print "Testing a str subclass used as dict key .."
2260 class cistr(str):
2261 """Sublcass of str that computes __eq__ case-insensitively.
2263 Also computes a hash code of the string in canonical form.
2266 def __init__(self, value):
2267 self.canonical = value.lower()
2268 self.hashcode = hash(self.canonical)
2270 def __eq__(self, other):
2271 if not isinstance(other, cistr):
2272 other = cistr(other)
2273 return self.canonical == other.canonical
2275 def __hash__(self):
2276 return self.hashcode
2278 vereq(cistr('ABC'), 'abc')
2279 vereq('aBc', cistr('ABC'))
2280 vereq(str(cistr('ABC')), 'ABC')
2282 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2283 vereq(d[cistr('one')], 1)
2284 vereq(d[cistr('tWo')], 2)
2285 vereq(d[cistr('THrEE')], 3)
2286 verify(cistr('ONe') in d)
2287 vereq(d.get(cistr('thrEE')), 3)
2289 def classic_comparisons():
2290 if verbose: print "Testing classic comparisons..."
2291 class classic:
2292 pass
2293 for base in (classic, int, object):
2294 if verbose: print " (base = %s)" % base
2295 class C(base):
2296 def __init__(self, value):
2297 self.value = int(value)
2298 def __cmp__(self, other):
2299 if isinstance(other, C):
2300 return cmp(self.value, other.value)
2301 if isinstance(other, int) or isinstance(other, long):
2302 return cmp(self.value, other)
2303 return NotImplemented
2304 c1 = C(1)
2305 c2 = C(2)
2306 c3 = C(3)
2307 vereq(c1, 1)
2308 c = {1: c1, 2: c2, 3: c3}
2309 for x in 1, 2, 3:
2310 for y in 1, 2, 3:
2311 verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2312 for op in "<", "<=", "==", "!=", ">", ">=":
2313 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2314 "x=%d, y=%d" % (x, y))
2315 verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2316 verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
2318 def rich_comparisons():
2319 if verbose:
2320 print "Testing rich comparisons..."
2321 class Z(complex):
2322 pass
2323 z = Z(1)
2324 vereq(z, 1+0j)
2325 vereq(1+0j, z)
2326 class ZZ(complex):
2327 def __eq__(self, other):
2328 try:
2329 return abs(self - other) <= 1e-6
2330 except:
2331 return NotImplemented
2332 zz = ZZ(1.0000003)
2333 vereq(zz, 1+0j)
2334 vereq(1+0j, zz)
2336 class classic:
2337 pass
2338 for base in (classic, int, object, list):
2339 if verbose: print " (base = %s)" % base
2340 class C(base):
2341 def __init__(self, value):
2342 self.value = int(value)
2343 def __cmp__(self, other):
2344 raise TestFailed, "shouldn't call __cmp__"
2345 def __eq__(self, other):
2346 if isinstance(other, C):
2347 return self.value == other.value
2348 if isinstance(other, int) or isinstance(other, long):
2349 return self.value == other
2350 return NotImplemented
2351 def __ne__(self, other):
2352 if isinstance(other, C):
2353 return self.value != other.value
2354 if isinstance(other, int) or isinstance(other, long):
2355 return self.value != other
2356 return NotImplemented
2357 def __lt__(self, other):
2358 if isinstance(other, C):
2359 return self.value < other.value
2360 if isinstance(other, int) or isinstance(other, long):
2361 return self.value < other
2362 return NotImplemented
2363 def __le__(self, other):
2364 if isinstance(other, C):
2365 return self.value <= other.value
2366 if isinstance(other, int) or isinstance(other, long):
2367 return self.value <= other
2368 return NotImplemented
2369 def __gt__(self, other):
2370 if isinstance(other, C):
2371 return self.value > other.value
2372 if isinstance(other, int) or isinstance(other, long):
2373 return self.value > other
2374 return NotImplemented
2375 def __ge__(self, other):
2376 if isinstance(other, C):
2377 return self.value >= other.value
2378 if isinstance(other, int) or isinstance(other, long):
2379 return self.value >= other
2380 return NotImplemented
2381 c1 = C(1)
2382 c2 = C(2)
2383 c3 = C(3)
2384 vereq(c1, 1)
2385 c = {1: c1, 2: c2, 3: c3}
2386 for x in 1, 2, 3:
2387 for y in 1, 2, 3:
2388 for op in "<", "<=", "==", "!=", ">", ">=":
2389 verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
2390 "x=%d, y=%d" % (x, y))
2391 verify(eval("c[x] %s y" % op) == eval("x %s y" % op),
2392 "x=%d, y=%d" % (x, y))
2393 verify(eval("x %s c[y]" % op) == eval("x %s y" % op),
2394 "x=%d, y=%d" % (x, y))
2396 def coercions():
2397 if verbose: print "Testing coercions..."
2398 class I(int): pass
2399 coerce(I(0), 0)
2400 coerce(0, I(0))
2401 class L(long): pass
2402 coerce(L(0), 0)
2403 coerce(L(0), 0L)
2404 coerce(0, L(0))
2405 coerce(0L, L(0))
2406 class F(float): pass
2407 coerce(F(0), 0)
2408 coerce(F(0), 0L)
2409 coerce(F(0), 0.)
2410 coerce(0, F(0))
2411 coerce(0L, F(0))
2412 coerce(0., F(0))
2413 class C(complex): pass
2414 coerce(C(0), 0)
2415 coerce(C(0), 0L)
2416 coerce(C(0), 0.)
2417 coerce(C(0), 0j)
2418 coerce(0, C(0))
2419 coerce(0L, C(0))
2420 coerce(0., C(0))
2421 coerce(0j, C(0))
2423 def descrdoc():
2424 if verbose: print "Testing descriptor doc strings..."
2425 def check(descr, what):
2426 vereq(descr.__doc__, what)
2427 check(file.closed, "True if the file is closed") # getset descriptor
2428 check(file.name, "file name") # member descriptor
2430 def setclass():
2431 if verbose: print "Testing __class__ assignment..."
2432 class C(object): pass
2433 class D(object): pass
2434 class E(object): pass
2435 class F(D, E): pass
2436 for cls in C, D, E, F:
2437 for cls2 in C, D, E, F:
2438 x = cls()
2439 x.__class__ = cls2
2440 verify(x.__class__ is cls2)
2441 x.__class__ = cls
2442 verify(x.__class__ is cls)
2443 def cant(x, C):
2444 try:
2445 x.__class__ = C
2446 except TypeError:
2447 pass
2448 else:
2449 raise TestFailed, "shouldn't allow %r.__class__ = %r" % (x, C)
2450 try:
2451 delattr(x, "__class__")
2452 except TypeError:
2453 pass
2454 else:
2455 raise TestFailed, "shouldn't allow del %r.__class__" % x
2456 cant(C(), list)
2457 cant(list(), C)
2458 cant(C(), 1)
2459 cant(C(), object)
2460 cant(object(), list)
2461 cant(list(), object)
2463 def setdict():
2464 if verbose: print "Testing __dict__ assignment..."
2465 class C(object): pass
2466 a = C()
2467 a.__dict__ = {'b': 1}
2468 vereq(a.b, 1)
2469 def cant(x, dict):
2470 try:
2471 x.__dict__ = dict
2472 except TypeError:
2473 pass
2474 else:
2475 raise TestFailed, "shouldn't allow %r.__dict__ = %r" % (x, dict)
2476 cant(a, None)
2477 cant(a, [])
2478 cant(a, 1)
2479 del a.__dict__ # Deleting __dict__ is allowed
2480 # Classes don't allow __dict__ assignment
2481 cant(C, {})
2483 def pickles():
2484 if verbose:
2485 print "Testing pickling and copying new-style classes and objects..."
2486 import pickle, cPickle
2488 def sorteditems(d):
2489 L = d.items()
2490 L.sort()
2491 return L
2493 global C
2494 class C(object):
2495 def __init__(self, a, b):
2496 super(C, self).__init__()
2497 self.a = a
2498 self.b = b
2499 def __repr__(self):
2500 return "C(%r, %r)" % (self.a, self.b)
2502 global C1
2503 class C1(list):
2504 def __new__(cls, a, b):
2505 return super(C1, cls).__new__(cls)
2506 def __init__(self, a, b):
2507 self.a = a
2508 self.b = b
2509 def __repr__(self):
2510 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2512 global C2
2513 class C2(int):
2514 def __new__(cls, a, b, val=0):
2515 return super(C2, cls).__new__(cls, val)
2516 def __init__(self, a, b, val=0):
2517 self.a = a
2518 self.b = b
2519 def __repr__(self):
2520 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2522 global C3
2523 class C3(object):
2524 def __init__(self, foo):
2525 self.foo = foo
2526 def __getstate__(self):
2527 return self.foo
2528 def __setstate__(self, foo):
2529 self.foo = foo
2531 global C4classic, C4
2532 class C4classic: # classic
2533 pass
2534 class C4(C4classic, object): # mixed inheritance
2535 pass
2537 for p in pickle, cPickle:
2538 for bin in 0, 1:
2539 if verbose:
2540 print p.__name__, ["text", "binary"][bin]
2542 for cls in C, C1, C2:
2543 s = p.dumps(cls, bin)
2544 cls2 = p.loads(s)
2545 verify(cls2 is cls)
2547 a = C1(1, 2); a.append(42); a.append(24)
2548 b = C2("hello", "world", 42)
2549 s = p.dumps((a, b), bin)
2550 x, y = p.loads(s)
2551 vereq(x.__class__, a.__class__)
2552 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2553 vereq(y.__class__, b.__class__)
2554 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
2555 vereq(`x`, `a`)
2556 vereq(`y`, `b`)
2557 if verbose:
2558 print "a = x =", a
2559 print "b = y =", b
2560 # Test for __getstate__ and __setstate__ on new style class
2561 u = C3(42)
2562 s = p.dumps(u, bin)
2563 v = p.loads(s)
2564 veris(u.__class__, v.__class__)
2565 vereq(u.foo, v.foo)
2566 # Test for picklability of hybrid class
2567 u = C4()
2568 u.foo = 42
2569 s = p.dumps(u, bin)
2570 v = p.loads(s)
2571 veris(u.__class__, v.__class__)
2572 vereq(u.foo, v.foo)
2574 # Testing copy.deepcopy()
2575 if verbose:
2576 print "deepcopy"
2577 import copy
2578 for cls in C, C1, C2:
2579 cls2 = copy.deepcopy(cls)
2580 verify(cls2 is cls)
2582 a = C1(1, 2); a.append(42); a.append(24)
2583 b = C2("hello", "world", 42)
2584 x, y = copy.deepcopy((a, b))
2585 vereq(x.__class__, a.__class__)
2586 vereq(sorteditems(x.__dict__), sorteditems(a.__dict__))
2587 vereq(y.__class__, b.__class__)
2588 vereq(sorteditems(y.__dict__), sorteditems(b.__dict__))
2589 vereq(`x`, `a`)
2590 vereq(`y`, `b`)
2591 if verbose:
2592 print "a = x =", a
2593 print "b = y =", b
2595 def pickleslots():
2596 if verbose: print "Testing pickling of classes with __slots__ ..."
2597 import pickle, cPickle
2598 # Pickling of classes with __slots__ but without __getstate__ should fail
2599 global B, C, D, E
2600 class B(object):
2601 pass
2602 for base in [object, B]:
2603 class C(base):
2604 __slots__ = ['a']
2605 class D(C):
2606 pass
2607 try:
2608 pickle.dumps(C())
2609 except TypeError:
2610 pass
2611 else:
2612 raise TestFailed, "should fail: pickle C instance - %s" % base
2613 try:
2614 cPickle.dumps(C())
2615 except TypeError:
2616 pass
2617 else:
2618 raise TestFailed, "should fail: cPickle C instance - %s" % base
2619 try:
2620 pickle.dumps(C())
2621 except TypeError:
2622 pass
2623 else:
2624 raise TestFailed, "should fail: pickle D instance - %s" % base
2625 try:
2626 cPickle.dumps(D())
2627 except TypeError:
2628 pass
2629 else:
2630 raise TestFailed, "should fail: cPickle D instance - %s" % base
2631 # Give C a __getstate__ and __setstate__
2632 class C(base):
2633 __slots__ = ['a']
2634 def __getstate__(self):
2635 try:
2636 d = self.__dict__.copy()
2637 except AttributeError:
2638 d = {}
2639 try:
2640 d['a'] = self.a
2641 except AttributeError:
2642 pass
2643 return d
2644 def __setstate__(self, d):
2645 for k, v in d.items():
2646 setattr(self, k, v)
2647 class D(C):
2648 pass
2649 # Now it should work
2650 x = C()
2651 y = pickle.loads(pickle.dumps(x))
2652 vereq(hasattr(y, 'a'), 0)
2653 y = cPickle.loads(cPickle.dumps(x))
2654 vereq(hasattr(y, 'a'), 0)
2655 x.a = 42
2656 y = pickle.loads(pickle.dumps(x))
2657 vereq(y.a, 42)
2658 y = cPickle.loads(cPickle.dumps(x))
2659 vereq(y.a, 42)
2660 x = D()
2661 x.a = 42
2662 x.b = 100
2663 y = pickle.loads(pickle.dumps(x))
2664 vereq(y.a + y.b, 142)
2665 y = cPickle.loads(cPickle.dumps(x))
2666 vereq(y.a + y.b, 142)
2667 # But a subclass that adds a slot should not work
2668 class E(C):
2669 __slots__ = ['b']
2670 try:
2671 pickle.dumps(E())
2672 except TypeError:
2673 pass
2674 else:
2675 raise TestFailed, "should fail: pickle E instance - %s" % base
2676 try:
2677 cPickle.dumps(E())
2678 except TypeError:
2679 pass
2680 else:
2681 raise TestFailed, "should fail: cPickle E instance - %s" % base
2683 def copies():
2684 if verbose: print "Testing copy.copy() and copy.deepcopy()..."
2685 import copy
2686 class C(object):
2687 pass
2689 a = C()
2690 a.foo = 12
2691 b = copy.copy(a)
2692 vereq(b.__dict__, a.__dict__)
2694 a.bar = [1,2,3]
2695 c = copy.copy(a)
2696 vereq(c.bar, a.bar)
2697 verify(c.bar is a.bar)
2699 d = copy.deepcopy(a)
2700 vereq(d.__dict__, a.__dict__)
2701 a.bar.append(4)
2702 vereq(d.bar, [1,2,3])
2704 def binopoverride():
2705 if verbose: print "Testing overrides of binary operations..."
2706 class I(int):
2707 def __repr__(self):
2708 return "I(%r)" % int(self)
2709 def __add__(self, other):
2710 return I(int(self) + int(other))
2711 __radd__ = __add__
2712 def __pow__(self, other, mod=None):
2713 if mod is None:
2714 return I(pow(int(self), int(other)))
2715 else:
2716 return I(pow(int(self), int(other), int(mod)))
2717 def __rpow__(self, other, mod=None):
2718 if mod is None:
2719 return I(pow(int(other), int(self), mod))
2720 else:
2721 return I(pow(int(other), int(self), int(mod)))
2723 vereq(`I(1) + I(2)`, "I(3)")
2724 vereq(`I(1) + 2`, "I(3)")
2725 vereq(`1 + I(2)`, "I(3)")
2726 vereq(`I(2) ** I(3)`, "I(8)")
2727 vereq(`2 ** I(3)`, "I(8)")
2728 vereq(`I(2) ** 3`, "I(8)")
2729 vereq(`pow(I(2), I(3), I(5))`, "I(3)")
2730 class S(str):
2731 def __eq__(self, other):
2732 return self.lower() == other.lower()
2734 def subclasspropagation():
2735 if verbose: print "Testing propagation of slot functions to subclasses..."
2736 class A(object):
2737 pass
2738 class B(A):
2739 pass
2740 class C(A):
2741 pass
2742 class D(B, C):
2743 pass
2744 d = D()
2745 vereq(hash(d), id(d))
2746 A.__hash__ = lambda self: 42
2747 vereq(hash(d), 42)
2748 C.__hash__ = lambda self: 314
2749 vereq(hash(d), 314)
2750 B.__hash__ = lambda self: 144
2751 vereq(hash(d), 144)
2752 D.__hash__ = lambda self: 100
2753 vereq(hash(d), 100)
2754 del D.__hash__
2755 vereq(hash(d), 144)
2756 del B.__hash__
2757 vereq(hash(d), 314)
2758 del C.__hash__
2759 vereq(hash(d), 42)
2760 del A.__hash__
2761 vereq(hash(d), id(d))
2762 d.foo = 42
2763 d.bar = 42
2764 vereq(d.foo, 42)
2765 vereq(d.bar, 42)
2766 def __getattribute__(self, name):
2767 if name == "foo":
2768 return 24
2769 return object.__getattribute__(self, name)
2770 A.__getattribute__ = __getattribute__
2771 vereq(d.foo, 24)
2772 vereq(d.bar, 42)
2773 def __getattr__(self, name):
2774 if name in ("spam", "foo", "bar"):
2775 return "hello"
2776 raise AttributeError, name
2777 B.__getattr__ = __getattr__
2778 vereq(d.spam, "hello")
2779 vereq(d.foo, 24)
2780 vereq(d.bar, 42)
2781 del A.__getattribute__
2782 vereq(d.foo, 42)
2783 del d.foo
2784 vereq(d.foo, "hello")
2785 vereq(d.bar, 42)
2786 del B.__getattr__
2787 try:
2788 d.foo
2789 except AttributeError:
2790 pass
2791 else:
2792 raise TestFailed, "d.foo should be undefined now"
2794 # Test a nasty bug in recurse_down_subclasses()
2795 import gc
2796 class A(object):
2797 pass
2798 class B(A):
2799 pass
2800 del B
2801 gc.collect()
2802 A.__setitem__ = lambda *a: None # crash
2804 def buffer_inherit():
2805 import binascii
2806 # SF bug [#470040] ParseTuple t# vs subclasses.
2807 if verbose:
2808 print "Testing that buffer interface is inherited ..."
2810 class MyStr(str):
2811 pass
2812 base = 'abc'
2813 m = MyStr(base)
2814 # b2a_hex uses the buffer interface to get its argument's value, via
2815 # PyArg_ParseTuple 't#' code.
2816 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
2818 # It's not clear that unicode will continue to support the character
2819 # buffer interface, and this test will fail if that's taken away.
2820 class MyUni(unicode):
2821 pass
2822 base = u'abc'
2823 m = MyUni(base)
2824 vereq(binascii.b2a_hex(m), binascii.b2a_hex(base))
2826 class MyInt(int):
2827 pass
2828 m = MyInt(42)
2829 try:
2830 binascii.b2a_hex(m)
2831 raise TestFailed('subclass of int should not have a buffer interface')
2832 except TypeError:
2833 pass
2835 def str_of_str_subclass():
2836 import binascii
2837 import cStringIO
2839 if verbose:
2840 print "Testing __str__ defined in subclass of str ..."
2842 class octetstring(str):
2843 def __str__(self):
2844 return binascii.b2a_hex(self)
2845 def __repr__(self):
2846 return self + " repr"
2848 o = octetstring('A')
2849 vereq(type(o), octetstring)
2850 vereq(type(str(o)), str)
2851 vereq(type(repr(o)), str)
2852 vereq(ord(o), 0x41)
2853 vereq(str(o), '41')
2854 vereq(repr(o), 'A repr')
2855 vereq(o.__str__(), '41')
2856 vereq(o.__repr__(), 'A repr')
2858 capture = cStringIO.StringIO()
2859 # Calling str() or not exercises different internal paths.
2860 print >> capture, o
2861 print >> capture, str(o)
2862 vereq(capture.getvalue(), '41\n41\n')
2863 capture.close()
2865 def kwdargs():
2866 if verbose: print "Testing keyword arguments to __init__, __call__..."
2867 def f(a): return a
2868 vereq(f.__call__(a=42), 42)
2869 a = []
2870 list.__init__(a, sequence=[0, 1, 2])
2871 vereq(a, [0, 1, 2])
2873 def delhook():
2874 if verbose: print "Testing __del__ hook..."
2875 log = []
2876 class C(object):
2877 def __del__(self):
2878 log.append(1)
2879 c = C()
2880 vereq(log, [])
2881 del c
2882 vereq(log, [1])
2884 class D(object): pass
2885 d = D()
2886 try: del d[0]
2887 except TypeError: pass
2888 else: raise TestFailed, "invalid del() didn't raise TypeError"
2890 def hashinherit():
2891 if verbose: print "Testing hash of mutable subclasses..."
2893 class mydict(dict):
2894 pass
2895 d = mydict()
2896 try:
2897 hash(d)
2898 except TypeError:
2899 pass
2900 else:
2901 raise TestFailed, "hash() of dict subclass should fail"
2903 class mylist(list):
2904 pass
2905 d = mylist()
2906 try:
2907 hash(d)
2908 except TypeError:
2909 pass
2910 else:
2911 raise TestFailed, "hash() of list subclass should fail"
2913 def strops():
2914 try: 'a' + 5
2915 except TypeError: pass
2916 else: raise TestFailed, "'' + 5 doesn't raise TypeError"
2918 try: ''.split('')
2919 except ValueError: pass
2920 else: raise TestFailed, "''.split('') doesn't raise ValueError"
2922 try: ''.join([0])
2923 except TypeError: pass
2924 else: raise TestFailed, "''.join([0]) doesn't raise TypeError"
2926 try: ''.rindex('5')
2927 except ValueError: pass
2928 else: raise TestFailed, "''.rindex('5') doesn't raise ValueError"
2930 try: ''.replace('', '')
2931 except ValueError: pass
2932 else: raise TestFailed, "''.replace('', '') doesn't raise ValueError"
2934 try: '%(n)s' % None
2935 except TypeError: pass
2936 else: raise TestFailed, "'%(n)s' % None doesn't raise TypeError"
2938 try: '%(n' % {}
2939 except ValueError: pass
2940 else: raise TestFailed, "'%(n' % {} '' doesn't raise ValueError"
2942 try: '%*s' % ('abc')
2943 except TypeError: pass
2944 else: raise TestFailed, "'%*s' % ('abc') doesn't raise TypeError"
2946 try: '%*.*s' % ('abc', 5)
2947 except TypeError: pass
2948 else: raise TestFailed, "'%*.*s' % ('abc', 5) doesn't raise TypeError"
2950 try: '%s' % (1, 2)
2951 except TypeError: pass
2952 else: raise TestFailed, "'%s' % (1, 2) doesn't raise TypeError"
2954 try: '%' % None
2955 except ValueError: pass
2956 else: raise TestFailed, "'%' % None doesn't raise ValueError"
2958 vereq('534253'.isdigit(), 1)
2959 vereq('534253x'.isdigit(), 0)
2960 vereq('%c' % 5, '\x05')
2961 vereq('%c' % '5', '5')
2963 def deepcopyrecursive():
2964 if verbose: print "Testing deepcopy of recursive objects..."
2965 class Node:
2966 pass
2967 a = Node()
2968 b = Node()
2969 a.b = b
2970 b.a = a
2971 z = deepcopy(a) # This blew up before
2973 def modules():
2974 if verbose: print "Testing uninitialized module objects..."
2975 from types import ModuleType as M
2976 m = M.__new__(M)
2977 str(m)
2978 vereq(hasattr(m, "__name__"), 0)
2979 vereq(hasattr(m, "__file__"), 0)
2980 vereq(hasattr(m, "foo"), 0)
2981 vereq(m.__dict__, None)
2982 m.foo = 1
2983 vereq(m.__dict__, {"foo": 1})
2985 def dictproxyiterkeys():
2986 class C(object):
2987 def meth(self):
2988 pass
2989 if verbose: print "Testing dict-proxy iterkeys..."
2990 keys = [ key for key in C.__dict__.iterkeys() ]
2991 keys.sort()
2992 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
2994 def dictproxyitervalues():
2995 class C(object):
2996 def meth(self):
2997 pass
2998 if verbose: print "Testing dict-proxy itervalues..."
2999 values = [ values for values in C.__dict__.itervalues() ]
3000 vereq(len(values), 5)
3002 def dictproxyiteritems():
3003 class C(object):
3004 def meth(self):
3005 pass
3006 if verbose: print "Testing dict-proxy iteritems..."
3007 keys = [ key for (key, value) in C.__dict__.iteritems() ]
3008 keys.sort()
3009 vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
3011 def funnynew():
3012 if verbose: print "Testing __new__ returning something unexpected..."
3013 class C(object):
3014 def __new__(cls, arg):
3015 if isinstance(arg, str): return [1, 2, 3]
3016 elif isinstance(arg, int): return object.__new__(D)
3017 else: return object.__new__(cls)
3018 class D(C):
3019 def __init__(self, arg):
3020 self.foo = arg
3021 vereq(C("1"), [1, 2, 3])
3022 vereq(D("1"), [1, 2, 3])
3023 d = D(None)
3024 veris(d.foo, None)
3025 d = C(1)
3026 vereq(isinstance(d, D), True)
3027 vereq(d.foo, 1)
3028 d = D(1)
3029 vereq(isinstance(d, D), True)
3030 vereq(d.foo, 1)
3032 def imulbug():
3033 # SF bug 544647
3034 if verbose: print "Testing for __imul__ problems..."
3035 class C(object):
3036 def __imul__(self, other):
3037 return (self, other)
3038 x = C()
3039 y = x
3040 y *= 1.0
3041 vereq(y, (x, 1.0))
3042 y = x
3043 y *= 2
3044 vereq(y, (x, 2))
3045 y = x
3046 y *= 3L
3047 vereq(y, (x, 3L))
3048 y = x
3049 y *= 1L<<100
3050 vereq(y, (x, 1L<<100))
3051 y = x
3052 y *= None
3053 vereq(y, (x, None))
3054 y = x
3055 y *= "foo"
3056 vereq(y, (x, "foo"))
3058 def docdescriptor():
3059 # SF bug 542984
3060 if verbose: print "Testing __doc__ descriptor..."
3061 class DocDescr(object):
3062 def __get__(self, object, otype):
3063 if object:
3064 object = object.__class__.__name__ + ' instance'
3065 if otype:
3066 otype = otype.__name__
3067 return 'object=%s; type=%s' % (object, otype)
3068 class OldClass:
3069 __doc__ = DocDescr()
3070 class NewClass(object):
3071 __doc__ = DocDescr()
3072 vereq(OldClass.__doc__, 'object=None; type=OldClass')
3073 vereq(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3074 vereq(NewClass.__doc__, 'object=None; type=NewClass')
3075 vereq(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3077 def string_exceptions():
3078 if verbose:
3079 print "Testing string exceptions ..."
3081 # Ensure builtin strings work OK as exceptions.
3082 astring = "An exception string."
3083 try:
3084 raise astring
3085 except astring:
3086 pass
3087 else:
3088 raise TestFailed, "builtin string not usable as exception"
3090 # Ensure string subclass instances do not.
3091 class MyStr(str):
3092 pass
3094 newstring = MyStr("oops -- shouldn't work")
3095 try:
3096 raise newstring
3097 except TypeError:
3098 pass
3099 except:
3100 raise TestFailed, "string subclass allowed as exception"
3102 def copy_setstate():
3103 if verbose:
3104 print "Testing that copy.*copy() correctly uses __setstate__..."
3105 import copy
3106 class C(object):
3107 def __init__(self, foo=None):
3108 self.foo = foo
3109 self.__foo = foo
3110 def setfoo(self, foo=None):
3111 self.foo = foo
3112 def getfoo(self):
3113 return self.__foo
3114 def __getstate__(self):
3115 return [self.foo]
3116 def __setstate__(self, lst):
3117 assert len(lst) == 1
3118 self.__foo = self.foo = lst[0]
3119 a = C(42)
3120 a.setfoo(24)
3121 vereq(a.foo, 24)
3122 vereq(a.getfoo(), 42)
3123 b = copy.copy(a)
3124 vereq(b.foo, 24)
3125 vereq(b.getfoo(), 24)
3126 b = copy.deepcopy(a)
3127 vereq(b.foo, 24)
3128 vereq(b.getfoo(), 24)
3130 def slices():
3131 if verbose:
3132 print "Testing cases with slices and overridden __getitem__ ..."
3133 # Strings
3134 vereq("hello"[:4], "hell")
3135 vereq("hello"[slice(4)], "hell")
3136 vereq(str.__getitem__("hello", slice(4)), "hell")
3137 class S(str):
3138 def __getitem__(self, x):
3139 return str.__getitem__(self, x)
3140 vereq(S("hello")[:4], "hell")
3141 vereq(S("hello")[slice(4)], "hell")
3142 vereq(S("hello").__getitem__(slice(4)), "hell")
3143 # Tuples
3144 vereq((1,2,3)[:2], (1,2))
3145 vereq((1,2,3)[slice(2)], (1,2))
3146 vereq(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3147 class T(tuple):
3148 def __getitem__(self, x):
3149 return tuple.__getitem__(self, x)
3150 vereq(T((1,2,3))[:2], (1,2))
3151 vereq(T((1,2,3))[slice(2)], (1,2))
3152 vereq(T((1,2,3)).__getitem__(slice(2)), (1,2))
3153 # Lists
3154 vereq([1,2,3][:2], [1,2])
3155 vereq([1,2,3][slice(2)], [1,2])
3156 vereq(list.__getitem__([1,2,3], slice(2)), [1,2])
3157 class L(list):
3158 def __getitem__(self, x):
3159 return list.__getitem__(self, x)
3160 vereq(L([1,2,3])[:2], [1,2])
3161 vereq(L([1,2,3])[slice(2)], [1,2])
3162 vereq(L([1,2,3]).__getitem__(slice(2)), [1,2])
3163 # Now do lists and __setitem__
3164 a = L([1,2,3])
3165 a[slice(1, 3)] = [3,2]
3166 vereq(a, [1,3,2])
3167 a[slice(0, 2, 1)] = [3,1]
3168 vereq(a, [3,1,2])
3169 a.__setitem__(slice(1, 3), [2,1])
3170 vereq(a, [3,2,1])
3171 a.__setitem__(slice(0, 2, 1), [2,3])
3172 vereq(a, [2,3,1])
3175 def do_this_first():
3176 if verbose:
3177 print "Testing SF bug 551412 ..."
3178 # This dumps core when SF bug 551412 isn't fixed --
3179 # but only when test_descr.py is run separately.
3180 # (That can't be helped -- as soon as PyType_Ready()
3181 # is called for PyLong_Type, the bug is gone.)
3182 class UserLong(object):
3183 def __pow__(self, *args):
3184 pass
3185 try:
3186 pow(0L, UserLong(), 0L)
3187 except:
3188 pass
3190 if verbose:
3191 print "Testing SF bug 570483..."
3192 # Another segfault only when run early
3193 # (before PyType_Ready(tuple) is called)
3194 type.mro(tuple)
3196 def test_main():
3197 do_this_first()
3198 class_docstrings()
3199 lists()
3200 dicts()
3201 dict_constructor()
3202 test_dir()
3203 ints()
3204 longs()
3205 floats()
3206 complexes()
3207 spamlists()
3208 spamdicts()
3209 pydicts()
3210 pylists()
3211 metaclass()
3212 pymods()
3213 multi()
3214 diamond()
3215 objects()
3216 slots()
3217 dynamics()
3218 errors()
3219 classmethods()
3220 classmethods_in_c()
3221 staticmethods()
3222 staticmethods_in_c()
3223 classic()
3224 compattr()
3225 newslot()
3226 altmro()
3227 overloading()
3228 methods()
3229 specials()
3230 weakrefs()
3231 properties()
3232 supers()
3233 inherits()
3234 keywords()
3235 restricted()
3236 str_subclass_as_dict_key()
3237 classic_comparisons()
3238 rich_comparisons()
3239 coercions()
3240 descrdoc()
3241 setclass()
3242 setdict()
3243 pickles()
3244 copies()
3245 binopoverride()
3246 subclasspropagation()
3247 buffer_inherit()
3248 str_of_str_subclass()
3249 kwdargs()
3250 delhook()
3251 hashinherit()
3252 strops()
3253 deepcopyrecursive()
3254 modules()
3255 dictproxyiterkeys()
3256 dictproxyitervalues()
3257 dictproxyiteritems()
3258 pickleslots()
3259 funnynew()
3260 imulbug()
3261 docdescriptor()
3262 string_exceptions()
3263 copy_setstate()
3264 slices()
3265 if verbose: print "All OK"
3267 if __name__ == "__main__":
3268 test_main()